Code

Only create the faces of a 3D box when needed (use pointers to refer to them).
[inkscape.git] / src / box3d-context.cpp
1 #define __SP_3DBOX_CONTEXT_C__
3 /*
4  * 3D box drawing context
5  *
6  * Author:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   bulia byak <buliabyak@users.sf.net>
9  *
10  * Copyright (C) 2007      Maximilian Albert <Anhalter42@gmx.de>
11  * Copyright (C) 2006      Johan Engelen <johan@shouraizou.nl>
12  * Copyright (C) 2000-2005 authors
13  * Copyright (C) 2000-2001 Ximian, Inc.
14  *
15  * Released under GNU GPL, read the file 'COPYING' for more information
16  */
18 #include "config.h"
20 #include <gdk/gdkkeysyms.h>
22 #include "macros.h"
23 #include "display/sp-canvas.h"
24 #include "document.h"
25 #include "sp-namedview.h"
26 #include "selection.h"
27 #include "desktop-handles.h"
28 #include "snap.h"
29 #include "display/curve.h"
30 #include "desktop.h"
31 #include "message-context.h"
32 #include "pixmaps/cursor-rect.xpm"
33 #include "box3d.h"
34 #include "box3d-context.h"
35 #include "sp-metrics.h"
36 #include <glibmm/i18n.h>
37 #include "object-edit.h"
38 #include "xml/repr.h"
39 #include "xml/node-event-vector.h"
40 #include "prefs-utils.h"
41 #include "context-fns.h"
43 static void sp_3dbox_context_class_init(SP3DBoxContextClass *klass);
44 static void sp_3dbox_context_init(SP3DBoxContext *box3d_context);
45 static void sp_3dbox_context_dispose(GObject *object);
47 static void sp_3dbox_context_setup(SPEventContext *ec);
48 static void sp_3dbox_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
50 static gint sp_3dbox_context_root_handler(SPEventContext *event_context, GdkEvent *event);
51 static gint sp_3dbox_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event);
53 static void sp_3dbox_drag(SP3DBoxContext &rc, guint state);
54 static void sp_3dbox_finish(SP3DBoxContext *rc);
56 static SPEventContextClass *parent_class;
59 GtkType sp_3dbox_context_get_type()
60 {
61     static GType type = 0;
62     if (!type) {
63         GTypeInfo info = {
64             sizeof(SP3DBoxContextClass),
65             NULL, NULL,
66             (GClassInitFunc) sp_3dbox_context_class_init,
67             NULL, NULL,
68             sizeof(SP3DBoxContext),
69             4,
70             (GInstanceInitFunc) sp_3dbox_context_init,
71             NULL,    /* value_table */
72         };
73         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SP3DBoxContext", &info, (GTypeFlags) 0);
74     }
75     return type;
76 }
78 static void sp_3dbox_context_class_init(SP3DBoxContextClass *klass)
79 {
80     GObjectClass *object_class = (GObjectClass *) klass;
81     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
83     parent_class = (SPEventContextClass *) g_type_class_peek_parent(klass);
85     object_class->dispose = sp_3dbox_context_dispose;
87     event_context_class->setup = sp_3dbox_context_setup;
88     event_context_class->set = sp_3dbox_context_set;
89     event_context_class->root_handler  = sp_3dbox_context_root_handler;
90     event_context_class->item_handler  = sp_3dbox_context_item_handler;
91 }
93 Box3D::Perspective3D * SP3DBoxContext::current_perspective = NULL;
95 static void sp_3dbox_context_init(SP3DBoxContext *box3d_context)
96 {
97     SPEventContext *event_context = SP_EVENT_CONTEXT(box3d_context);
99     event_context->cursor_shape = cursor_rect_xpm;
100     event_context->hot_x = 4;
101     event_context->hot_y = 4;
102     event_context->xp = 0;
103     event_context->yp = 0;
104     event_context->tolerance = 0;
105     event_context->within_tolerance = false;
106     event_context->item_to_select = NULL;
108     event_context->shape_repr = NULL;
109     event_context->shape_knot_holder = NULL;
111     box3d_context->item = NULL;
113     box3d_context->rx = 0.0;
114     box3d_context->ry = 0.0;
116     box3d_context->ctrl_dragged = false;
117     box3d_context->extruded = false;
119     /* create an initial perspective */
120     if (!SP3DBoxContext::current_perspective) {
121         SP3DBoxContext::current_perspective = new Box3D::Perspective3D (
122                                               // VP in x-direction
123                                               Box3D::VanishingPoint( NR::Point( 50.0, 600.0),
124                                                                      NR::Point( -1.0,   0.0), Box3D::VP_INFINITE),
125                                               // VP in y-direction
126                                               Box3D::VanishingPoint( NR::Point(500.0,1000.0),
127                                                                      NR::Point(  0.0,   1.0), Box3D::VP_INFINITE),
128                                               // VP in z-direction
129                                               Box3D::VanishingPoint( NR::Point(700.0, 500.0),
130                                                                      NR::Point(sqrt(3.0),1.0), Box3D::VP_INFINITE));
131     }
132     
133     new (&box3d_context->sel_changed_connection) sigc::connection();
136 static void sp_3dbox_context_dispose(GObject *object)
138     SP3DBoxContext *rc = SP_3DBOX_CONTEXT(object);
139     SPEventContext *ec = SP_EVENT_CONTEXT(object);
141     ec->enableGrDrag(false);
143     rc->sel_changed_connection.disconnect();
144     rc->sel_changed_connection.~connection();
146     /* fixme: This is necessary because we do not grab */
147     if (rc->item) {
148         sp_3dbox_finish(rc);
149     }
151     if (ec->shape_knot_holder) {
152         sp_knot_holder_destroy(ec->shape_knot_holder);
153         ec->shape_knot_holder = NULL;
154     }
156     if (ec->shape_repr) { // remove old listener
157         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
158         Inkscape::GC::release(ec->shape_repr);
159         ec->shape_repr = 0;
160     }
162     if (rc->_message_context) {
163         delete rc->_message_context;
164     }
166     G_OBJECT_CLASS(parent_class)->dispose(object);
169 static Inkscape::XML::NodeEventVector ec_shape_repr_events = {
170     NULL, /* child_added */
171     NULL, /* child_removed */
172     ec_shape_event_attr_changed,
173     NULL, /* content_changed */
174     NULL  /* order_changed */
175 };
177 /**
178 \brief  Callback that processes the "changed" signal on the selection;
179 destroys old and creates new knotholder
180 */
181 void sp_3dbox_context_selection_changed(Inkscape::Selection *selection, gpointer data)
183     SP3DBoxContext *rc = SP_3DBOX_CONTEXT(data);
184     SPEventContext *ec = SP_EVENT_CONTEXT(rc);
186     if (ec->shape_knot_holder) { // destroy knotholder
187         sp_knot_holder_destroy(ec->shape_knot_holder);
188         ec->shape_knot_holder = NULL;
189     }
191     if (ec->shape_repr) { // remove old listener
192         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
193         Inkscape::GC::release(ec->shape_repr);
194         ec->shape_repr = 0;
195     }
197     SPItem *item = selection->singleItem();
198     if (item) {
199         ec->shape_knot_holder = sp_item_knot_holder(item, ec->desktop);
200         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
201         if (shape_repr) {
202             ec->shape_repr = shape_repr;
203             Inkscape::GC::anchor(shape_repr);
204             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
205         }
206     }
209 static void sp_3dbox_context_setup(SPEventContext *ec)
211     SP3DBoxContext *rc = SP_3DBOX_CONTEXT(ec);
213     if (((SPEventContextClass *) parent_class)->setup) {
214         ((SPEventContextClass *) parent_class)->setup(ec);
215     }
217     SPItem *item = sp_desktop_selection(ec->desktop)->singleItem();
218     if (item) {
219         ec->shape_knot_holder = sp_item_knot_holder(item, ec->desktop);
220         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
221         if (shape_repr) {
222             ec->shape_repr = shape_repr;
223             Inkscape::GC::anchor(shape_repr);
224             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
225         }
226     }
228     rc->sel_changed_connection.disconnect();
229     rc->sel_changed_connection = sp_desktop_selection(ec->desktop)->connectChanged(
230         sigc::bind(sigc::ptr_fun(&sp_3dbox_context_selection_changed), (gpointer)rc)
231     );
233     sp_event_context_read(ec, "rx");
234     sp_event_context_read(ec, "ry");
236     if (prefs_get_int_attribute("tools.shapes", "selcue", 0) != 0) {
237         ec->enableSelectionCue();
238     }
240     if (prefs_get_int_attribute("tools.shapes", "gradientdrag", 0) != 0) {
241         ec->enableGrDrag();
242     }
244     rc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
247 static void sp_3dbox_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
249     SP3DBoxContext *rc = SP_3DBOX_CONTEXT(ec);
251     /* fixme: Proper error handling for non-numeric data.  Use a locale-independent function like
252      * g_ascii_strtod (or a thin wrapper that does the right thing for invalid values inf/nan). */
253     if ( strcmp(key, "rx") == 0 ) {
254         rc->rx = ( val
255                          ? g_ascii_strtod (val, NULL)
256                          : 0.0 );
257     } else if ( strcmp(key, "ry") == 0 ) {
258         rc->ry = ( val
259                          ? g_ascii_strtod (val, NULL)
260                          : 0.0 );
261     }
264 static gint sp_3dbox_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
266     SPDesktop *desktop = event_context->desktop;
268     gint ret = FALSE;
270     switch (event->type) {
271     case GDK_BUTTON_PRESS:
272         if ( event->button.button == 1 ) {
273             Inkscape::setup_for_drag_start(desktop, event_context, event);
274             ret = TRUE;
275         }
276         break;
277         // motion and release are always on root (why?)
278     default:
279         break;
280     }
282     if (((SPEventContextClass *) parent_class)->item_handler) {
283         ret = ((SPEventContextClass *) parent_class)->item_handler(event_context, item, event);
284     }
286     return ret;
289 static gint sp_3dbox_context_root_handler(SPEventContext *event_context, GdkEvent *event)
291     static bool dragging;
293     SPDesktop *desktop = event_context->desktop;
294     Inkscape::Selection *selection = sp_desktop_selection (desktop);
296     SP3DBoxContext *rc = SP_3DBOX_CONTEXT(event_context);
298     event_context->tolerance = prefs_get_int_attribute_limited("options.dragtolerance", "value", 0, 0, 100);
300     gint ret = FALSE;
301     switch (event->type) {
302     case GDK_BUTTON_PRESS:
303         if ( event->button.button == 1 ) {
304             NR::Point const button_w(event->button.x,
305                                      event->button.y);
307             // save drag origin
308             event_context->xp = (gint) button_w[NR::X];
309             event_context->yp = (gint) button_w[NR::Y];
310             event_context->within_tolerance = true;
311             
312             // remember clicked item, disregarding groups, honoring Alt
313             event_context->item_to_select = sp_event_context_find_item (desktop, button_w, event->button.state & GDK_MOD1_MASK, TRUE);
315             dragging = true;
316             
317             /* Position center */
318             NR::Point const button_dt(desktop->w2d(button_w));
319             rc->drag_origin = button_dt;
320             rc->drag_ptB = button_dt;
321             rc->drag_ptC = button_dt;
323             /* Snap center */
324             SnapManager const &m = desktop->namedview->snap_manager;
325             rc->center = m.freeSnap(Inkscape::Snapper::SNAP_POINT | Inkscape::Snapper::BBOX_POINT,
326                                     button_dt, rc->item).getPoint();
328             sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
329                                 ( GDK_KEY_PRESS_MASK |
330                                   GDK_BUTTON_RELEASE_MASK       |
331                                   GDK_POINTER_MOTION_MASK       |
332                                   GDK_BUTTON_PRESS_MASK ),
333                                 NULL, event->button.time);
334             ret = TRUE;
335         }
336         break;
337     case GDK_MOTION_NOTIFY:
338         if ( dragging
339              && ( event->motion.state & GDK_BUTTON1_MASK ) )
340         {
341             if ( event_context->within_tolerance
342                  && ( abs( (gint) event->motion.x - event_context->xp ) < event_context->tolerance )
343                  && ( abs( (gint) event->motion.y - event_context->yp ) < event_context->tolerance ) ) {
344                 break; // do not drag if we're within tolerance from origin
345             }
346             // Once the user has moved farther than tolerance from the original location
347             // (indicating they intend to draw, not click), then always process the
348             // motion notify coordinates as given (no snapping back to origin)
349             event_context->within_tolerance = false;
351             NR::Point const motion_w(event->motion.x,
352                                      event->motion.y);
353             NR::Point motion_dt(desktop->w2d(motion_w));
355             SnapManager const &m = desktop->namedview->snap_manager;
356             motion_dt = m.freeSnap(Inkscape::Snapper::BBOX_POINT | Inkscape::Snapper::SNAP_POINT, motion_dt, rc->item).getPoint();
358             rc->ctrl_dragged  = event->motion.state & GDK_CONTROL_MASK;
360             if (event->motion.state & GDK_SHIFT_MASK && !rc->extruded) {
361                 /* once shift is pressed, set rc->extruded and create the remaining faces */
362                 rc->extruded = true;
363                 
364                 /* The separate faces */
365                 SP3DBox *box3d = SP_3DBOX(rc->item);
366                 for (int i = 0; i < 6; ++i) {
367                     if (i == 4 || box3d->faces[i]) continue;
368                     box3d->faces[i] = new Box3DFace (box3d);
369                     box3d->faces[i]->hook_path_to_3dbox();
370                 }
371             }
373             if (!rc->extruded) {
374                 rc->drag_ptB = motion_dt;
375             } else {
376                 // Without Ctrl, motion of the extruded corner is constrained to the
377                 // perspective line from drag_ptB to vanishing point Y.
378                 if (!rc->ctrl_dragged) {
379                         rc->drag_ptC = Box3D::perspective_line_snap (rc->drag_ptB, Box3D::Z, motion_dt);
380                 } else {
381                     rc->drag_ptC = motion_dt;
382                 }
383                 rc->drag_ptC = m.freeSnap(Inkscape::Snapper::BBOX_POINT | Inkscape::Snapper::SNAP_POINT, rc->drag_ptC, rc->item).getPoint();
384                 if (rc->ctrl_dragged) {
385                         Box3D::PerspectiveLine pl1 (NR::Point (event_context->xp, event_context->yp), Box3D::Y);
386                         Box3D::PerspectiveLine pl2 (rc->drag_ptB, Box3D::X);
387                         NR::Point corner1 = pl1.meet(pl2);
388                         
389                         Box3D::PerspectiveLine pl3 (corner1, Box3D::X);
390                         Box3D::PerspectiveLine pl4 (rc->drag_ptC, Box3D::Z);
391                         rc->drag_ptB = pl3.meet(pl4);
392                 }
393             }
394             
395             
396             sp_3dbox_drag(*rc, event->motion.state);
397             
398             ret = TRUE;
399         }
400         ret = TRUE;
401         break;
402     case GDK_BUTTON_RELEASE:
403         event_context->xp = event_context->yp = 0;
404         if ( event->button.button == 1 ) {
405             dragging = false;
407             if (!event_context->within_tolerance) {
408                 // we've been dragging, finish the rect
409                 sp_3dbox_finish(rc);
410             } else if (event_context->item_to_select) {
411                 // no dragging, select clicked item if any
412                 if (event->button.state & GDK_SHIFT_MASK) {
413                     selection->toggle(event_context->item_to_select);
414                 } else {
415                     selection->set(event_context->item_to_select);
416                 }
417             } else {
418                 // click in an empty space
419                 selection->clear();
420             }
422             event_context->item_to_select = NULL;
423             ret = TRUE;
424             sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate),
425                                   event->button.time);
426         }
427         break;
428     case GDK_KEY_PRESS:
429         switch (get_group0_keyval (&event->key)) {
430         case GDK_Alt_L:
431         case GDK_Alt_R:
432         case GDK_Control_L:
433         case GDK_Control_R:
434         case GDK_Shift_L:
435         case GDK_Shift_R:
436         case GDK_Meta_L:  // Meta is when you press Shift+Alt (at least on my machine)
437         case GDK_Meta_R:
438             if (!dragging){
439                 sp_event_show_modifier_tip (event_context->defaultMessageContext(), event,
440                                             _("<b>Ctrl</b>: make square or integer-ratio rect, lock a rounded corner circular"),
441                                             _("<b>Shift</b>: draw around the starting point"),
442                                             NULL);
443             }
444             break;
445         case GDK_Up:
446         case GDK_Down:
447         case GDK_KP_Up:
448         case GDK_KP_Down:
449             // prevent the zoom field from activation
450             if (!MOD__CTRL_ONLY)
451                 ret = TRUE;
452             break;
454         case GDK_x:
455         case GDK_X:
456             if (MOD__ALT_ONLY) {
457                 desktop->setToolboxFocusTo ("altx-rect");
458                 ret = TRUE;
459             }
460             break;
462         case GDK_Escape:
463             sp_desktop_selection(desktop)->clear();
464             //TODO: make dragging escapable by Esc
465             break;
467         case GDK_space:
468             if (dragging) {
469                 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate),
470                                       event->button.time);
471                 dragging = false;
472                 if (!event_context->within_tolerance) {
473                     // we've been dragging, finish the rect
474                     sp_3dbox_finish(rc);
475                 }
476                 // do not return true, so that space would work switching to selector
477             }
478             break;
480         default:
481             break;
482         }
483         break;
484     case GDK_KEY_RELEASE:
485         switch (get_group0_keyval (&event->key)) {
486         case GDK_Alt_L:
487         case GDK_Alt_R:
488         case GDK_Control_L:
489         case GDK_Control_R:
490         case GDK_Shift_L:
491         case GDK_Shift_R:
492         case GDK_Meta_L:  // Meta is when you press Shift+Alt
493         case GDK_Meta_R:
494             event_context->defaultMessageContext()->clear();
495             break;
496         default:
497             break;
498         }
499         break;
500     default:
501         break;
502     }
504     if (!ret) {
505         if (((SPEventContextClass *) parent_class)->root_handler) {
506             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
507         }
508     }
510     return ret;
513 static void sp_3dbox_drag(SP3DBoxContext &rc, guint state)
515     SPDesktop *desktop = SP_EVENT_CONTEXT(&rc)->desktop;
517     if (!rc.item) {
519         if (Inkscape::have_viable_layer(desktop, rc._message_context) == false) {
520             return;
521         }
523         /* Create object */
524         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(SP_EVENT_CONTEXT_DOCUMENT(&rc));
525         Inkscape::XML::Node *repr = xml_doc->createElement("svg:g");
526         repr->setAttribute("sodipodi:type", "inkscape:3dbox");
528         /* Set style */
529         //sp_desktop_apply_style_tool (desktop, repr, "tools.shapes.3dbox", false);
531         rc.item = (SPItem *) desktop->currentLayer()->appendChildRepr(repr);
532         Inkscape::GC::release(repr);
533         rc.item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
535         /* Hook path to the only currenctly existing face */
536         SP_3DBOX(rc.item)->faces[4]->hook_path_to_3dbox();
538         rc.item->updateRepr();
540         sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 5);
541     }
543     // FIXME: remove these extra points
544     NR::Point pt = rc.drag_ptB;
545     NR::Point shift_pt = rc.drag_ptC;
547     NR::Rect r;
548     if (!(state & GDK_SHIFT_MASK)) {
549         r = Inkscape::snap_rectangular_box(desktop, rc.item, pt, rc.center, state);
550     } else {
551         r = Inkscape::snap_rectangular_box(desktop, rc.item, shift_pt, rc.center, state);
552     }
554     /*** artefacts of rect ***
555     if ( rc.rx != 0.0 ) {
556         sp_3dbox_set_rx (SP_3DBOX(rc.item), TRUE, rc.rx);
557     }
558     if ( rc.ry != 0.0 ) {
559         if (rc.rx == 0.0)
560             sp_3dbox_set_ry (SP_3DBOX(rc.item), TRUE, CLAMP(rc.ry, 0, MIN(r.dimensions()[NR::X], r.dimensions()[NR::Y])/2));
561         else
562             sp_3dbox_set_ry (SP_3DBOX(rc.item), TRUE, CLAMP(rc.ry, 0, r.dimensions()[NR::Y]));
563     }
564     ***/
566     SPEventContext *ec = SP_EVENT_CONTEXT(&rc);
567     NR::Point origin_w(ec->xp, ec->yp);
568     NR::Point origin(desktop->w2d(origin_w));
569     sp_3dbox_position_set(rc);
571     // status text
572     GString *xs = SP_PX_TO_METRIC_STRING(r.dimensions()[NR::X], desktop->namedview->getDefaultMetric());
573     GString *ys = SP_PX_TO_METRIC_STRING(r.dimensions()[NR::Y], desktop->namedview->getDefaultMetric());
574     rc._message_context->setF(Inkscape::NORMAL_MESSAGE, _("<b>Rectangle</b>: %s &#215; %s; with <b>Ctrl</b> to make square or integer-ratio rectangle; with <b>Shift</b> to draw around the starting point"), xs->str, ys->str);
575     g_string_free(xs, FALSE);
576     g_string_free(ys, FALSE);
579 static void sp_3dbox_finish(SP3DBoxContext *rc)
581     rc->_message_context->clear();
583     if ( rc->item != NULL ) {
584         SPDesktop * desktop;
586         desktop = SP_EVENT_CONTEXT_DESKTOP(rc);
588         SP_OBJECT(rc->item)->updateRepr();
590         sp_canvas_end_forced_full_redraws(desktop->canvas);
592         sp_desktop_selection(desktop)->set(rc->item);
593         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_3DBOX,
594                          _("Create 3d box"));
596         rc->item = NULL;
597     }
599     rc->ctrl_dragged = false;
600     rc->extruded = false;
603 /*
604   Local Variables:
605   mode:c++
606   c-file-style:"stroustrup"
607   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
608   indent-tabs-mode:nil
609   fill-column:99
610   End:
611 */
612 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :