Code

Revert #17388 as per buliabyaks comment in LP
[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"
45 static void sp_pencil_context_class_init(SPPencilContextClass *klass);
46 static void sp_pencil_context_init(SPPencilContext *pc);
47 static void sp_pencil_context_setup(SPEventContext *ec);
48 static void sp_pencil_context_dispose(GObject *object);
50 static gint sp_pencil_context_root_handler(SPEventContext *event_context, GdkEvent *event);
51 static gint pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent);
52 static gint pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent);
53 static gint pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent);
54 static gint pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state);
56 static void spdc_set_startpoint(SPPencilContext *pc, NR::Point const p);
57 static void spdc_set_endpoint(SPPencilContext *pc, NR::Point const p);
58 static void spdc_finish_endpoint(SPPencilContext *pc);
59 static void spdc_add_freehand_point(SPPencilContext *pc, NR::Point p, guint state);
60 static void fit_and_split(SPPencilContext *pc);
63 static SPDrawContextClass *pencil_parent_class;
65 /**
66  * Register SPPencilContext class with Gdk and return its type number.
67  */
68 GType
69 sp_pencil_context_get_type()
70 {
71     static GType type = 0;
72     if (!type) {
73         GTypeInfo info = {
74             sizeof(SPPencilContextClass),
75             NULL, NULL,
76             (GClassInitFunc) sp_pencil_context_class_init,
77             NULL, NULL,
78             sizeof(SPPencilContext),
79             4,
80             (GInstanceInitFunc) sp_pencil_context_init,
81             NULL,   /* value_table */
82         };
83         type = g_type_register_static(SP_TYPE_DRAW_CONTEXT, "SPPencilContext", &info, (GTypeFlags)0);
84     }
85     return type;
86 }
88 /**
89  * Initialize SPPencilContext vtable.
90  */
91 static void
92 sp_pencil_context_class_init(SPPencilContextClass *klass)
93 {
94     GObjectClass *object_class;
95     SPEventContextClass *event_context_class;
97     object_class = (GObjectClass *) klass;
98     event_context_class = (SPEventContextClass *) klass;
100     pencil_parent_class = (SPDrawContextClass*)g_type_class_peek_parent(klass);
102     object_class->dispose = sp_pencil_context_dispose;
104     event_context_class->setup = sp_pencil_context_setup;
105     event_context_class->root_handler = sp_pencil_context_root_handler;
108 /**
109  * Callback to initialize SPPencilContext object.
110  */
111 static void
112 sp_pencil_context_init(SPPencilContext *pc)
114     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
116     event_context->cursor_shape = cursor_pencil_xpm;
117     event_context->hot_x = 4;
118     event_context->hot_y = 4;
120     pc->npoints = 0;
121     pc->state = SP_PENCIL_CONTEXT_IDLE;
122     pc->req_tangent = NR::Point(0, 0);
125 /**
126  * Callback to setup SPPencilContext object.
127  */
128 static void
129 sp_pencil_context_setup(SPEventContext *ec)
131     if (prefs_get_int_attribute("tools.freehand.pencil", "selcue", 0) != 0) {
132         ec->enableSelectionCue();
133     }
135     if (((SPEventContextClass *) pencil_parent_class)->setup) {
136         ((SPEventContextClass *) pencil_parent_class)->setup(ec);
137     }
139     SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
140     pc->is_drawing = false;
142     pc->anchor_statusbar = false;
145 static void
146 sp_pencil_context_dispose(GObject *object)
148     G_OBJECT_CLASS(pencil_parent_class)->dispose(object);
151 /** Snaps new node relative to the previous node. */
152 static void
153 spdc_endpoint_snap(SPPencilContext const *pc, NR::Point &p, guint const state)
155     spdc_endpoint_snap_rotation(pc, p, pc->p[0], state);
156     spdc_endpoint_snap_free(pc, p, state);
159 /**
160  * Callback for handling all pencil context events.
161  */
162 gint
163 sp_pencil_context_root_handler(SPEventContext *const ec, GdkEvent *event)
165     SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
167     gint ret = FALSE;
169     switch (event->type) {
170         case GDK_BUTTON_PRESS:
171             ret = pencil_handle_button_press(pc, event->button);
172             break;
174         case GDK_MOTION_NOTIFY:
175             ret = pencil_handle_motion_notify(pc, event->motion);
176             break;
178         case GDK_BUTTON_RELEASE:
179             ret = pencil_handle_button_release(pc, event->button);
180             break;
182         case GDK_KEY_PRESS:
183             ret = pencil_handle_key_press(pc, get_group0_keyval (&event->key), event->key.state);
184             break;
186         default:
187             break;
188     }
190     if (!ret) {
191         gint (*const parent_root_handler)(SPEventContext *, GdkEvent *)
192             = ((SPEventContextClass *) pencil_parent_class)->root_handler;
193         if (parent_root_handler) {
194             ret = parent_root_handler(ec, event);
195         }
196     }
198     return ret;
201 static gint
202 pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent)
204     gint ret = FALSE;
205     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
206     if ( bevent.button == 1  && !event_context->space_panning) {
208         SPDrawContext *dc = SP_DRAW_CONTEXT (pc);
209         SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
210         Inkscape::Selection *selection = sp_desktop_selection(desktop);
212         if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
213             return TRUE;
214         }
216         NR::Point const button_w(bevent.x, bevent.y);
218         /* Find desktop coordinates */
219         NR::Point p = pc->desktop->w2d(button_w);
221         /* Test whether we hit any anchor. */
222         SPDrawAnchor *anchor = spdc_test_inside(pc, button_w);
224         switch (pc->state) {
225             case SP_PENCIL_CONTEXT_ADDLINE:
226                 /* Current segment will be finished with release */
227                 ret = TRUE;
228                 break;
229             default:
230                 /* Set first point of sequence */
231                 if (bevent.state & GDK_CONTROL_MASK) {
232                     freehand_create_single_dot(event_context, p, "tools.freehand.pencil", bevent.state);
233                     ret = true;
234                     break;
235                 }
236                 if (anchor) {
237                     p = anchor->dp;
238                     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path"));
239                 } else {
241                     if (!(bevent.state & GDK_SHIFT_MASK)) {
243                         // This is the first click of a new curve; deselect item so that
244                         // this curve is not combined with it (unless it is drawn from its
245                         // anchor, which is handled by the sibling branch above)
246                         selection->clear();
247                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path"));
248                         SnapManager const &m = desktop->namedview->snap_manager;
249                         p = m.freeSnap(Inkscape::Snapper::SNAPPOINT_NODE, p, NULL).getPoint();
250                     } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) {
251                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path"));
252                     }
253                 }
254                 pc->sa = anchor;
255                 spdc_set_startpoint(pc, p);
256                 ret = TRUE;
257                 break;
258         }
260         pc->is_drawing = true;
261     }
262     return ret;
265 static gint
266 pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent)
268     if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) {
269         // mouse was accidentally moved during Ctrl+click;
270         // ignore the motion and create a single point
271         pc->is_drawing = false;
272         return TRUE;
273     }
274     gint ret = FALSE;
275     SPDesktop *const dt = pc->desktop;
277     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
278     if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
279         // allow scrolling
280         return FALSE;
281     }
283     if ( ( mevent.state & GDK_BUTTON1_MASK ) && !pc->grab && pc->is_drawing) {
284         /* Grab mouse, so release will not pass unnoticed */
285         pc->grab = SP_CANVAS_ITEM(dt->acetate);
286         sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK   |
287                                         GDK_BUTTON_RELEASE_MASK |
288                                         GDK_POINTER_MOTION_MASK  ),
289                             NULL, mevent.time);
290     }
292     /* Find desktop coordinates */
293     NR::Point p = dt->w2d(NR::Point(mevent.x, mevent.y));
295     /* Test whether we hit any anchor. */
296     SPDrawAnchor *anchor = spdc_test_inside(pc, NR::Point(mevent.x, mevent.y));
298     switch (pc->state) {
299         case SP_PENCIL_CONTEXT_ADDLINE:
300             /* Set red endpoint */
301             if (anchor) {
302                 p = anchor->dp;
303             } else {
304                 spdc_endpoint_snap(pc, p, mevent.state);
305             }
306             spdc_set_endpoint(pc, p);
307             ret = TRUE;
308             break;
309         default:
310             /* We may be idle or already freehand */
311             if ( mevent.state & GDK_BUTTON1_MASK && pc->is_drawing ) {
312                 pc->state = SP_PENCIL_CONTEXT_FREEHAND;
313                 if ( !pc->sa && !pc->green_anchor ) {
314                     /* Create green anchor */
315                     pc->green_anchor = sp_draw_anchor_new(pc, pc->green_curve, TRUE, pc->p[0]);
316                 }
317                 /** \todo
318                  * fixme: I am not sure whether we want to snap to anchors
319                  * in middle of freehand (Lauris)
320                  */
321                 if (anchor) {
322                     p = anchor->dp;
323                 } else if ((mevent.state & GDK_SHIFT_MASK) == 0) {
324                     SnapManager const &m = dt->namedview->snap_manager;
325                     p = m.freeSnap(Inkscape::Snapper::SNAPPOINT_NODE, p, NULL).getPoint();
326                 }
327                 if ( pc->npoints != 0 ) { // buttonpress may have happened before we entered draw context!
328                     spdc_add_freehand_point(pc, p, mevent.state);
329                     ret = TRUE;
330                 }
332                 if (anchor && !pc->anchor_statusbar) {
333                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path."));
334                     pc->anchor_statusbar = true;
335                 } else if (!anchor && pc->anchor_statusbar) {
336                     pc->_message_context->clear();
337                     pc->anchor_statusbar = false;
338                 } else if (!anchor) {
339                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path"));
340                 }
342             } else {
343                 if (anchor && !pc->anchor_statusbar) {
344                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point."));
345                     pc->anchor_statusbar = true;
346                 } else if (!anchor && pc->anchor_statusbar) {
347                     pc->_message_context->clear();
348                     pc->anchor_statusbar = false;
349                 }
350             }
351             break;
352     }
353     return ret;
356 static gint
357 pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
359     gint ret = FALSE;
361     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
362     if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
363         SPDesktop *const dt = pc->desktop;
365         pc->is_drawing = false;
367         /* Find desktop coordinates */
368         NR::Point p = dt->w2d(NR::Point(revent.x, revent.y));
370         /* Test whether we hit any anchor. */
371         SPDrawAnchor *anchor = spdc_test_inside(pc, NR::Point(revent.x,
372                                                               revent.y));
374         switch (pc->state) {
375             case SP_PENCIL_CONTEXT_IDLE:
376                 /* Releasing button in idle mode means single click */
377                 /* We have already set up start point/anchor in button_press */
378                 if (!(revent.state & GDK_CONTROL_MASK)) {
379                     // Ctrl+click creates a single point so only set context in ADDLINE mode when Ctrl isn't pressed
380                     pc->state = SP_PENCIL_CONTEXT_ADDLINE;
381                 }
382                 ret = TRUE;
383                 break;
384             case SP_PENCIL_CONTEXT_ADDLINE:
385                 /* Finish segment now */
386                 if (anchor) {
387                     p = anchor->dp;
388                 } else {
389                     spdc_endpoint_snap(pc, p, revent.state);
390                 }
391                 pc->ea = anchor;
392                 spdc_set_endpoint(pc, p);
393                 spdc_finish_endpoint(pc);
394                 pc->state = SP_PENCIL_CONTEXT_IDLE;
395                 ret = TRUE;
396                 break;
397             case SP_PENCIL_CONTEXT_FREEHAND:
398                 /* Finish segment now */
399                 /// \todo fixme: Clean up what follows (Lauris)
400                 if (anchor) {
401                     p = anchor->dp;
402                 }
403                 pc->ea = anchor;
404                 /* Write curves to object */
406                 dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));
408                 spdc_concat_colors_and_flush(pc, FALSE);
409                 pc->sa = NULL;
410                 pc->ea = NULL;
411                 if (pc->green_anchor) {
412                     pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
413                 }
414                 pc->state = SP_PENCIL_CONTEXT_IDLE;
415                 ret = TRUE;
416                 break;
417             default:
418                 break;
419         }
421         if (pc->grab) {
422             /* Release grab now */
423             sp_canvas_item_ungrab(pc->grab, revent.time);
424             pc->grab = NULL;
425         }
427         ret = TRUE;
428     }
429     return ret;
432 static void
433 pencil_cancel (SPPencilContext *const pc) 
435     if (pc->grab) {
436         /* Release grab now */
437         sp_canvas_item_ungrab(pc->grab, 0);
438         pc->grab = NULL;
439     }
441     pc->is_drawing = false;
443     pc->state = SP_PENCIL_CONTEXT_IDLE;
445     sp_curve_reset(pc->red_curve);
446     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
447     while (pc->green_bpaths) {
448         gtk_object_destroy(GTK_OBJECT(pc->green_bpaths->data));
449         pc->green_bpaths = g_slist_remove(pc->green_bpaths, pc->green_bpaths->data);
450     }
451     sp_curve_reset(pc->green_curve);
452     if (pc->green_anchor) {
453         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
454     }
456     pc->_message_context->clear();
457     pc->_message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled"));
459     sp_canvas_end_forced_full_redraws(pc->desktop->canvas);
463 static gint
464 pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state)
466     gint ret = FALSE;
467     switch (keyval) {
468         case GDK_Up:
469         case GDK_Down:
470         case GDK_KP_Up:
471         case GDK_KP_Down:
472             // Prevent the zoom field from activation.
473             if (!mod_ctrl_only(state)) {
474                 ret = TRUE;
475             }
476             break;
477         case GDK_Escape:
478             if (pc->npoints != 0) {
479                 // if drawing, cancel, otherwise pass it up for deselecting
480                 if (pc->is_drawing) {
481                     pencil_cancel (pc);
482                     ret = TRUE;
483                 }
484             }
485             break;
486         case GDK_z:
487         case GDK_Z:
488             if (mod_ctrl_only(state) && pc->npoints != 0) {
489                 // if drawing, cancel, otherwise pass it up for undo
490                 if (pc->is_drawing) {
491                     pencil_cancel (pc);
492                     ret = TRUE;
493                 }
494             }
495             break;
496         case GDK_g:
497         case GDK_G:
498             if (mod_shift_only(state)) {
499                 sp_selection_to_guides();
500                 ret = true;
501             }
502             break;
503         default:
504             break;
505     }
506     return ret;
509 /**
510  * Reset points and set new starting point.
511  */
512 static void
513 spdc_set_startpoint(SPPencilContext *const pc, NR::Point const p)
515     pc->npoints = 0;
516     pc->red_curve_is_valid = false;
517     if (in_svg_plane(p)) {
518         pc->p[pc->npoints++] = p;
519     }
522 /**
523  * Change moving endpoint position.
524  * <ul>
525  * <li>Ctrl constrains to moving to H/V direction, snapping in given direction.
526  * <li>Otherwise we snap freely to whatever attractors are available.
527  * </ul>
528  *
529  * Number of points is (re)set to 2 always, 2nd point is modified.
530  * We change RED curve.
531  */
532 static void
533 spdc_set_endpoint(SPPencilContext *const pc, NR::Point const p)
535     if (pc->npoints == 0) {
536         return;
537         /* May occur if first point wasn't in SVG plane (e.g. weird w2d transform, perhaps from bad
538          * zoom setting).
539          */
540     }
541     g_return_if_fail( pc->npoints > 0 );
543     sp_curve_reset(pc->red_curve);
544     if ( ( p == pc->p[0] )
545          || !in_svg_plane(p) )
546     {
547         pc->npoints = 1;
548     } else {
549         pc->p[1] = p;
550         pc->npoints = 2;
552         sp_curve_moveto(pc->red_curve, pc->p[0]);
553         sp_curve_lineto(pc->red_curve, pc->p[1]);
554         pc->red_curve_is_valid = true;
556         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
557     }
560 /**
561  * Finalize addline.
562  *
563  * \todo
564  * fixme: I'd like remove red reset from concat colors (lauris).
565  * Still not sure, how it will make most sense.
566  */
567 static void
568 spdc_finish_endpoint(SPPencilContext *const pc)
570     if ( ( SP_CURVE_LENGTH(pc->red_curve) != 2 )
571          || ( SP_CURVE_SEGMENT(pc->red_curve, 0)->c(3) ==
572               SP_CURVE_SEGMENT(pc->red_curve, 1)->c(3)   ) )
573     {
574         sp_curve_reset(pc->red_curve);
575         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
576     } else {
577         /* Write curves to object. */
578         spdc_concat_colors_and_flush(pc, FALSE);
579         pc->sa = NULL;
580         pc->ea = NULL;
581     }
584 static void
585 spdc_add_freehand_point(SPPencilContext *pc, NR::Point p, guint /*state*/)
587     g_assert( pc->npoints > 0 );
588     g_return_if_fail(unsigned(pc->npoints) < G_N_ELEMENTS(pc->p));
590     if ( ( p != pc->p[ pc->npoints - 1 ] )
591          && in_svg_plane(p) )
592     {
593         pc->p[pc->npoints++] = p;
594         fit_and_split(pc);
595     }
598 static inline double
599 square(double const x)
601     return x * x;
604 static void
605 fit_and_split(SPPencilContext *pc)
607     g_assert( pc->npoints > 1 );
609     double const tolerance_sq = square( NR::expansion(pc->desktop->w2d())
610                                         * prefs_get_double_attribute_limited("tools.freehand.pencil",
611                                                                              "tolerance", 10.0, 1.0, 100.0) );
613     NR::Point b[4];
614     g_assert(is_zero(pc->req_tangent)
615              || is_unit_vector(pc->req_tangent));
616     NR::Point const tHatEnd(0, 0);
617     int const n_segs = sp_bezier_fit_cubic_full(b, NULL, pc->p, pc->npoints,
618                                                 pc->req_tangent, tHatEnd, tolerance_sq, 1);
619     if ( n_segs > 0
620          && unsigned(pc->npoints) < G_N_ELEMENTS(pc->p) )
621     {
622         /* Fit and draw and reset state */
623         sp_curve_reset(pc->red_curve);
624         sp_curve_moveto(pc->red_curve, b[0]);
625         sp_curve_curveto(pc->red_curve, b[1], b[2], b[3]);
626         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
627         pc->red_curve_is_valid = true;
628     } else {
629         /* Fit and draw and copy last point */
631         g_assert(!sp_curve_empty(pc->red_curve));
633         /* Set up direction of next curve. */
634         {
635             NArtBpath const &last_seg = *sp_curve_last_bpath(pc->red_curve);
636             pc->p[0] = last_seg.c(3);
637             pc->npoints = 1;
638             g_assert( last_seg.code == NR_CURVETO );
639             /* Relevance: validity of last_seg.c(2). */
640             NR::Point const req_vec( pc->p[0] - last_seg.c(2) );
641             pc->req_tangent = ( ( NR::is_zero(req_vec) || !in_svg_plane(req_vec) )
642                                 ? NR::Point(0, 0)
643                                 : NR::unit_vector(req_vec) );
644         }
646         sp_curve_append_continuous(pc->green_curve, pc->red_curve, 0.0625);
647         SPCurve *curve = sp_curve_copy(pc->red_curve);
649         /// \todo fixme:
650         SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(pc->desktop), curve);
651         sp_curve_unref(curve);
652         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), pc->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
654         pc->green_bpaths = g_slist_prepend(pc->green_bpaths, cshape);
656         pc->red_curve_is_valid = false;
657     }
661 /*
662   Local Variables:
663   mode:c++
664   c-file-style:"stroustrup"
665   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
666   indent-tabs-mode:nil
667   fill-column:99
668   End:
669 */
670 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :