Code

Move all of the snapper code to 2geom
[inkscape.git] / src / rect-context.cpp
1 #define __SP_RECT_CONTEXT_C__
3 /*
4  * Rectangle drawing context
5  *
6  * Author:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   bulia byak <buliabyak@users.sf.net>
9  *
10  * Copyright (C) 2006      Johan Engelen <johan@shouraizou.nl>
11  * Copyright (C) 2000-2005 authors
12  * Copyright (C) 2000-2001 Ximian, Inc.
13  *
14  * Released under GNU GPL, read the file 'COPYING' for more information
15  */
17 #include "config.h"
18 #include "inkscape.h"
20 #include <gdk/gdkkeysyms.h>
21 #include <cstring>
22 #include <string>
24 #include "macros.h"
25 #include "display/sp-canvas.h"
26 #include "sp-rect.h"
27 #include "document.h"
28 #include "sp-namedview.h"
29 #include "selection.h"
30 #include "selection-chemistry.h"
31 #include "desktop-handles.h"
32 #include "snap.h"
33 #include "desktop.h"
34 #include "desktop-style.h"
35 #include "message-context.h"
36 #include "pixmaps/cursor-rect.xpm"
37 #include "rect-context.h"
38 #include "sp-metrics.h"
39 #include <glibmm/i18n.h>
40 #include "object-edit.h"
41 #include "xml/repr.h"
42 #include "xml/node-event-vector.h"
43 #include "prefs-utils.h"
44 #include "context-fns.h"
46 //static const double goldenratio = 1.61803398874989484820; // golden ratio
48 static void sp_rect_context_class_init(SPRectContextClass *klass);
49 static void sp_rect_context_init(SPRectContext *rect_context);
50 static void sp_rect_context_dispose(GObject *object);
52 static void sp_rect_context_setup(SPEventContext *ec);
53 static void sp_rect_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
55 static gint sp_rect_context_root_handler(SPEventContext *event_context, GdkEvent *event);
56 static gint sp_rect_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event);
58 static void sp_rect_drag(SPRectContext &rc, NR::Point const pt, guint state);
59 static void sp_rect_finish(SPRectContext *rc);
61 static SPEventContextClass *parent_class;
64 GtkType sp_rect_context_get_type()
65 {
66     static GType type = 0;
67     if (!type) {
68         GTypeInfo info = {
69             sizeof(SPRectContextClass),
70             NULL, NULL,
71             (GClassInitFunc) sp_rect_context_class_init,
72             NULL, NULL,
73             sizeof(SPRectContext),
74             4,
75             (GInstanceInitFunc) sp_rect_context_init,
76             NULL,    /* value_table */
77         };
78         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPRectContext", &info, (GTypeFlags) 0);
79     }
80     return type;
81 }
83 static void sp_rect_context_class_init(SPRectContextClass *klass)
84 {
85     GObjectClass *object_class = (GObjectClass *) klass;
86     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
88     parent_class = (SPEventContextClass *) g_type_class_peek_parent(klass);
90     object_class->dispose = sp_rect_context_dispose;
92     event_context_class->setup = sp_rect_context_setup;
93     event_context_class->set = sp_rect_context_set;
94     event_context_class->root_handler  = sp_rect_context_root_handler;
95     event_context_class->item_handler  = sp_rect_context_item_handler;
96 }
98 static void sp_rect_context_init(SPRectContext *rect_context)
99 {
100     SPEventContext *event_context = SP_EVENT_CONTEXT(rect_context);
102     event_context->cursor_shape = cursor_rect_xpm;
103     event_context->hot_x = 4;
104     event_context->hot_y = 4;
105     event_context->xp = 0;
106     event_context->yp = 0;
107     event_context->tolerance = 0;
108     event_context->within_tolerance = false;
109     event_context->item_to_select = NULL;
111     event_context->shape_repr = NULL;
112     event_context->shape_knot_holder = NULL;
114     rect_context->item = NULL;
116     rect_context->rx = 0.0;
117     rect_context->ry = 0.0;
119     new (&rect_context->sel_changed_connection) sigc::connection();
122 static void sp_rect_context_dispose(GObject *object)
124     SPRectContext *rc = SP_RECT_CONTEXT(object);
125     SPEventContext *ec = SP_EVENT_CONTEXT(object);
127     ec->enableGrDrag(false);
129     rc->sel_changed_connection.disconnect();
130     rc->sel_changed_connection.~connection();
132     /* fixme: This is necessary because we do not grab */
133     if (rc->item) {
134         sp_rect_finish(rc);
135     }
137     if (ec->shape_knot_holder) {
138         delete ec->shape_knot_holder;
139         ec->shape_knot_holder = NULL;
140     }
142     if (ec->shape_repr) { // remove old listener
143         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
144         Inkscape::GC::release(ec->shape_repr);
145         ec->shape_repr = 0;
146     }
148     if (rc->_message_context) {
149         delete rc->_message_context;
150     }
152     G_OBJECT_CLASS(parent_class)->dispose(object);
155 static Inkscape::XML::NodeEventVector ec_shape_repr_events = {
156     NULL, /* child_added */
157     NULL, /* child_removed */
158     ec_shape_event_attr_changed,
159     NULL, /* content_changed */
160     NULL  /* order_changed */
161 };
163 /**
164 \brief  Callback that processes the "changed" signal on the selection;
165 destroys old and creates new knotholder
166 */
167 void sp_rect_context_selection_changed(Inkscape::Selection *selection, gpointer data)
169     SPRectContext *rc = SP_RECT_CONTEXT(data);
170     SPEventContext *ec = SP_EVENT_CONTEXT(rc);
172     if (ec->shape_knot_holder) { // destroy knotholder
173         delete ec->shape_knot_holder;
174         ec->shape_knot_holder = NULL;
175     }
177     if (ec->shape_repr) { // remove old listener
178         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
179         Inkscape::GC::release(ec->shape_repr);
180         ec->shape_repr = 0;
181     }
183     SPItem *item = selection->singleItem();
184     if (item) {
185         ec->shape_knot_holder = sp_item_knot_holder(item, ec->desktop);
186         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
187         if (shape_repr) {
188             ec->shape_repr = shape_repr;
189             Inkscape::GC::anchor(shape_repr);
190             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
191         }
192     }
195 static void sp_rect_context_setup(SPEventContext *ec)
197     SPRectContext *rc = SP_RECT_CONTEXT(ec);
199     if (((SPEventContextClass *) parent_class)->setup) {
200         ((SPEventContextClass *) parent_class)->setup(ec);
201     }
203     SPItem *item = sp_desktop_selection(ec->desktop)->singleItem();
204     if (item) {
205         ec->shape_knot_holder = sp_item_knot_holder(item, ec->desktop);
206         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
207         if (shape_repr) {
208             ec->shape_repr = shape_repr;
209             Inkscape::GC::anchor(shape_repr);
210             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
211         }
212     }
214     rc->sel_changed_connection.disconnect();
215     rc->sel_changed_connection = sp_desktop_selection(ec->desktop)->connectChanged(
216         sigc::bind(sigc::ptr_fun(&sp_rect_context_selection_changed), (gpointer)rc)
217     );
219     sp_event_context_read(ec, "rx");
220     sp_event_context_read(ec, "ry");
222     if (prefs_get_int_attribute("tools.shapes", "selcue", 0) != 0) {
223         ec->enableSelectionCue();
224     }
226     if (prefs_get_int_attribute("tools.shapes", "gradientdrag", 0) != 0) {
227         ec->enableGrDrag();
228     }
230     rc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
233 static void sp_rect_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
235     SPRectContext *rc = SP_RECT_CONTEXT(ec);
237     /* fixme: Proper error handling for non-numeric data.  Use a locale-independent function like
238      * g_ascii_strtod (or a thin wrapper that does the right thing for invalid values inf/nan). */
239     if ( strcmp(key, "rx") == 0 ) {
240         rc->rx = ( val
241                          ? g_ascii_strtod (val, NULL)
242                          : 0.0 );
243     } else if ( strcmp(key, "ry") == 0 ) {
244         rc->ry = ( val
245                          ? g_ascii_strtod (val, NULL)
246                          : 0.0 );
247     }
250 static gint sp_rect_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
252     SPDesktop *desktop = event_context->desktop;
254     gint ret = FALSE;
256     switch (event->type) {
257     case GDK_BUTTON_PRESS:
258         if ( event->button.button == 1 && !event_context->space_panning) {
259             Inkscape::setup_for_drag_start(desktop, event_context, event);
260             ret = TRUE;
261         }
262         break;
263         // motion and release are always on root (why?)
264     default:
265         break;
266     }
268     if (((SPEventContextClass *) parent_class)->item_handler) {
269         ret = ((SPEventContextClass *) parent_class)->item_handler(event_context, item, event);
270     }
272     return ret;
275 static gint sp_rect_context_root_handler(SPEventContext *event_context, GdkEvent *event)
277     static bool dragging;
279     SPDesktop *desktop = event_context->desktop;
280     Inkscape::Selection *selection = sp_desktop_selection (desktop);
282     SPRectContext *rc = SP_RECT_CONTEXT(event_context);
284     event_context->tolerance = prefs_get_int_attribute_limited("options.dragtolerance", "value", 0, 0, 100);
286     gint ret = FALSE;
287     switch (event->type) {
288     case GDK_BUTTON_PRESS:
289         if (event->button.button == 1 && !event_context->space_panning) {
290             NR::Point const button_w(event->button.x,
291                                      event->button.y);
293             // save drag origin
294             event_context->xp = (gint) button_w[NR::X];
295             event_context->yp = (gint) button_w[NR::Y];
296             event_context->within_tolerance = true;
298             // remember clicked item, disregarding groups, honoring Alt
299             event_context->item_to_select = sp_event_context_find_item (desktop, button_w, event->button.state & GDK_MOD1_MASK, TRUE);
301             dragging = true;
303             /* Position center */
304             Geom::Point button_dt(desktop->w2d(button_w));
305             rc->center = from_2geom(button_dt);
306             
307             /* Snap center */
308             SnapManager &m = desktop->namedview->snap_manager;
309             m.setup(desktop, NULL); //null, because we don't have an item yet
310             m.freeSnapReturnByRef(Inkscape::Snapper::SNAPPOINT_NODE, button_dt);
311             rc->center = from_2geom(button_dt);
312             
313             sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
314                                 ( GDK_KEY_PRESS_MASK |
315                                   GDK_BUTTON_RELEASE_MASK       |
316                                   GDK_POINTER_MOTION_MASK       |
317                                   GDK_POINTER_MOTION_HINT_MASK       |
318                                   GDK_BUTTON_PRESS_MASK ),
319                                 NULL, event->button.time);
320                                 
321             ret = TRUE;
322         }
323         break;
324     case GDK_MOTION_NOTIFY:
325         if ( dragging
326              && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning)
327         {
328             if ( event_context->within_tolerance
329                  && ( abs( (gint) event->motion.x - event_context->xp ) < event_context->tolerance )
330                  && ( abs( (gint) event->motion.y - event_context->yp ) < event_context->tolerance ) ) {
331                 break; // do not drag if we're within tolerance from origin
332             }
333             // Once the user has moved farther than tolerance from the original location
334             // (indicating they intend to draw, not click), then always process the
335             // motion notify coordinates as given (no snapping back to origin)
336             event_context->within_tolerance = false;
338             NR::Point const motion_w(event->motion.x, event->motion.y);
339             NR::Point motion_dt(desktop->w2d(motion_w));
340             
341             sp_rect_drag(*rc, motion_dt, event->motion.state); // this will also handle the snapping
342             gobble_motion_events(GDK_BUTTON1_MASK);
343             ret = TRUE;
344         }
345         break;
346     case GDK_BUTTON_RELEASE:
347         event_context->xp = event_context->yp = 0;
348         if (event->button.button == 1 && !event_context->space_panning) {
349             dragging = false;
351             if (!event_context->within_tolerance) {
352                 // we've been dragging, finish the rect
353                 sp_rect_finish(rc);
354             } else if (event_context->item_to_select) {
355                 // no dragging, select clicked item if any
356                 if (event->button.state & GDK_SHIFT_MASK) {
357                     selection->toggle(event_context->item_to_select);
358                 } else {
359                     selection->set(event_context->item_to_select);
360                 }
361             } else {
362                 // click in an empty space
363                 selection->clear();
364             }
366             event_context->item_to_select = NULL;
367             ret = TRUE;
368             sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate),
369                                   event->button.time);
370         }
371         break;
372     case GDK_KEY_PRESS:
373         switch (get_group0_keyval (&event->key)) {
374         case GDK_Alt_L:
375         case GDK_Alt_R:
376         case GDK_Control_L:
377         case GDK_Control_R:
378         case GDK_Shift_L:
379         case GDK_Shift_R:
380         case GDK_Meta_L:  // Meta is when you press Shift+Alt (at least on my machine)
381         case GDK_Meta_R:
382             if (!dragging){
383                 sp_event_show_modifier_tip (event_context->defaultMessageContext(), event,
384                                             _("<b>Ctrl</b>: make square or integer-ratio rect, lock a rounded corner circular"),
385                                             _("<b>Shift</b>: draw around the starting point"),
386                                             NULL);
387             }
388             break;
389         case GDK_Up:
390         case GDK_Down:
391         case GDK_KP_Up:
392         case GDK_KP_Down:
393             // prevent the zoom field from activation
394             if (!MOD__CTRL_ONLY)
395                 ret = TRUE;
396             break;
398         case GDK_x:
399         case GDK_X:
400             if (MOD__ALT_ONLY) {
401                 desktop->setToolboxFocusTo ("altx-rect");
402                 ret = TRUE;
403             }
404             break;
406         case GDK_T:
407             {
408                 Inkscape::Selection *selection = sp_desktop_selection (inkscape_active_desktop());
409                 SPItem *item = selection->singleItem();
410                 if (item && SP_IS_RECT (item)) {
411                     g_print ("Scaling transformation matrix\n");
412                     SP_RECT (item)->transform = NR::Matrix(NR::scale(1.25, 1.5));
413                     SP_OBJECT (item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
414                 }
415                 ret = TRUE;
416             }
417             break;
419         case GDK_g:
420         case GDK_G:
421             if (MOD__SHIFT_ONLY) {
422                 sp_selection_to_guides();
423                 ret = true;
424             }
425             break;
427         case GDK_Escape:
428             sp_desktop_selection(desktop)->clear();
429             //TODO: make dragging escapable by Esc
430             break;
432         case GDK_space:
433             if (dragging) {
434                 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate),
435                                       event->button.time);
436                 dragging = false;
437                 if (!event_context->within_tolerance) {
438                     // we've been dragging, finish the rect
439                     sp_rect_finish(rc);
440                 }
441                 // do not return true, so that space would work switching to selector
442             }
443             break;
445         default:
446             break;
447         }
448         break;
449     case GDK_KEY_RELEASE:
450         switch (get_group0_keyval (&event->key)) {
451         case GDK_Alt_L:
452         case GDK_Alt_R:
453         case GDK_Control_L:
454         case GDK_Control_R:
455         case GDK_Shift_L:
456         case GDK_Shift_R:
457         case GDK_Meta_L:  // Meta is when you press Shift+Alt
458         case GDK_Meta_R:
459             event_context->defaultMessageContext()->clear();
460             break;
461         default:
462             break;
463         }
464         break;
465     default:
466         break;
467     }
469     if (!ret) {
470         if (((SPEventContextClass *) parent_class)->root_handler) {
471             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
472         }
473     }
475     return ret;
478 static void sp_rect_drag(SPRectContext &rc, NR::Point const pt, guint state)
480     SPDesktop *desktop = SP_EVENT_CONTEXT(&rc)->desktop;
482     if (!rc.item) {
484         if (Inkscape::have_viable_layer(desktop, rc._message_context) == false) {
485             return;
486         }
488         /* Create object */
489         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(SP_EVENT_CONTEXT_DOCUMENT(&rc));
490         Inkscape::XML::Node *repr = xml_doc->createElement("svg:rect");
492         /* Set style */
493         sp_desktop_apply_style_tool (desktop, repr, "tools.shapes.rect", false);
495         rc.item = (SPItem *) desktop->currentLayer()->appendChildRepr(repr);
496         Inkscape::GC::release(repr);
497         rc.item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
498         rc.item->updateRepr();
500         sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 5);
501     }
503     NR::Rect const r = Inkscape::snap_rectangular_box(desktop, rc.item, pt, rc.center, state);
505     sp_rect_position_set(SP_RECT(rc.item), r.min()[NR::X], r.min()[NR::Y], r.dimensions()[NR::X], r.dimensions()[NR::Y]);
506     if ( rc.rx != 0.0 ) {
507         sp_rect_set_rx (SP_RECT(rc.item), TRUE, rc.rx);
508     }
509     if ( rc.ry != 0.0 ) {
510         if (rc.rx == 0.0)
511             sp_rect_set_ry (SP_RECT(rc.item), TRUE, CLAMP(rc.ry, 0, MIN(r.dimensions()[NR::X], r.dimensions()[NR::Y])/2));
512         else
513             sp_rect_set_ry (SP_RECT(rc.item), TRUE, CLAMP(rc.ry, 0, r.dimensions()[NR::Y]));
514     }
516     // status text
517     double rdimx = r.dimensions()[NR::X];
518     double rdimy = r.dimensions()[NR::Y];
519     GString *xs = SP_PX_TO_METRIC_STRING(rdimx, desktop->namedview->getDefaultMetric());
520     GString *ys = SP_PX_TO_METRIC_STRING(rdimy, desktop->namedview->getDefaultMetric());
521     if (state & GDK_CONTROL_MASK) {
522         int ratio_x, ratio_y;
523         bool is_golden_ratio = false;
524         if (fabs (rdimx) > fabs (rdimy)) {
525             if (fabs(rdimx / rdimy - goldenratio) < 1e-6) {
526                 is_golden_ratio = true;
527             }
528             ratio_x = (int) rint (rdimx / rdimy);
529             ratio_y = 1;
530         } else {
531             if (fabs(rdimy / rdimx - goldenratio) < 1e-6) {
532                 is_golden_ratio = true;
533             }
534             ratio_x = 1;
535             ratio_y = (int) rint (rdimy / rdimx);
536         }
537         if (!is_golden_ratio) {
538             rc._message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Rectangle</b>: %s &#215; %s (constrained to ratio %d:%d); with <b>Shift</b> to draw around the starting point"), xs->str, ys->str, ratio_x, ratio_y);
539         } else {
540             if (ratio_y == 1) {
541                 rc._message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Rectangle</b>: %s &#215; %s (constrained to golden ratio 1.618 : 1); with <b>Shift</b> to draw around the starting point"), xs->str, ys->str);
542             } else {
543                 rc._message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Rectangle</b>: %s &#215; %s (constrained to golden ratio 1 : 1.618); with <b>Shift</b> to draw around the starting point"), xs->str, ys->str);
544             }
545         }
546     } else {
547         rc._message_context->setF(Inkscape::IMMEDIATE_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);
548     }
549     g_string_free(xs, FALSE);
550     g_string_free(ys, FALSE);
553 static void sp_rect_finish(SPRectContext *rc)
555     rc->_message_context->clear();
557     if ( rc->item != NULL ) {
558         SPDesktop * desktop;
560         desktop = SP_EVENT_CONTEXT_DESKTOP(rc);
562         SP_OBJECT(rc->item)->updateRepr();
564         sp_canvas_end_forced_full_redraws(desktop->canvas);
566         sp_desktop_selection(desktop)->set(rc->item);
567         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_RECT,
568                          _("Create rectangle"));
570         rc->item = NULL;
571     }
574 /*
575   Local Variables:
576   mode:c++
577   c-file-style:"stroustrup"
578   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
579   indent-tabs-mode:nil
580   fill-column:99
581   End:
582 */
583 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :