Code

Fix snap bug as reported by Arcadie Cracan on the developers mailing list, dating...
[inkscape.git] / src / event-context.cpp
1 #define __SP_EVENT_CONTEXT_C__
3 /** \file
4  * Main event handling, and related helper functions.
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   Frank Felfe <innerspace@iname.com>
9  *   bulia byak <buliabyak@users.sf.net>
10  *
11  * Copyright (C) 1999-2005 authors
12  * Copyright (C) 2001-2002 Ximian, Inc.
13  *
14  * Released under GNU GPL, read the file 'COPYING' for more information
15  */
17 /** \class SPEventContext
18  * SPEventContext is an abstract base class of all tools. As the name
19  * indicates, event context implementations process UI events (mouse
20  * movements and keypresses) and take actions (like creating or modifying
21  * objects).  There is one event context implementation for each tool,
22  * plus few abstract base classes. Writing a new tool involves
23  * subclassing SPEventContext.
24  */
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
30 #include "event-context.h"
32 #include <string.h>
33 #include <gdk/gdkkeysyms.h>
34 #include <gtk/gtkmain.h>
35 #include <gtk/gtkmenu.h>
36 #include <glibmm/i18n.h>
37 #include <cstring>
38 #include <string>
40 #include "display/sp-canvas.h"
41 #include "xml/node-event-vector.h"
42 #include "sp-cursor.h"
43 #include "shortcuts.h"
44 #include "desktop.h"
45 #include "desktop-handles.h"
46 #include "sp-namedview.h"
47 #include "selection.h"
48 #include "file.h"
49 #include "interface.h"
50 #include "macros.h"
51 #include "tools-switch.h"
52 #include "preferences.h"
53 #include "message-context.h"
54 #include "gradient-drag.h"
55 #include "object-edit.h"
56 #include "attributes.h"
57 #include "rubberband.h"
58 #include "selcue.h"
59 #include "lpe-tool-context.h"
60 #include "ui/tool/control-point.h"
62 static void sp_event_context_class_init(SPEventContextClass *klass);
63 static void sp_event_context_init(SPEventContext *event_context);
64 static void sp_event_context_dispose(GObject *object);
66 static void sp_event_context_private_setup(SPEventContext *ec);
67 static gint sp_event_context_private_root_handler(
68         SPEventContext *event_context, GdkEvent *event);
69 static gint sp_event_context_private_item_handler(
70         SPEventContext *event_context, SPItem *item, GdkEvent *event);
72 static void set_event_location(SPDesktop * desktop, GdkEvent * event);
74 static GObjectClass *parent_class;
76 // globals for temporary switching to selector by space
77 static bool selector_toggled = FALSE;
78 static int switch_selector_to = 0;
80 // globals for temporary switching to dropper by 'D'
81 static bool dropper_toggled = FALSE;
82 static int switch_dropper_to = 0;
84 static gint xp = 0, yp = 0; // where drag started
85 static gint tolerance = 0;
86 static bool within_tolerance = false;
88 // globals for keeping track of keyboard scroll events in order to accelerate
89 static guint32 scroll_event_time = 0;
90 static gdouble scroll_multiply = 1;
91 static guint scroll_keyval = 0;
93 /**
94  * Registers the SPEventContext class with Glib and returns its type number.
95  */
96 GType sp_event_context_get_type(void) {
97     static GType type = 0;
98     if (!type) {
99         GTypeInfo info = { sizeof(SPEventContextClass), NULL, NULL,
100                 (GClassInitFunc) sp_event_context_class_init, NULL, NULL,
101                 sizeof(SPEventContext), 4,
102                 (GInstanceInitFunc) sp_event_context_init, NULL, /* value_table */
103         };
104         type = g_type_register_static(G_TYPE_OBJECT, "SPEventContext", &info,
105                 (GTypeFlags) 0);
106     }
107     return type;
110 /**
111  * Callback to set up the SPEventContext vtable.
112  */
113 static void sp_event_context_class_init(SPEventContextClass *klass) {
114     GObjectClass *object_class;
116     object_class = (GObjectClass *) klass;
118     parent_class = (GObjectClass*) g_type_class_peek_parent(klass);
120     object_class->dispose = sp_event_context_dispose;
122     klass->setup = sp_event_context_private_setup;
123     klass->root_handler = sp_event_context_private_root_handler;
124     klass->item_handler = sp_event_context_private_item_handler;
127 /**
128  * Clears all SPEventContext object members.
129  */
130 static void sp_event_context_init(SPEventContext *event_context) {
131     event_context->desktop = NULL;
132     event_context->cursor = NULL;
133     event_context->_message_context = NULL;
134     event_context->_selcue = NULL;
135     event_context->_grdrag = NULL;
136     event_context->space_panning = false;
137     event_context->shape_editor = NULL;
138     event_context->_delayed_snap_event = NULL;
141 /**
142  * Callback to free and null member variables of SPEventContext object.
143  */
144 static void sp_event_context_dispose(GObject *object) {
145     SPEventContext *ec;
147     ec = SP_EVENT_CONTEXT(object);
149     if (ec->_message_context) {
150         delete ec->_message_context;
151     }
153     if (ec->cursor != NULL) {
154         gdk_cursor_unref(ec->cursor);
155         ec->cursor = NULL;
156     }
158     if (ec->desktop) {
159         ec->desktop = NULL;
160     }
162     if (ec->pref_observer) {
163         delete ec->pref_observer;
164     }
166     if (ec->_delayed_snap_event) {
167         delete ec->_delayed_snap_event;
168     }
170     G_OBJECT_CLASS(parent_class)->dispose(object);
173 /**
174  * Recreates and draws cursor on desktop related to SPEventContext.
175  */
176 void sp_event_context_update_cursor(SPEventContext *ec) {
177     GtkWidget *w = GTK_WIDGET(sp_desktop_canvas(ec->desktop));
178     if (w->window) {
179         /* fixme: */
180         if (ec->cursor_shape) {
181             GdkBitmap *bitmap = NULL;
182             GdkBitmap *mask = NULL;
183             sp_cursor_bitmap_and_mask_from_xpm(&bitmap, &mask, ec->cursor_shape);
184             if ((bitmap != NULL) && (mask != NULL)) {
185                 if (ec->cursor)
186                     gdk_cursor_unref(ec->cursor);
187                 ec->cursor = gdk_cursor_new_from_pixmap(bitmap, mask,
188                         &w->style->black, &w->style->white, ec->hot_x,
189                         ec->hot_y);
190                 g_object_unref(bitmap);
191                 g_object_unref(mask);
192             }
193         }
194         gdk_window_set_cursor(w->window, ec->cursor);
195         gdk_flush();
196     }
197     ec->desktop->waiting_cursor = false;
200 /**
201  * Callback that gets called on initialization of SPEventContext object.
202  * Redraws mouse cursor, at the moment.
203  */
204 static void sp_event_context_private_setup(SPEventContext *ec) {
205     sp_event_context_update_cursor(ec);
208 /**
209  * \brief   Gobbles next key events on the queue with the same keyval and mask. Returns the number of events consumed.
210  */
211 gint gobble_key_events(guint keyval, gint mask) {
212     GdkEvent *event_next;
213     gint i = 0;
215     event_next = gdk_event_get();
216     // while the next event is also a key notify with the same keyval and mask,
217     while (event_next && (event_next->type == GDK_KEY_PRESS || event_next->type
218             == GDK_KEY_RELEASE) && event_next->key.keyval == keyval && (!mask
219             || (event_next->key.state & mask))) {
220         if (event_next->type == GDK_KEY_PRESS)
221             i++;
222         // kill it
223         gdk_event_free(event_next);
224         // get next
225         event_next = gdk_event_get();
226     }
227     // otherwise, put it back onto the queue
228     if (event_next)
229         gdk_event_put(event_next);
231     return i;
234 /**
235  * \brief   Gobbles next motion notify events on the queue with the same mask. Returns the number of events consumed.
236  */
237 gint gobble_motion_events(gint mask) {
238     GdkEvent *event_next;
239     gint i = 0;
241     event_next = gdk_event_get();
242     // while the next event is also a key notify with the same keyval and mask,
243     while (event_next && event_next->type == GDK_MOTION_NOTIFY
244             && (event_next->motion.state & mask)) {
245         // kill it
246         gdk_event_free(event_next);
247         // get next
248         event_next = gdk_event_get();
249         i++;
250     }
251     // otherwise, put it back onto the queue
252     if (event_next)
253         gdk_event_put(event_next);
255     return i;
258 /**
259  * Toggles current tool between active tool and selector tool.
260  * Subroutine of sp_event_context_private_root_handler().
261  */
262 static void sp_toggle_selector(SPDesktop *dt) {
263     if (!dt->event_context)
264         return;
266     if (tools_isactive(dt, TOOLS_SELECT)) {
267         if (selector_toggled) {
268             if (switch_selector_to)
269                 tools_switch(dt, switch_selector_to);
270             selector_toggled = FALSE;
271         } else
272             return;
273     } else {
274         selector_toggled = TRUE;
275         switch_selector_to = tools_active(dt);
276         tools_switch(dt, TOOLS_SELECT);
277     }
280 /**
281  * Toggles current tool between active tool and dropper tool.
282  * Subroutine of sp_event_context_private_root_handler().
283  */
284 static void sp_toggle_dropper(SPDesktop *dt) {
285     if (!dt->event_context)
286         return;
288     if (tools_isactive(dt, TOOLS_DROPPER)) {
289         if (dropper_toggled) {
290             if (switch_dropper_to)
291                 tools_switch(dt, switch_dropper_to);
292             dropper_toggled = FALSE;
293         } else
294             return;
295     } else {
296         dropper_toggled = TRUE;
297         switch_dropper_to = tools_active(dt);
298         tools_switch(dt, TOOLS_DROPPER);
299     }
302 /**
303  * Calculates and keeps track of scroll acceleration.
304  * Subroutine of sp_event_context_private_root_handler().
305  */
306 static gdouble accelerate_scroll(GdkEvent *event, gdouble acceleration,
307         SPCanvas */*canvas*/) {
308     guint32 time_diff = ((GdkEventKey *) event)->time - scroll_event_time;
310     /* key pressed within 500ms ? (1/2 second) */
311     if (time_diff > 500 || event->key.keyval != scroll_keyval) {
312         scroll_multiply = 1; // abort acceleration
313     } else {
314         scroll_multiply += acceleration; // continue acceleration
315     }
317     scroll_event_time = ((GdkEventKey *) event)->time;
318     scroll_keyval = event->key.keyval;
320     return scroll_multiply;
323 /**
324  * Main event dispatch, gets called from Gdk.
325  */
326 static gint sp_event_context_private_root_handler(
327         SPEventContext *event_context, GdkEvent *event) {
328     static Geom::Point button_w;
329     static unsigned int panning = 0;
330     static unsigned int zoom_rb = 0;
332     SPDesktop *desktop = event_context->desktop;
333     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
335     /// @todo REmove redundant /value in preference keys
336     tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
338     gint ret = FALSE;
340     switch (event->type) {
341     case GDK_2BUTTON_PRESS:
342         if (panning) {
343             panning = 0;
344             sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate),
345                     event->button.time);
346             ret = TRUE;
347         } else {
348             /* sp_desktop_dialog(); */
349         }
350         break;
351     case GDK_BUTTON_PRESS:
353         // save drag origin
354         xp = (gint) event->button.x;
355         yp = (gint) event->button.y;
356         within_tolerance = true;
358         button_w = Geom::Point(event->button.x, event->button.y);
360         switch (event->button.button) {
361         case 1:
362             if (event_context->space_panning) {
363                 // When starting panning, make sure there are no snap events pending because these might disable the panning again
364                 sp_event_context_discard_delayed_snap_event(event_context);
365                 panning = 1;
366                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
367                         GDK_KEY_RELEASE_MASK | GDK_BUTTON_RELEASE_MASK
368                                 | GDK_POINTER_MOTION_MASK
369                                 | GDK_POINTER_MOTION_HINT_MASK, NULL,
370                         event->button.time - 1);
371                 ret = TRUE;
372             }
373             break;
374         case 2:
375             if (event->button.state & GDK_SHIFT_MASK) {
376                 zoom_rb = 2;
377             } else {
378                 // When starting panning, make sure there are no snap events pending because these might disable the panning again
379                 sp_event_context_discard_delayed_snap_event(event_context);
380                 panning = 2;
381                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
382                         GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK
383                                 | GDK_POINTER_MOTION_HINT_MASK, NULL,
384                         event->button.time - 1);
385             }
386             ret = TRUE;
387             break;
388         case 3:
389             if (event->button.state & GDK_SHIFT_MASK || event->button.state
390                     & GDK_CONTROL_MASK) {
391                 // When starting panning, make sure there are no snap events pending because these might disable the panning again
392                 sp_event_context_discard_delayed_snap_event(event_context);
393                 panning = 3;
394                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
395                         GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK
396                                 | GDK_POINTER_MOTION_HINT_MASK, NULL,
397                         event->button.time);
398                 ret = TRUE;
399             } else {
400                 sp_event_root_menu_popup(desktop, NULL, event);
401             }
402             break;
403         default:
404             break;
405         }
406         break;
407     case GDK_MOTION_NOTIFY:
408         if (panning) {
409             if ((panning == 2 && !(event->motion.state & GDK_BUTTON2_MASK))
410                     || (panning == 1 && !(event->motion.state
411                             & GDK_BUTTON1_MASK)) || (panning == 3
412                     && !(event->motion.state & GDK_BUTTON3_MASK))) {
413                 /* Gdk seems to lose button release for us sometimes :-( */
414                 panning = 0;
415                 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate),
416                         event->button.time);
417                 ret = TRUE;
418             } else {
419                 if (within_tolerance && (abs((gint) event->motion.x - xp)
420                         < tolerance) && (abs((gint) event->motion.y - yp)
421                         < tolerance)) {
422                     // do not drag if we're within tolerance from origin
423                     break;
424                 }
425                 // Once the user has moved farther than tolerance from
426                 // the original location (indicating they intend to move
427                 // the object, not click), then always process the motion
428                 // notify coordinates as given (no snapping back to origin)
429                 within_tolerance = false;
431                 // gobble subsequent motion events to prevent "sticking"
432                 // when scrolling is slow
433                 gobble_motion_events(panning == 2 ? GDK_BUTTON2_MASK : (panning
434                         == 1 ? GDK_BUTTON1_MASK : GDK_BUTTON3_MASK));
436                 Geom::Point const motion_w(event->motion.x, event->motion.y);
437                 Geom::Point const moved_w(motion_w - button_w);
438                 event_context->desktop->scroll_world(moved_w, true); // we're still scrolling, do not redraw
439                 ret = TRUE;
440             }
441         } else if (zoom_rb) {
442             Geom::Point const motion_w(event->motion.x, event->motion.y);
443             Geom::Point const motion_dt(desktop->w2d(motion_w));
445             if (within_tolerance && (abs((gint) event->motion.x - xp)
446                     < tolerance) && (abs((gint) event->motion.y - yp)
447                     < tolerance)) {
448                 break; // do not drag if we're within tolerance from origin
449             }
450             // Once the user has moved farther than tolerance from the original location
451             // (indicating they intend to move the object, not click), then always process the
452             // motion notify coordinates as given (no snapping back to origin)
453             within_tolerance = false;
455             if (Inkscape::Rubberband::get(desktop)->is_started()) {
456                 Inkscape::Rubberband::get(desktop)->move(motion_dt);
457             } else {
458                 Inkscape::Rubberband::get(desktop)->start(desktop, motion_dt);
459             }
460             if (zoom_rb == 2)
461                 gobble_motion_events(GDK_BUTTON2_MASK);
462         }
463         break;
464     case GDK_BUTTON_RELEASE:
465         xp = yp = 0;
466         if (within_tolerance && (panning || zoom_rb)) {
467             zoom_rb = 0;
468             if (panning) {
469                 panning = 0;
470                 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate),
471                         event->button.time);
472             }
473             Geom::Point const event_w(event->button.x, event->button.y);
474             Geom::Point const event_dt(desktop->w2d(event_w));
475             double const zoom_inc = prefs->getDoubleLimited(
476                     "/options/zoomincrement/value", M_SQRT2, 1.01, 10);
477             desktop->zoom_relative_keep_point(event_dt, (event->button.state
478                     & GDK_SHIFT_MASK) ? 1 / zoom_inc : zoom_inc);
479             desktop->updateNow();
480             ret = TRUE;
481         } else if (panning == event->button.button) {
482             panning = 0;
483             sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate),
484                     event->button.time);
486             // in slow complex drawings, some of the motion events are lost;
487             // to make up for this, we scroll it once again to the button-up event coordinates
488             // (i.e. canvas will always get scrolled all the way to the mouse release point,
489             // even if few intermediate steps were visible)
490             Geom::Point const motion_w(event->button.x, event->button.y);
491             Geom::Point const moved_w(motion_w - button_w);
492             event_context->desktop->scroll_world(moved_w);
493             desktop->updateNow();
494             ret = TRUE;
495         } else if (zoom_rb == event->button.button) {
496             zoom_rb = 0;
497             Geom::OptRect const b =
498                     Inkscape::Rubberband::get(desktop)->getRectangle();
499             Inkscape::Rubberband::get(desktop)->stop();
500             if (b && !within_tolerance) {
501                 desktop->set_display_area(*b, 10);
502             }
503             ret = TRUE;
504         }
505         break;
506     case GDK_KEY_PRESS: {
507         double const acceleration = prefs->getDoubleLimited(
508                 "/options/scrollingacceleration/value", 0, 0, 6);
509         int const key_scroll = prefs->getIntLimited("/options/keyscroll/value",
510                 10, 0, 1000);
512         switch (get_group0_keyval(&event->key)) {
513         // GDK insists on stealing these keys (F1 for no idea what, tab for cycling widgets
514         // in the editing window). So we resteal them back and run our regular shortcut
515         // invoker on them.
516         unsigned int shortcut;
517     case GDK_Tab:
518     case GDK_ISO_Left_Tab:
519     case GDK_F1:
520         shortcut = get_group0_keyval(&event->key);
521         if (event->key.state & GDK_SHIFT_MASK)
522             shortcut |= SP_SHORTCUT_SHIFT_MASK;
523         if (event->key.state & GDK_CONTROL_MASK)
524             shortcut |= SP_SHORTCUT_CONTROL_MASK;
525         if (event->key.state & GDK_MOD1_MASK)
526             shortcut |= SP_SHORTCUT_ALT_MASK;
527         ret = sp_shortcut_invoke(shortcut, desktop);
528         break;
530     case GDK_D:
531     case GDK_d:
532         if (!MOD__SHIFT && !MOD__CTRL && !MOD__ALT) {
533             sp_toggle_dropper(desktop);
534             ret = TRUE;
535         }
536         break;
537     case GDK_Q:
538     case GDK_q:
539         if (desktop->quick_zoomed()) {
540             ret = TRUE;
541         }
542         if (!MOD__SHIFT && !MOD__CTRL && !MOD__ALT) {
543             desktop->zoom_quick(true);
544             ret = TRUE;
545         }
546         break;
547     case GDK_W:
548     case GDK_w:
549     case GDK_F4:
550         /* Close view */
551         if (MOD__CTRL_ONLY) {
552             sp_ui_close_view(NULL);
553             ret = TRUE;
554         }
555         break;
556     case GDK_Left: // Ctrl Left
557     case GDK_KP_Left:
558     case GDK_KP_4:
559         if (MOD__CTRL_ONLY) {
560             int i = (int) floor(key_scroll * accelerate_scroll(event,
561                     acceleration, sp_desktop_canvas(desktop)));
562             gobble_key_events(get_group0_keyval(&event->key), GDK_CONTROL_MASK);
563             event_context->desktop->scroll_world(i, 0);
564             ret = TRUE;
565         }
566         break;
567     case GDK_Up: // Ctrl Up
568     case GDK_KP_Up:
569     case GDK_KP_8:
570         if (MOD__CTRL_ONLY) {
571             int i = (int) floor(key_scroll * accelerate_scroll(event,
572                     acceleration, sp_desktop_canvas(desktop)));
573             gobble_key_events(get_group0_keyval(&event->key), GDK_CONTROL_MASK);
574             event_context->desktop->scroll_world(0, i);
575             ret = TRUE;
576         }
577         break;
578     case GDK_Right: // Ctrl Right
579     case GDK_KP_Right:
580     case GDK_KP_6:
581         if (MOD__CTRL_ONLY) {
582             int i = (int) floor(key_scroll * accelerate_scroll(event,
583                     acceleration, sp_desktop_canvas(desktop)));
584             gobble_key_events(get_group0_keyval(&event->key), GDK_CONTROL_MASK);
585             event_context->desktop->scroll_world(-i, 0);
586             ret = TRUE;
587         }
588         break;
589     case GDK_Down: // Ctrl Down
590     case GDK_KP_Down:
591     case GDK_KP_2:
592         if (MOD__CTRL_ONLY) {
593             int i = (int) floor(key_scroll * accelerate_scroll(event,
594                     acceleration, sp_desktop_canvas(desktop)));
595             gobble_key_events(get_group0_keyval(&event->key), GDK_CONTROL_MASK);
596             event_context->desktop->scroll_world(0, -i);
597             ret = TRUE;
598         }
599         break;
600     case GDK_F10:
601         if (MOD__SHIFT_ONLY) {
602             sp_event_root_menu_popup(desktop, NULL, event);
603             ret = TRUE;
604         }
605         break;
606     case GDK_space:
607         if (prefs->getBool("/options/spacepans/value")) {
608             event_context->space_panning = true;
609             event_context->_message_context->set(Inkscape::INFORMATION_MESSAGE,
610                     _("<b>Space+mouse drag</b> to pan canvas"));
611             ret = TRUE;
612         } else {
613             sp_toggle_selector(desktop);
614             ret = TRUE;
615         }
616         break;
617     case GDK_z:
618     case GDK_Z:
619         if (MOD__ALT_ONLY) {
620             desktop->zoom_grab_focus();
621             ret = TRUE;
622         }
623         break;
624     default:
625         break;
626         }
627     }
628         break;
629     case GDK_KEY_RELEASE:
630         switch (get_group0_keyval(&event->key)) {
631         case GDK_space:
632             if (event_context->space_panning) {
633                 event_context->space_panning = false;
634                 event_context->_message_context->clear();
635                 if (panning == 1) {
636                     panning = 0;
637                     sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate),
638                             event->key.time);
639                     desktop->updateNow();
640                 }
641                 ret = TRUE;
642             }
643             break;
644         case GDK_Q:
645         case GDK_q:
646             if (desktop->quick_zoomed()) {
647                 desktop->zoom_quick(false);
648                 ret = TRUE;
649             }
650             break;
651         default:
652             break;
653         }
654         break;
655     case GDK_SCROLL: {
656         bool ctrl = (event->scroll.state & GDK_CONTROL_MASK);
657         bool wheelzooms = prefs->getBool("/options/wheelzooms/value");
658         int const wheel_scroll = prefs->getIntLimited(
659                 "/options/wheelscroll/value", 40, 0, 1000);
661         /* shift + wheel, pan left--right */
662         if (event->scroll.state & GDK_SHIFT_MASK) {
663             switch (event->scroll.direction) {
664             case GDK_SCROLL_UP:
665                 desktop->scroll_world(wheel_scroll, 0);
666                 break;
667             case GDK_SCROLL_DOWN:
668                 desktop->scroll_world(-wheel_scroll, 0);
669                 break;
670             default:
671                 break;
672             }
674             /* ctrl + wheel, zoom in--out */
675         } else if ((ctrl && !wheelzooms) || (!ctrl && wheelzooms)) {
676             double rel_zoom;
677             double const zoom_inc = prefs->getDoubleLimited(
678                     "/options/zoomincrement/value", M_SQRT2, 1.01, 10);
679             switch (event->scroll.direction) {
680             case GDK_SCROLL_UP:
681                 rel_zoom = zoom_inc;
682                 break;
683             case GDK_SCROLL_DOWN:
684                 rel_zoom = 1 / zoom_inc;
685                 break;
686             default:
687                 rel_zoom = 0.0;
688                 break;
689             }
690             if (rel_zoom != 0.0) {
691                 Geom::Point const scroll_dt = desktop->point();
692                 desktop->zoom_relative_keep_point(scroll_dt, rel_zoom);
693             }
695             /* no modifier, pan up--down (left--right on multiwheel mice?) */
696         } else {
697             switch (event->scroll.direction) {
698             case GDK_SCROLL_UP:
699                 desktop->scroll_world(0, wheel_scroll);
700                 break;
701             case GDK_SCROLL_DOWN:
702                 desktop->scroll_world(0, -wheel_scroll);
703                 break;
704             case GDK_SCROLL_LEFT:
705                 desktop->scroll_world(wheel_scroll, 0);
706                 break;
707             case GDK_SCROLL_RIGHT:
708                 desktop->scroll_world(-wheel_scroll, 0);
709                 break;
710             }
711         }
712         break;
713     }
714     default:
715         break;
716     }
718     return ret;
721 /**
722  * Handles item specific events. Gets called from Gdk.
723  *
724  * Only reacts to right mouse button at the moment.
725  * \todo Fixme: do context sensitive popup menu on items.
726  */
727 gint sp_event_context_private_item_handler(SPEventContext *ec, SPItem *item,
728         GdkEvent *event) {
729     int ret = FALSE;
731     switch (event->type) {
732     case GDK_BUTTON_PRESS:
733         if ((event->button.button == 3) && !(event->button.state
734                 & GDK_SHIFT_MASK || event->button.state & GDK_CONTROL_MASK)) {
735             sp_event_root_menu_popup(ec->desktop, item, event);
736             ret = TRUE;
737         }
738         break;
739     default:
740         break;
741     }
743     return ret;
746 /**
747  * @brief An observer that relays pref changes to the derived classes
748  */
749 class ToolPrefObserver: public Inkscape::Preferences::Observer {
750 public:
751     ToolPrefObserver(Glib::ustring const &path, SPEventContext *ec) :
752         Inkscape::Preferences::Observer(path), _ec(ec) {
753     }
754     virtual void notify(Inkscape::Preferences::Entry const &val) {
755         if (((SPEventContextClass *) G_OBJECT_GET_CLASS(_ec))->set) {
756             ((SPEventContextClass *) G_OBJECT_GET_CLASS(_ec))->set(_ec,
757                     const_cast<Inkscape::Preferences::Entry*> (&val));
758         }
759     }
760 private:
761     SPEventContext * const _ec;
762 };
764 /**
765  * Creates new SPEventContext object and calls its virtual setup() function.
766  * @todo This is bogus. pref_path should be a private property of the inheriting objects.
767  */
768 SPEventContext *
769 sp_event_context_new(GType type, SPDesktop *desktop, gchar const *pref_path,
770         unsigned int key) {
771     g_return_val_if_fail(g_type_is_a(type, SP_TYPE_EVENT_CONTEXT), NULL);
772     g_return_val_if_fail(desktop != NULL, NULL);
774     SPEventContext * const ec = (SPEventContext*) g_object_new(type, NULL);
776     ec->desktop = desktop;
777     ec->_message_context
778             = new Inkscape::MessageContext(desktop->messageStack());
779     ec->key = key;
780     ec->pref_observer = NULL;
782     if (pref_path) {
783         ec->pref_observer = new ToolPrefObserver(pref_path, ec);
785         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
786         prefs->addObserver(*(ec->pref_observer));
787     }
789     if (((SPEventContextClass *) G_OBJECT_GET_CLASS(ec))->setup)
790         ((SPEventContextClass *) G_OBJECT_GET_CLASS(ec))->setup(ec);
792     return ec;
795 /**
796  * Finishes SPEventContext.
797  */
798 void sp_event_context_finish(SPEventContext *ec) {
799     g_return_if_fail(ec != NULL);
800     g_return_if_fail(SP_IS_EVENT_CONTEXT(ec));
802     ec->enableSelectionCue(false);
804     if (ec->next) {
805         g_warning("Finishing event context with active link\n");
806     }
808     if (((SPEventContextClass *) G_OBJECT_GET_CLASS(ec))->finish)
809         ((SPEventContextClass *) G_OBJECT_GET_CLASS(ec))->finish(ec);
812 //-------------------------------member functions
814 /**
815  * Enables/disables the SPEventContext's SelCue.
816  */
817 void SPEventContext::enableSelectionCue(bool enable) {
818     if (enable) {
819         if (!_selcue) {
820             _selcue = new Inkscape::SelCue(desktop);
821         }
822     } else {
823         delete _selcue;
824         _selcue = NULL;
825     }
828 /**
829  * Enables/disables the SPEventContext's GrDrag.
830  */
831 void SPEventContext::enableGrDrag(bool enable) {
832     if (enable) {
833         if (!_grdrag) {
834             _grdrag = new GrDrag(desktop);
835         }
836     } else {
837         if (_grdrag) {
838             delete _grdrag;
839             _grdrag = NULL;
840         }
841     }
844 /**
845  * Calls virtual set() function of SPEventContext.
846  */
847 void sp_event_context_read(SPEventContext *ec, gchar const *key) {
848     g_return_if_fail(ec != NULL);
849     g_return_if_fail(SP_IS_EVENT_CONTEXT(ec));
850     g_return_if_fail(key != NULL);
852     if (((SPEventContextClass *) G_OBJECT_GET_CLASS(ec))->set) {
853         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
854         Inkscape::Preferences::Entry val = prefs->getEntry(
855                 ec->pref_observer->observed_path + '/' + key);
856         ((SPEventContextClass *) G_OBJECT_GET_CLASS(ec))->set(ec, &val);
857     }
860 /**
861  * Calls virtual activate() function of SPEventContext.
862  */
863 void sp_event_context_activate(SPEventContext *ec) {
864     g_return_if_fail(ec != NULL);
865     g_return_if_fail(SP_IS_EVENT_CONTEXT(ec));
867     // Make sure no delayed snapping events are carried over after switching contexts
868     // (this is only an additional safety measure against sloppy coding, because each
869     // context should take care of this by itself.
870     sp_event_context_discard_delayed_snap_event(ec);
872     if (((SPEventContextClass *) G_OBJECT_GET_CLASS(ec))->activate)
873         ((SPEventContextClass *) G_OBJECT_GET_CLASS(ec))->activate(ec);
876 /**
877  * Calls virtual deactivate() function of SPEventContext.
878  */
879 void sp_event_context_deactivate(SPEventContext *ec) {
880     g_return_if_fail(ec != NULL);
881     g_return_if_fail(SP_IS_EVENT_CONTEXT(ec));
883     if (((SPEventContextClass *) G_OBJECT_GET_CLASS(ec))->deactivate)
884         ((SPEventContextClass *) G_OBJECT_GET_CLASS(ec))->deactivate(ec);
887 /**
888  * Calls virtual root_handler(), the main event handling function.
889  */
890 gint sp_event_context_root_handler(SPEventContext * event_context,
891         GdkEvent * event) {
892     switch (event->type) {
893     case GDK_MOTION_NOTIFY:
894         sp_event_context_snap_delay_handler(event_context, NULL, NULL,
895                 (GdkEventMotion *) event,
896                 DelayedSnapEvent::EVENTCONTEXT_ROOT_HANDLER);
897         break;
898     case GDK_BUTTON_RELEASE:
899         if (event_context->_delayed_snap_event) {
900             // If we have any pending snapping action, then invoke it now
901             sp_event_context_snap_watchdog_callback(
902                     event_context->_delayed_snap_event);
903         }
904         break;
905     case GDK_BUTTON_PRESS:
906     case GDK_2BUTTON_PRESS:
907     case GDK_3BUTTON_PRESS:
908         // Snapping will be on hold if we're moving the mouse at high speeds. When starting
909         // drawing a new shape we really should snap though.
910         event_context->desktop->namedview->snap_manager.snapprefs.setSnapPostponedGlobally(
911                 false);
912         break;
913     default:
914         break;
915     }
917     return sp_event_context_virtual_root_handler(event_context, event);
920 gint sp_event_context_virtual_root_handler(SPEventContext * event_context,
921         GdkEvent * event) {
922     gint
923             ret =
924                     ((SPEventContextClass *) G_OBJECT_GET_CLASS(event_context))->root_handler(
925                             event_context, event);
926     set_event_location(event_context->desktop, event);
927     return ret;
930 /**
931  * Calls virtual item_handler(), the item event handling function.
932  */
933 gint sp_event_context_item_handler(SPEventContext * event_context,
934         SPItem * item, GdkEvent * event) {
935     switch (event->type) {
936     case GDK_MOTION_NOTIFY:
937         sp_event_context_snap_delay_handler(event_context, item, NULL, (GdkEventMotion *) event, DelayedSnapEvent::EVENTCONTEXT_ITEM_HANDLER);
938         break;
939     case GDK_BUTTON_RELEASE:
940         if (event_context->_delayed_snap_event) {
941             // If we have any pending snapping action, then invoke it now
942             sp_event_context_snap_watchdog_callback(event_context->_delayed_snap_event);
943         }
944         break;
945     case GDK_BUTTON_PRESS:
946     case GDK_2BUTTON_PRESS:
947     case GDK_3BUTTON_PRESS:
948         // Snapping will be on hold if we're moving the mouse at high speeds. When starting
949         // drawing a new shape we really should snap though.
950         event_context->desktop->namedview->snap_manager.snapprefs.setSnapPostponedGlobally(false);
951         break;
952     default:
953         break;
954     }
956     return sp_event_context_virtual_item_handler(event_context, item, event);
959 gint sp_event_context_virtual_item_handler(SPEventContext * event_context,
960         SPItem * item, GdkEvent * event) {
961     gint
962             ret =
963                     ((SPEventContextClass *) G_OBJECT_GET_CLASS(event_context))->item_handler(
964                             event_context, item, event);
966     if (!ret) {
967         ret = sp_event_context_virtual_root_handler(event_context, event);
968     } else {
969         set_event_location(event_context->desktop, event);
970     }
972     return ret;
975 /**
976  * Emits 'position_set' signal on desktop and shows coordinates on status bar.
977  */
978 static void set_event_location(SPDesktop *desktop, GdkEvent *event) {
979     if (event->type != GDK_MOTION_NOTIFY) {
980         return;
981     }
983     Geom::Point const button_w(event->button.x, event->button.y);
984     Geom::Point const button_dt(desktop->w2d(button_w));
985     desktop->setPosition(button_dt);
986     desktop->set_coordinate_status(button_dt);
989 //-------------------------------------------------------------------
990 /**
991  * Create popup menu and tell Gtk to show it.
992  */
993 void sp_event_root_menu_popup(SPDesktop *desktop, SPItem *item, GdkEvent *event) {
994     GtkWidget *menu;
996     /* fixme: This is not what I want but works for now (Lauris) */
997     if (event->type == GDK_KEY_PRESS) {
998         item = sp_desktop_selection(desktop)->singleItem();
999     }
1000     menu = sp_ui_context_menu(desktop, item);
1001     gtk_widget_show(menu);
1003     switch (event->type) {
1004     case GDK_BUTTON_PRESS:
1005         gtk_menu_popup(GTK_MENU(menu), NULL, NULL, 0, NULL,
1006                 event->button.button, event->button.time);
1007         break;
1008     case GDK_KEY_PRESS:
1009         gtk_menu_popup(GTK_MENU(menu), NULL, NULL, 0, NULL, 0, event->key.time);
1010         break;
1011     default:
1012         break;
1013     }
1016 /**
1017  * Show tool context specific modifier tip.
1018  */
1019 void sp_event_show_modifier_tip(Inkscape::MessageContext *message_context,
1020         GdkEvent *event, gchar const *ctrl_tip, gchar const *shift_tip,
1021         gchar const *alt_tip) {
1022     guint keyval = get_group0_keyval(&event->key);
1024     bool ctrl = ctrl_tip && (MOD__CTRL || (keyval == GDK_Control_L) || (keyval
1025             == GDK_Control_R));
1026     bool shift = shift_tip && (MOD__SHIFT || (keyval == GDK_Shift_L) || (keyval
1027             == GDK_Shift_R));
1028     bool alt = alt_tip && (MOD__ALT || (keyval == GDK_Alt_L) || (keyval
1029             == GDK_Alt_R) || (keyval == GDK_Meta_L) || (keyval == GDK_Meta_R));
1031     gchar *tip = g_strdup_printf("%s%s%s%s%s", (ctrl ? ctrl_tip : ""), (ctrl
1032             && (shift || alt) ? "; " : ""), (shift ? shift_tip : ""), ((ctrl
1033             || shift) && alt ? "; " : ""), (alt ? alt_tip : ""));
1035     if (strlen(tip) > 0) {
1036         message_context->flash(Inkscape::INFORMATION_MESSAGE, tip);
1037     }
1039     g_free(tip);
1042 /**
1043  * Return the keyval corresponding to the key event in group 0, i.e.,
1044  * in the main (English) layout.
1045  *
1046  * Use this instead of simply event->keyval, so that your keyboard shortcuts
1047  * work regardless of layouts (e.g., in Cyrillic).
1048  */
1049 guint get_group0_keyval(GdkEventKey *event) {
1050     guint keyval = 0;
1051     gdk_keymap_translate_keyboard_state(gdk_keymap_get_for_display(
1052             gdk_display_get_default()), event->hardware_keycode,
1053             (GdkModifierType) event->state, 0 /*event->key.group*/, &keyval,
1054             NULL, NULL, NULL);
1055     return keyval;
1058 /**
1059  * Returns item at point p in desktop.
1060  *
1061  * If state includes alt key mask, cyclically selects under; honors
1062  * into_groups.
1063  */
1064 SPItem *
1065 sp_event_context_find_item(SPDesktop *desktop, Geom::Point const &p,
1066         bool select_under, bool into_groups) {
1067     SPItem *item;
1069     if (select_under) {
1070         SPItem *selected_at_point = desktop->item_from_list_at_point_bottom(
1071                 desktop->selection->itemList(), p);
1072         item = desktop->item_at_point(p, into_groups, selected_at_point);
1073         if (item == NULL) { // we may have reached bottom, flip over to the top
1074             item = desktop->item_at_point(p, into_groups, NULL);
1075         }
1076     } else
1077         item = desktop->item_at_point(p, into_groups, NULL);
1079     return item;
1082 /**
1083  * Returns item if it is under point p in desktop, at any depth; otherwise returns NULL.
1084  *
1085  * Honors into_groups.
1086  */
1087 SPItem *
1088 sp_event_context_over_item(SPDesktop *desktop, SPItem *item,
1089         Geom::Point const &p) {
1090     GSList *temp = NULL;
1091     temp = g_slist_prepend(temp, item);
1092     SPItem *item_at_point = desktop->item_from_list_at_point_bottom(temp, p);
1093     g_slist_free(temp);
1095     return item_at_point;
1098 ShapeEditor *
1099 sp_event_context_get_shape_editor(SPEventContext *ec) {
1100     return ec->shape_editor;
1103 void event_context_print_event_info(GdkEvent *event, bool print_return) {
1104     switch (event->type) {
1105     case GDK_BUTTON_PRESS:
1106         g_print("GDK_BUTTON_PRESS");
1107         break;
1108     case GDK_2BUTTON_PRESS:
1109         g_print("GDK_2BUTTON_PRESS");
1110         break;
1111     case GDK_3BUTTON_PRESS:
1112         g_print("GDK_3BUTTON_PRESS");
1113         break;
1115     case GDK_MOTION_NOTIFY:
1116         g_print("GDK_MOTION_NOTIFY");
1117         break;
1118     case GDK_ENTER_NOTIFY:
1119         g_print("GDK_ENTER_NOTIFY");
1120         break;
1122     case GDK_LEAVE_NOTIFY:
1123         g_print("GDK_LEAVE_NOTIFY");
1124         break;
1125     case GDK_BUTTON_RELEASE:
1126         g_print("GDK_BUTTON_RELEASE");
1127         break;
1129     case GDK_KEY_PRESS:
1130         g_print("GDK_KEY_PRESS: %d", get_group0_keyval(&event->key));
1131         break;
1132     case GDK_KEY_RELEASE:
1133         g_print("GDK_KEY_RELEASE: %d", get_group0_keyval(&event->key));
1134         break;
1135     default:
1136         //g_print ("even type not recognized");
1137         break;
1138     }
1140     if (print_return) {
1141         g_print("\n");
1142     }
1145 void sp_event_context_snap_delay_handler(SPEventContext *ec,
1146         SPItem* const item, SPKnot* const knot, GdkEventMotion *event,
1147         DelayedSnapEvent::DelayedSnapEventOrigin origin) {
1148     static guint32 prev_time;
1149     static boost::optional<Geom::Point> prev_pos;
1151     // Snapping occurs when dragging with the left mouse button down, or when hovering e.g. in the pen tool with left mouse button up
1152     bool const c1 = event->state & GDK_BUTTON2_MASK; // We shouldn't hold back any events when other mouse buttons have been
1153     bool const c2 = event->state & GDK_BUTTON3_MASK; // pressed, e.g. when scrolling with the middle mouse button; if we do then
1154     // Inkscape will get stuck in an unresponsive state
1155     bool const c3 = tools_isactive(ec->desktop, TOOLS_CALLIGRAPHIC);
1156     // The snap delay will repeat the last motion event, which will lead to
1157     // erroneous points in the calligraphy context. And because we don't snap
1158     // in this context, we might just as well disable the snap delay all together
1160     if (c1 || c2 || c3) {
1161         // Make sure that we don't send any pending snap events to a context if we know in advance
1162         // that we're not going to snap any way (e.g. while scrolling with middle mouse button)
1163         // Any motion event might affect the state of the context, leading to unexpected behavior
1164         sp_event_context_discard_delayed_snap_event(ec);
1165     } else if (ec->desktop
1166             && ec->desktop->namedview->snap_manager.snapprefs.getSnapEnabledGlobally()) {
1167         // Snap when speed drops below e.g. 0.02 px/msec, or when no motion events have occurred for some period.
1168         // i.e. snap when we're at stand still. A speed threshold enforces snapping for tablets, which might never
1169         // be fully at stand still and might keep spitting out motion events.
1170         ec->desktop->namedview->snap_manager.snapprefs.setSnapPostponedGlobally(
1171                 true); // put snapping on hold
1173         Geom::Point event_pos(event->x, event->y);
1174         guint32 event_t = gdk_event_get_time((GdkEvent *) event);
1176         if (prev_pos) {
1177             Geom::Coord dist = Geom::L2(event_pos - *prev_pos);
1178             guint32 delta_t = event_t - prev_time;
1179             gdouble speed = delta_t > 0 ? dist / delta_t : 1000;
1180             //std::cout << "Mouse speed = " << speed << " px/msec " << std::endl;
1181             if (speed > 0.02) { // Jitter threshold, might be needed for tablets
1182                 // We're moving fast, so postpone any snapping until the next GDK_MOTION_NOTIFY event. We
1183                 // will keep on postponing the snapping as long as the speed is high.
1184                 // We must snap at some point in time though, so set a watchdog timer at some time from
1185                 // now, just in case there's no future motion event that drops under the speed limit (when
1186                 // stopping abruptly)
1187                 delete ec->_delayed_snap_event;
1188                 ec->_delayed_snap_event = new DelayedSnapEvent(ec, item, knot,
1189                         event, origin); // watchdog is reset, i.e. pushed forward in time
1190                 // If the watchdog expires before a new motion event is received, we will snap (as explained
1191                 // above). This means however that when the timer is too short, we will always snap and that the
1192                 // speed threshold is ineffective. In the extreme case the delay is set to zero, and snapping will
1193                 // be immediate, as it used to be in the old days ;-).
1194             } else { // Speed is very low, so we're virtually at stand still
1195                 // But if we're really standing still, then we should snap now. We could use some low-pass filtering,
1196                 // otherwise snapping occurs for each jitter movement. For this filtering we'll leave the watchdog to expire,
1197                 // snap, and set a new watchdog again.
1198                 if (ec->_delayed_snap_event == NULL) { // no watchdog has been set
1199                     // it might have already expired, so we'll set a new one; the snapping frequency will be limited this way
1200                     ec->_delayed_snap_event = new DelayedSnapEvent(ec, item,
1201                             knot, event, origin);
1202                 } // else: watchdog has been set before and we'll wait for it to expire
1203             }
1204         } else {
1205             // This is the first GDK_MOTION_NOTIFY event, so postpone snapping and set the watchdog
1206             g_assert(ec->_delayed_snap_event == NULL);
1207             ec->_delayed_snap_event = new DelayedSnapEvent(ec, item, knot,
1208                     event, origin);
1209         }
1211         prev_pos = event_pos;
1212         prev_time = event_t;
1213     }
1216 gboolean sp_event_context_snap_watchdog_callback(gpointer data) {
1217     // Snap NOW! For this the "postponed" flag will be reset and the last motion event will be repeated
1218     DelayedSnapEvent *dse = reinterpret_cast<DelayedSnapEvent*> (data);
1220     if (dse == NULL) {
1221         // This might occur when this method is called directly, i.e. not through the timer
1222         // E.g. on GDK_BUTTON_RELEASE in sp_event_context_root_handler()
1223         return FALSE;
1224     }
1226     SPEventContext *ec = dse->getEventContext();
1227     if (ec == NULL || ec->desktop == NULL) {
1228         return false;
1229     }
1231     SPDesktop *dt = ec->desktop;
1232     dt->namedview->snap_manager.snapprefs.setSnapPostponedGlobally(false);
1234     switch (dse->getOrigin()) {
1235     case DelayedSnapEvent::EVENTCONTEXT_ROOT_HANDLER:
1236         sp_event_context_virtual_root_handler(ec, dse->getEvent());
1237         break;
1238     case DelayedSnapEvent::EVENTCONTEXT_ITEM_HANDLER: {
1239         SPItem* item = NULL;
1240         item = dse->getItem();
1241         if (item && SP_IS_ITEM(item)) {
1242             sp_event_context_virtual_item_handler(ec, item, dse->getEvent());
1243         }
1244     }
1245         break;
1246     case DelayedSnapEvent::KNOT_HANDLER: {
1247         SPKnot* knot = dse->getKnot();
1248         if (knot && SP_IS_KNOT(knot)) {
1249             sp_knot_handler_request_position(dse->getEvent(), knot);
1250         }
1251     }
1252         break;
1253     case DelayedSnapEvent::CONTROL_POINT_HANDLER: {
1254         using Inkscape::UI::ControlPoint;
1255         ControlPoint *point = reinterpret_cast<ControlPoint*> (dse->getKnot());
1256         point->_eventHandler(dse->getEvent());
1257     }
1258         break;
1259     default:
1260         g_warning("Origin of snap-delay event has not been defined!;");
1261         break;
1262     }
1264     ec->_delayed_snap_event = NULL;
1265     delete dse;
1267     return FALSE; //Kills the timer and stops it from executing this callback over and over again.
1270 void sp_event_context_discard_delayed_snap_event(SPEventContext *ec) {
1271     delete ec->_delayed_snap_event;
1272     ec->_delayed_snap_event = NULL;
1275 /*
1276  Local Variables:
1277  mode:c++
1278  c-file-style:"stroustrup"
1279  c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1280  indent-tabs-mode:nil
1281  fill-column:99
1282  End:
1283  */
1284 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :