Code

snapindicator in freehand
[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 "display/snap-indicator.h"
36 #include <glibmm/i18n.h>
37 #include "libnr/in-svg-plane.h"
38 #include "libnr/n-art-bpath.h"
39 #include "context-fns.h"
40 #include "sp-namedview.h"
41 #include "xml/repr.h"
42 #include "document.h"
43 #include "desktop-style.h"
44 #include "macros.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 const &m = desktop->namedview->snap_manager;
250                         p = m.freeSnap(Inkscape::Snapper::SNAPPOINT_NODE, p, NULL).getPoint();
251                     } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) {
252                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path"));
253                     }
254                 }
255                 pc->sa = anchor;
256                 spdc_set_startpoint(pc, p);
257                 ret = TRUE;
258                 break;
259         }
261         pc->is_drawing = true;
262     }
263     return ret;
266 static gint
267 pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent)
269     if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) {
270         // mouse was accidentally moved during Ctrl+click;
271         // ignore the motion and create a single point
272         pc->is_drawing = false;
273         return TRUE;
274     }
275     gint ret = FALSE;
276     SPDesktop *const dt = pc->desktop;
278     dt->snapindicator->remove_snappoint();
280     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
281     if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
282         // allow scrolling
283         return FALSE;
284     }
286     if ( ( mevent.state & GDK_BUTTON1_MASK ) && !pc->grab && pc->is_drawing) {
287         /* Grab mouse, so release will not pass unnoticed */
288         pc->grab = SP_CANVAS_ITEM(dt->acetate);
289         sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK   |
290                                         GDK_BUTTON_RELEASE_MASK |
291                                         GDK_POINTER_MOTION_MASK  ),
292                             NULL, mevent.time);
293     }
295     /* Find desktop coordinates */
296     NR::Point p = dt->w2d(NR::Point(mevent.x, mevent.y));
298     /* Test whether we hit any anchor. */
299     SPDrawAnchor *anchor = spdc_test_inside(pc, NR::Point(mevent.x, mevent.y));
301     switch (pc->state) {
302         case SP_PENCIL_CONTEXT_ADDLINE:
303             /* Set red endpoint */
304             if (anchor) {
305                 p = anchor->dp;
306             } else {
307                 spdc_endpoint_snap(pc, p, mevent.state);
308             }
309             spdc_set_endpoint(pc, p);
310             ret = TRUE;
311             break;
312         default:
313             /* We may be idle or already freehand */
314             if ( mevent.state & GDK_BUTTON1_MASK && pc->is_drawing ) {
315                 pc->state = SP_PENCIL_CONTEXT_FREEHAND;
316                 if ( !pc->sa && !pc->green_anchor ) {
317                     /* Create green anchor */
318                     pc->green_anchor = sp_draw_anchor_new(pc, pc->green_curve, TRUE, pc->p[0]);
319                 }
320                 /** \todo
321                  * fixme: I am not sure whether we want to snap to anchors
322                  * in middle of freehand (Lauris)
323                  */
324                 if (anchor) {
325                     p = anchor->dp;
326                 } else if ((mevent.state & GDK_SHIFT_MASK) == 0) {
327                     SnapManager const &m = dt->namedview->snap_manager;
328                     Inkscape::SnappedPoint const s = m.freeSnap(Inkscape::Snapper::SNAPPOINT_NODE, p, NULL);
329                     p = s.getPoint();
330                     if (s.getDistance() < NR_HUGE) {
331                         dt->snapindicator->set_new_snappoint(p.to_2geom());
332                     }
333                 }
334                 if ( pc->npoints != 0 ) { // buttonpress may have happened before we entered draw context!
335                     spdc_add_freehand_point(pc, p, mevent.state);
336                     ret = TRUE;
337                 }
339                 if (anchor && !pc->anchor_statusbar) {
340                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path."));
341                     pc->anchor_statusbar = true;
342                 } else if (!anchor && pc->anchor_statusbar) {
343                     pc->_message_context->clear();
344                     pc->anchor_statusbar = false;
345                 } else if (!anchor) {
346                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path"));
347                 }
349             } else {
350                 if (anchor && !pc->anchor_statusbar) {
351                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point."));
352                     pc->anchor_statusbar = true;
353                 } else if (!anchor && pc->anchor_statusbar) {
354                     pc->_message_context->clear();
355                     pc->anchor_statusbar = false;
356                 }
357             }
358             break;
359     }
360     return ret;
363 static gint
364 pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
366     gint ret = FALSE;
368     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
369     if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
370         SPDesktop *const dt = pc->desktop;
372         pc->is_drawing = false;
374         /* Find desktop coordinates */
375         NR::Point p = dt->w2d(NR::Point(revent.x, revent.y));
377         /* Test whether we hit any anchor. */
378         SPDrawAnchor *anchor = spdc_test_inside(pc, NR::Point(revent.x,
379                                                               revent.y));
381         switch (pc->state) {
382             case SP_PENCIL_CONTEXT_IDLE:
383                 /* Releasing button in idle mode means single click */
384                 /* We have already set up start point/anchor in button_press */
385                 if (!(revent.state & GDK_CONTROL_MASK)) {
386                     // Ctrl+click creates a single point so only set context in ADDLINE mode when Ctrl isn't pressed
387                     pc->state = SP_PENCIL_CONTEXT_ADDLINE;
388                 }
389                 ret = TRUE;
390                 break;
391             case SP_PENCIL_CONTEXT_ADDLINE:
392                 /* Finish segment now */
393                 if (anchor) {
394                     p = anchor->dp;
395                 } else {
396                     spdc_endpoint_snap(pc, p, revent.state);
397                 }
398                 pc->ea = anchor;
399                 spdc_set_endpoint(pc, p);
400                 spdc_finish_endpoint(pc);
401                 pc->state = SP_PENCIL_CONTEXT_IDLE;
402                 ret = TRUE;
403                 break;
404             case SP_PENCIL_CONTEXT_FREEHAND:
405                 /* Finish segment now */
406                 /// \todo fixme: Clean up what follows (Lauris)
407                 if (anchor) {
408                     p = anchor->dp;
409                 }
410                 pc->ea = anchor;
411                 /* Write curves to object */
413                 dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));
415                 spdc_concat_colors_and_flush(pc, FALSE);
416                 pc->sa = NULL;
417                 pc->ea = NULL;
418                 if (pc->green_anchor) {
419                     pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
420                 }
421                 pc->state = SP_PENCIL_CONTEXT_IDLE;
422                 ret = TRUE;
423                 break;
424             default:
425                 break;
426         }
428         if (pc->grab) {
429             /* Release grab now */
430             sp_canvas_item_ungrab(pc->grab, revent.time);
431             pc->grab = NULL;
432         }
434         ret = TRUE;
435     }
436     return ret;
439 static void
440 pencil_cancel (SPPencilContext *const pc) 
442     if (pc->grab) {
443         /* Release grab now */
444         sp_canvas_item_ungrab(pc->grab, 0);
445         pc->grab = NULL;
446     }
448     pc->is_drawing = false;
450     pc->state = SP_PENCIL_CONTEXT_IDLE;
452     sp_curve_reset(pc->red_curve);
453     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
454     while (pc->green_bpaths) {
455         gtk_object_destroy(GTK_OBJECT(pc->green_bpaths->data));
456         pc->green_bpaths = g_slist_remove(pc->green_bpaths, pc->green_bpaths->data);
457     }
458     sp_curve_reset(pc->green_curve);
459     if (pc->green_anchor) {
460         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
461     }
463     pc->_message_context->clear();
464     pc->_message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled"));
466     sp_canvas_end_forced_full_redraws(pc->desktop->canvas);
470 static gint
471 pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state)
473     gint ret = FALSE;
474     switch (keyval) {
475         case GDK_Up:
476         case GDK_Down:
477         case GDK_KP_Up:
478         case GDK_KP_Down:
479             // Prevent the zoom field from activation.
480             if (!mod_ctrl_only(state)) {
481                 ret = TRUE;
482             }
483             break;
484         case GDK_Escape:
485             if (pc->npoints != 0) {
486                 // if drawing, cancel, otherwise pass it up for deselecting
487                 if (pc->is_drawing) {
488                     pencil_cancel (pc);
489                     ret = TRUE;
490                 }
491             }
492             break;
493         case GDK_z:
494         case GDK_Z:
495             if (mod_ctrl_only(state) && pc->npoints != 0) {
496                 // if drawing, cancel, otherwise pass it up for undo
497                 if (pc->is_drawing) {
498                     pencil_cancel (pc);
499                     ret = TRUE;
500                 }
501             }
502             break;
503         case GDK_g:
504         case GDK_G:
505             if (mod_shift_only(state)) {
506                 sp_selection_to_guides();
507                 ret = true;
508             }
509             break;
510         default:
511             break;
512     }
513     return ret;
516 /**
517  * Reset points and set new starting point.
518  */
519 static void
520 spdc_set_startpoint(SPPencilContext *const pc, NR::Point const p)
522     pc->npoints = 0;
523     pc->red_curve_is_valid = false;
524     if (in_svg_plane(p)) {
525         pc->p[pc->npoints++] = p;
526     }
529 /**
530  * Change moving endpoint position.
531  * <ul>
532  * <li>Ctrl constrains to moving to H/V direction, snapping in given direction.
533  * <li>Otherwise we snap freely to whatever attractors are available.
534  * </ul>
535  *
536  * Number of points is (re)set to 2 always, 2nd point is modified.
537  * We change RED curve.
538  */
539 static void
540 spdc_set_endpoint(SPPencilContext *const pc, NR::Point const p)
542     if (pc->npoints == 0) {
543         return;
544         /* May occur if first point wasn't in SVG plane (e.g. weird w2d transform, perhaps from bad
545          * zoom setting).
546          */
547     }
548     g_return_if_fail( pc->npoints > 0 );
550     sp_curve_reset(pc->red_curve);
551     if ( ( p == pc->p[0] )
552          || !in_svg_plane(p) )
553     {
554         pc->npoints = 1;
555     } else {
556         pc->p[1] = p;
557         pc->npoints = 2;
559         sp_curve_moveto(pc->red_curve, pc->p[0]);
560         sp_curve_lineto(pc->red_curve, pc->p[1]);
561         pc->red_curve_is_valid = true;
563         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
564     }
567 /**
568  * Finalize addline.
569  *
570  * \todo
571  * fixme: I'd like remove red reset from concat colors (lauris).
572  * Still not sure, how it will make most sense.
573  */
574 static void
575 spdc_finish_endpoint(SPPencilContext *const pc)
577     if ( ( SP_CURVE_LENGTH(pc->red_curve) != 2 )
578          || ( SP_CURVE_SEGMENT(pc->red_curve, 0)->c(3) ==
579               SP_CURVE_SEGMENT(pc->red_curve, 1)->c(3)   ) )
580     {
581         sp_curve_reset(pc->red_curve);
582         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
583     } else {
584         /* Write curves to object. */
585         spdc_concat_colors_and_flush(pc, FALSE);
586         pc->sa = NULL;
587         pc->ea = NULL;
588     }
591 static void
592 spdc_add_freehand_point(SPPencilContext *pc, NR::Point p, guint /*state*/)
594     g_assert( pc->npoints > 0 );
595     g_return_if_fail(unsigned(pc->npoints) < G_N_ELEMENTS(pc->p));
597     if ( ( p != pc->p[ pc->npoints - 1 ] )
598          && in_svg_plane(p) )
599     {
600         pc->p[pc->npoints++] = p;
601         fit_and_split(pc);
602     }
605 static inline double
606 square(double const x)
608     return x * x;
611 static void
612 fit_and_split(SPPencilContext *pc)
614     g_assert( pc->npoints > 1 );
616     double const tolerance_sq = square( NR::expansion(pc->desktop->w2d())
617                                         * prefs_get_double_attribute_limited("tools.freehand.pencil",
618                                                                              "tolerance", 10.0, 1.0, 100.0) );
620     NR::Point b[4];
621     g_assert(is_zero(pc->req_tangent)
622              || is_unit_vector(pc->req_tangent));
623     NR::Point const tHatEnd(0, 0);
624     int const n_segs = sp_bezier_fit_cubic_full(b, NULL, pc->p, pc->npoints,
625                                                 pc->req_tangent, tHatEnd, tolerance_sq, 1);
626     if ( n_segs > 0
627          && unsigned(pc->npoints) < G_N_ELEMENTS(pc->p) )
628     {
629         /* Fit and draw and reset state */
630         sp_curve_reset(pc->red_curve);
631         sp_curve_moveto(pc->red_curve, b[0]);
632         sp_curve_curveto(pc->red_curve, b[1], b[2], b[3]);
633         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
634         pc->red_curve_is_valid = true;
635     } else {
636         /* Fit and draw and copy last point */
638         g_assert(!sp_curve_empty(pc->red_curve));
640         /* Set up direction of next curve. */
641         {
642             NArtBpath const &last_seg = *sp_curve_last_bpath(pc->red_curve);
643             pc->p[0] = last_seg.c(3);
644             pc->npoints = 1;
645             g_assert( last_seg.code == NR_CURVETO );
646             /* Relevance: validity of last_seg.c(2). */
647             NR::Point const req_vec( pc->p[0] - last_seg.c(2) );
648             pc->req_tangent = ( ( NR::is_zero(req_vec) || !in_svg_plane(req_vec) )
649                                 ? NR::Point(0, 0)
650                                 : NR::unit_vector(req_vec) );
651         }
653         sp_curve_append_continuous(pc->green_curve, pc->red_curve, 0.0625);
654         SPCurve *curve = sp_curve_copy(pc->red_curve);
656         /// \todo fixme:
657         SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(pc->desktop), curve);
658         sp_curve_unref(curve);
659         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), pc->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
661         pc->green_bpaths = g_slist_prepend(pc->green_bpaths, cshape);
663         pc->red_curve_is_valid = false;
664     }
668 /*
669   Local Variables:
670   mode:c++
671   c-file-style:"stroustrup"
672   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
673   indent-tabs-mode:nil
674   fill-column:99
675   End:
676 */
677 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :