Code

Add a centralized check (i.e. in the snapper mechanism) whether we've snapped or...
[inkscape.git] / src / pencil-context.cpp
1 /** \file
2  * Pencil event context implementation.
3  */
5 /*
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   bulia byak <buliabyak@users.sf.net>
9  *
10  * Copyright (C) 2000 Lauris Kaplinski
11  * Copyright (C) 2000-2001 Ximian, Inc.
12  * Copyright (C) 2002 Lauris Kaplinski
13  * Copyright (C) 2004 Monash University
14  *
15  * Released under GNU GPL, read the file 'COPYING' for more information
16  */
18 #include <gdk/gdkkeysyms.h>
20 #include "pencil-context.h"
21 #include "desktop.h"
22 #include "desktop-handles.h"
23 #include "selection.h"
24 #include "selection-chemistry.h"
25 #include "draw-anchor.h"
26 #include "message-stack.h"
27 #include "message-context.h"
28 #include "modifier-fns.h"
29 #include "sp-path.h"
30 #include "prefs-utils.h"
31 #include "snap.h"
32 #include "pixmaps/cursor-pencil.xpm"
33 #include "display/bezier-utils.h"
34 #include "display/canvas-bpath.h"
35 #include <glibmm/i18n.h>
36 #include "libnr/in-svg-plane.h"
37 #include "libnr/n-art-bpath.h"
38 #include "context-fns.h"
39 #include "sp-namedview.h"
40 #include "xml/repr.h"
41 #include "document.h"
42 #include "desktop-style.h"
43 #include "macros.h"
44 #include "display/curve.h"
46 static void sp_pencil_context_class_init(SPPencilContextClass *klass);
47 static void sp_pencil_context_init(SPPencilContext *pc);
48 static void sp_pencil_context_setup(SPEventContext *ec);
49 static void sp_pencil_context_dispose(GObject *object);
51 static gint sp_pencil_context_root_handler(SPEventContext *event_context, GdkEvent *event);
52 static gint pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent);
53 static gint pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent);
54 static gint pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent);
55 static gint pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state);
57 static void spdc_set_startpoint(SPPencilContext *pc, NR::Point const p);
58 static void spdc_set_endpoint(SPPencilContext *pc, NR::Point const p);
59 static void spdc_finish_endpoint(SPPencilContext *pc);
60 static void spdc_add_freehand_point(SPPencilContext *pc, NR::Point p, guint state);
61 static void fit_and_split(SPPencilContext *pc);
64 static SPDrawContextClass *pencil_parent_class;
66 /**
67  * Register SPPencilContext class with Gdk and return its type number.
68  */
69 GType
70 sp_pencil_context_get_type()
71 {
72     static GType type = 0;
73     if (!type) {
74         GTypeInfo info = {
75             sizeof(SPPencilContextClass),
76             NULL, NULL,
77             (GClassInitFunc) sp_pencil_context_class_init,
78             NULL, NULL,
79             sizeof(SPPencilContext),
80             4,
81             (GInstanceInitFunc) sp_pencil_context_init,
82             NULL,   /* value_table */
83         };
84         type = g_type_register_static(SP_TYPE_DRAW_CONTEXT, "SPPencilContext", &info, (GTypeFlags)0);
85     }
86     return type;
87 }
89 /**
90  * Initialize SPPencilContext vtable.
91  */
92 static void
93 sp_pencil_context_class_init(SPPencilContextClass *klass)
94 {
95     GObjectClass *object_class;
96     SPEventContextClass *event_context_class;
98     object_class = (GObjectClass *) klass;
99     event_context_class = (SPEventContextClass *) klass;
101     pencil_parent_class = (SPDrawContextClass*)g_type_class_peek_parent(klass);
103     object_class->dispose = sp_pencil_context_dispose;
105     event_context_class->setup = sp_pencil_context_setup;
106     event_context_class->root_handler = sp_pencil_context_root_handler;
109 /**
110  * Callback to initialize SPPencilContext object.
111  */
112 static void
113 sp_pencil_context_init(SPPencilContext *pc)
115     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
117     event_context->cursor_shape = cursor_pencil_xpm;
118     event_context->hot_x = 4;
119     event_context->hot_y = 4;
121     pc->npoints = 0;
122     pc->state = SP_PENCIL_CONTEXT_IDLE;
123     pc->req_tangent = NR::Point(0, 0);
126 /**
127  * Callback to setup SPPencilContext object.
128  */
129 static void
130 sp_pencil_context_setup(SPEventContext *ec)
132     if (prefs_get_int_attribute("tools.freehand.pencil", "selcue", 0) != 0) {
133         ec->enableSelectionCue();
134     }
136     if (((SPEventContextClass *) pencil_parent_class)->setup) {
137         ((SPEventContextClass *) pencil_parent_class)->setup(ec);
138     }
140     SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
141     pc->is_drawing = false;
143     pc->anchor_statusbar = false;
146 static void
147 sp_pencil_context_dispose(GObject *object)
149     G_OBJECT_CLASS(pencil_parent_class)->dispose(object);
152 /** Snaps new node relative to the previous node. */
153 static void
154 spdc_endpoint_snap(SPPencilContext const *pc, NR::Point &p, guint const state)
156     spdc_endpoint_snap_rotation(pc, p, pc->p[0], state);
157     spdc_endpoint_snap_free(pc, p, state);
160 /**
161  * Callback for handling all pencil context events.
162  */
163 gint
164 sp_pencil_context_root_handler(SPEventContext *const ec, GdkEvent *event)
166     SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
168     gint ret = FALSE;
170     switch (event->type) {
171         case GDK_BUTTON_PRESS:
172             ret = pencil_handle_button_press(pc, event->button);
173             break;
175         case GDK_MOTION_NOTIFY:
176             ret = pencil_handle_motion_notify(pc, event->motion);
177             break;
179         case GDK_BUTTON_RELEASE:
180             ret = pencil_handle_button_release(pc, event->button);
181             break;
183         case GDK_KEY_PRESS:
184             ret = pencil_handle_key_press(pc, get_group0_keyval (&event->key), event->key.state);
185             break;
187         default:
188             break;
189     }
191     if (!ret) {
192         gint (*const parent_root_handler)(SPEventContext *, GdkEvent *)
193             = ((SPEventContextClass *) pencil_parent_class)->root_handler;
194         if (parent_root_handler) {
195             ret = parent_root_handler(ec, event);
196         }
197     }
199     return ret;
202 static gint
203 pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent)
205     gint ret = FALSE;
206     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
207     if ( bevent.button == 1  && !event_context->space_panning) {
209         SPDrawContext *dc = SP_DRAW_CONTEXT (pc);
210         SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
211         Inkscape::Selection *selection = sp_desktop_selection(desktop);
213         if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
214             return TRUE;
215         }
217         NR::Point const button_w(bevent.x, bevent.y);
219         /* Find desktop coordinates */
220         NR::Point p = pc->desktop->w2d(button_w);
222         /* Test whether we hit any anchor. */
223         SPDrawAnchor *anchor = spdc_test_inside(pc, button_w);
225         switch (pc->state) {
226             case SP_PENCIL_CONTEXT_ADDLINE:
227                 /* Current segment will be finished with release */
228                 ret = TRUE;
229                 break;
230             default:
231                 /* Set first point of sequence */
232                 if (bevent.state & GDK_CONTROL_MASK) {
233                     freehand_create_single_dot(event_context, p, "tools.freehand.pencil", bevent.state);
234                     ret = true;
235                     break;
236                 }
237                 if (anchor) {
238                     p = anchor->dp;
239                     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path"));
240                 } else {
242                     if (!(bevent.state & GDK_SHIFT_MASK)) {
244                         // This is the first click of a new curve; deselect item so that
245                         // this curve is not combined with it (unless it is drawn from its
246                         // anchor, which is handled by the sibling branch above)
247                         selection->clear();
248                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path"));
249                         SnapManager &m = desktop->namedview->snap_manager;
250                         m.setup(desktop);
251                         m.freeSnap(Inkscape::Snapper::SNAPPOINT_NODE, p);
252                     } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) {
253                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path"));
254                     }
255                 }
256                 pc->sa = anchor;
257                 spdc_set_startpoint(pc, p);
258                 ret = TRUE;
259                 break;
260         }
262         pc->is_drawing = true;
263     }
264     return ret;
267 static gint
268 pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent)
270     if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) {
271         // mouse was accidentally moved during Ctrl+click;
272         // ignore the motion and create a single point
273         pc->is_drawing = false;
274         return TRUE;
275     }
276     gint ret = FALSE;
277     SPDesktop *const dt = pc->desktop;
279     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
280     if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
281         // allow scrolling
282         return FALSE;
283     }
285     if ( ( mevent.state & GDK_BUTTON1_MASK ) && !pc->grab && pc->is_drawing) {
286         /* Grab mouse, so release will not pass unnoticed */
287         pc->grab = SP_CANVAS_ITEM(dt->acetate);
288         sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK   |
289                                         GDK_BUTTON_RELEASE_MASK |
290                                         GDK_POINTER_MOTION_MASK  ),
291                             NULL, mevent.time);
292     }
294     /* Find desktop coordinates */
295     NR::Point p = dt->w2d(NR::Point(mevent.x, mevent.y));
297     /* Test whether we hit any anchor. */
298     SPDrawAnchor *anchor = spdc_test_inside(pc, NR::Point(mevent.x, mevent.y));
300     switch (pc->state) {
301         case SP_PENCIL_CONTEXT_ADDLINE:
302             /* Set red endpoint */
303             if (anchor) {
304                 p = anchor->dp;
305             } else {
306                 spdc_endpoint_snap(pc, p, mevent.state);
307             }
308             spdc_set_endpoint(pc, p);
309             ret = TRUE;
310             break;
311         default:
312             /* We may be idle or already freehand */
313             if ( mevent.state & GDK_BUTTON1_MASK && pc->is_drawing ) {
314                 pc->state = SP_PENCIL_CONTEXT_FREEHAND;
315                 if ( !pc->sa && !pc->green_anchor ) {
316                     /* Create green anchor */
317                     pc->green_anchor = sp_draw_anchor_new(pc, pc->green_curve, TRUE, pc->p[0]);
318                 }
319                 /** \todo
320                  * fixme: I am not sure whether we want to snap to anchors
321                  * in middle of freehand (Lauris)
322                  */
323                 if (anchor) {
324                     p = anchor->dp;
325                 } else if ((mevent.state & GDK_SHIFT_MASK) == 0) {
326                     SnapManager &m = dt->namedview->snap_manager;
327                     m.setup(dt, NULL);
328                     m.freeSnap(Inkscape::Snapper::SNAPPOINT_NODE, p);
329                 }
330                 if ( pc->npoints != 0 ) { // buttonpress may have happened before we entered draw context!
331                     spdc_add_freehand_point(pc, p, mevent.state);
332                     ret = TRUE;
333                 }
335                 if (anchor && !pc->anchor_statusbar) {
336                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path."));
337                     pc->anchor_statusbar = true;
338                 } else if (!anchor && pc->anchor_statusbar) {
339                     pc->_message_context->clear();
340                     pc->anchor_statusbar = false;
341                 } else if (!anchor) {
342                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path"));
343                 }
345             } else {
346                 if (anchor && !pc->anchor_statusbar) {
347                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point."));
348                     pc->anchor_statusbar = true;
349                 } else if (!anchor && pc->anchor_statusbar) {
350                     pc->_message_context->clear();
351                     pc->anchor_statusbar = false;
352                 }
353             }
354             break;
355     }
356     return ret;
359 static gint
360 pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
362     gint ret = FALSE;
364     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
365     if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
366         SPDesktop *const dt = pc->desktop;
368         pc->is_drawing = false;
370         /* Find desktop coordinates */
371         NR::Point p = dt->w2d(NR::Point(revent.x, revent.y));
373         /* Test whether we hit any anchor. */
374         SPDrawAnchor *anchor = spdc_test_inside(pc, NR::Point(revent.x,
375                                                               revent.y));
377         switch (pc->state) {
378             case SP_PENCIL_CONTEXT_IDLE:
379                 /* Releasing button in idle mode means single click */
380                 /* We have already set up start point/anchor in button_press */
381                 if (!(revent.state & GDK_CONTROL_MASK)) {
382                     // Ctrl+click creates a single point so only set context in ADDLINE mode when Ctrl isn't pressed
383                     pc->state = SP_PENCIL_CONTEXT_ADDLINE;
384                 }
385                 ret = TRUE;
386                 break;
387             case SP_PENCIL_CONTEXT_ADDLINE:
388                 /* Finish segment now */
389                 if (anchor) {
390                     p = anchor->dp;
391                 } else {
392                     spdc_endpoint_snap(pc, p, revent.state);
393                 }
394                 pc->ea = anchor;
395                 spdc_set_endpoint(pc, p);
396                 spdc_finish_endpoint(pc);
397                 pc->state = SP_PENCIL_CONTEXT_IDLE;
398                 ret = TRUE;
399                 break;
400             case SP_PENCIL_CONTEXT_FREEHAND:
401                 /* Finish segment now */
402                 /// \todo fixme: Clean up what follows (Lauris)
403                 if (anchor) {
404                     p = anchor->dp;
405                 }
406                 pc->ea = anchor;
407                 /* Write curves to object */
409                 dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));
411                 spdc_concat_colors_and_flush(pc, FALSE);
412                 pc->sa = NULL;
413                 pc->ea = NULL;
414                 if (pc->green_anchor) {
415                     pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
416                 }
417                 pc->state = SP_PENCIL_CONTEXT_IDLE;
418                 ret = TRUE;
419                 break;
420             default:
421                 break;
422         }
424         if (pc->grab) {
425             /* Release grab now */
426             sp_canvas_item_ungrab(pc->grab, revent.time);
427             pc->grab = NULL;
428         }
430         ret = TRUE;
431     }
432     return ret;
435 static void
436 pencil_cancel (SPPencilContext *const pc) 
438     if (pc->grab) {
439         /* Release grab now */
440         sp_canvas_item_ungrab(pc->grab, 0);
441         pc->grab = NULL;
442     }
444     pc->is_drawing = false;
446     pc->state = SP_PENCIL_CONTEXT_IDLE;
448     pc->red_curve->reset();
449     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
450     while (pc->green_bpaths) {
451         gtk_object_destroy(GTK_OBJECT(pc->green_bpaths->data));
452         pc->green_bpaths = g_slist_remove(pc->green_bpaths, pc->green_bpaths->data);
453     }
454     pc->green_curve->reset();
455     if (pc->green_anchor) {
456         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
457     }
459     pc->_message_context->clear();
460     pc->_message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled"));
462     sp_canvas_end_forced_full_redraws(pc->desktop->canvas);
466 static gint
467 pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state)
469     gint ret = FALSE;
470     switch (keyval) {
471         case GDK_Up:
472         case GDK_Down:
473         case GDK_KP_Up:
474         case GDK_KP_Down:
475             // Prevent the zoom field from activation.
476             if (!mod_ctrl_only(state)) {
477                 ret = TRUE;
478             }
479             break;
480         case GDK_Escape:
481             if (pc->npoints != 0) {
482                 // if drawing, cancel, otherwise pass it up for deselecting
483                 if (pc->is_drawing) {
484                     pencil_cancel (pc);
485                     ret = TRUE;
486                 }
487             }
488             break;
489         case GDK_z:
490         case GDK_Z:
491             if (mod_ctrl_only(state) && pc->npoints != 0) {
492                 // if drawing, cancel, otherwise pass it up for undo
493                 if (pc->is_drawing) {
494                     pencil_cancel (pc);
495                     ret = TRUE;
496                 }
497             }
498             break;
499         case GDK_g:
500         case GDK_G:
501             if (mod_shift_only(state)) {
502                 sp_selection_to_guides();
503                 ret = true;
504             }
505             break;
506         default:
507             break;
508     }
509     return ret;
512 /**
513  * Reset points and set new starting point.
514  */
515 static void
516 spdc_set_startpoint(SPPencilContext *const pc, NR::Point const p)
518     pc->npoints = 0;
519     pc->red_curve_is_valid = false;
520     if (in_svg_plane(p)) {
521         pc->p[pc->npoints++] = p;
522     }
525 /**
526  * Change moving endpoint position.
527  * <ul>
528  * <li>Ctrl constrains to moving to H/V direction, snapping in given direction.
529  * <li>Otherwise we snap freely to whatever attractors are available.
530  * </ul>
531  *
532  * Number of points is (re)set to 2 always, 2nd point is modified.
533  * We change RED curve.
534  */
535 static void
536 spdc_set_endpoint(SPPencilContext *const pc, NR::Point const p)
538     if (pc->npoints == 0) {
539         return;
540         /* May occur if first point wasn't in SVG plane (e.g. weird w2d transform, perhaps from bad
541          * zoom setting).
542          */
543     }
544     g_return_if_fail( pc->npoints > 0 );
546     pc->red_curve->reset();
547     if ( ( p == pc->p[0] )
548          || !in_svg_plane(p) )
549     {
550         pc->npoints = 1;
551     } else {
552         pc->p[1] = p;
553         pc->npoints = 2;
555         pc->red_curve->moveto(pc->p[0]);
556         pc->red_curve->lineto(pc->p[1]);
557         pc->red_curve_is_valid = true;
559         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
560     }
563 /**
564  * Finalize addline.
565  *
566  * \todo
567  * fixme: I'd like remove red reset from concat colors (lauris).
568  * Still not sure, how it will make most sense.
569  */
570 static void
571 spdc_finish_endpoint(SPPencilContext *const pc)
573     if ( ( SP_CURVE_LENGTH(pc->red_curve) != 2 )
574          || ( SP_CURVE_SEGMENT(pc->red_curve, 0)->c(3) ==
575               SP_CURVE_SEGMENT(pc->red_curve, 1)->c(3)   ) )
576     {
577         pc->red_curve->reset();
578         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
579     } else {
580         /* Write curves to object. */
581         spdc_concat_colors_and_flush(pc, FALSE);
582         pc->sa = NULL;
583         pc->ea = NULL;
584     }
587 static void
588 spdc_add_freehand_point(SPPencilContext *pc, NR::Point p, guint /*state*/)
590     g_assert( pc->npoints > 0 );
591     g_return_if_fail(unsigned(pc->npoints) < G_N_ELEMENTS(pc->p));
593     if ( ( p != pc->p[ pc->npoints - 1 ] )
594          && in_svg_plane(p) )
595     {
596         pc->p[pc->npoints++] = p;
597         fit_and_split(pc);
598     }
601 static inline double
602 square(double const x)
604     return x * x;
607 static void
608 fit_and_split(SPPencilContext *pc)
610     g_assert( pc->npoints > 1 );
612     double const tolerance_sq = square( NR::expansion(pc->desktop->w2d())
613                                         * prefs_get_double_attribute_limited("tools.freehand.pencil",
614                                                                              "tolerance", 10.0, 1.0, 100.0) );
616     NR::Point b[4];
617     g_assert(is_zero(pc->req_tangent)
618              || is_unit_vector(pc->req_tangent));
619     NR::Point const tHatEnd(0, 0);
620     int const n_segs = sp_bezier_fit_cubic_full(b, NULL, pc->p, pc->npoints,
621                                                 pc->req_tangent, tHatEnd, tolerance_sq, 1);
622     if ( n_segs > 0
623          && unsigned(pc->npoints) < G_N_ELEMENTS(pc->p) )
624     {
625         /* Fit and draw and reset state */
626         pc->red_curve->reset();
627         pc->red_curve->moveto(b[0]);
628         pc->red_curve->curveto(b[1], b[2], b[3]);
629         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
630         pc->red_curve_is_valid = true;
631     } else {
632         /* Fit and draw and copy last point */
634         g_assert(!pc->red_curve->is_empty());
636         /* Set up direction of next curve. */
637         {
638             NArtBpath const &last_seg = *pc->red_curve->last_bpath();
639             pc->p[0] = last_seg.c(3);
640             pc->npoints = 1;
641             g_assert( last_seg.code == NR_CURVETO );
642             /* Relevance: validity of last_seg.c(2). */
643             NR::Point const req_vec( pc->p[0] - last_seg.c(2) );
644             pc->req_tangent = ( ( NR::is_zero(req_vec) || !in_svg_plane(req_vec) )
645                                 ? NR::Point(0, 0)
646                                 : NR::unit_vector(req_vec) );
647         }
649         pc->green_curve->append_continuous(pc->red_curve, 0.0625);
650         SPCurve *curve = pc->red_curve->copy();
652         /// \todo fixme:
653         SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(pc->desktop), curve);
654         curve->unref();
655         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), pc->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
657         pc->green_bpaths = g_slist_prepend(pc->green_bpaths, cshape);
659         pc->red_curve_is_valid = false;
660     }
664 /*
665   Local Variables:
666   mode:c++
667   c-file-style:"stroustrup"
668   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
669   indent-tabs-mode:nil
670   fill-column:99
671   End:
672 */
673 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :