Code

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