Code

0717724de29f72a437bdda984d76f7f2ef550c14
[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 "preferences.h"
31 #include "snap.h"
32 #include "pixmaps/cursor-pencil.xpm"
33 #include <2geom/sbasis-to-bezier.h>
34 #include <2geom/bezier-utils.h>
35 #include "display/canvas-bpath.h"
36 #include <glibmm/i18n.h>
37 #include "libnr/in-svg-plane.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"
45 #include "livarot/Path.h"
47 static void sp_pencil_context_class_init(SPPencilContextClass *klass);
48 static void sp_pencil_context_init(SPPencilContext *pc);
49 static void sp_pencil_context_setup(SPEventContext *ec);
50 static void sp_pencil_context_dispose(GObject *object);
52 static gint sp_pencil_context_root_handler(SPEventContext *event_context, GdkEvent *event);
53 static gint pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent);
54 static gint pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent);
55 static gint pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent);
56 static gint pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state);
57 static gint pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const state);
59 static void spdc_set_startpoint(SPPencilContext *pc, Geom::Point const p);
60 static void spdc_set_endpoint(SPPencilContext *pc, Geom::Point const p);
61 static void spdc_finish_endpoint(SPPencilContext *pc);
62 static void spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint state);
63 static void fit_and_split(SPPencilContext *pc);
64 static void interpolate(SPPencilContext *pc);
65 static void sketch_interpolate(SPPencilContext *pc);
67 static SPDrawContextClass *pencil_parent_class;
68 static Geom::Point pencil_drag_origin_w(0, 0);
69 static bool pencil_within_tolerance = false;
71 /**
72  * Register SPPencilContext class with Gdk and return its type number.
73  */
74 GType
75 sp_pencil_context_get_type()
76 {
77     static GType type = 0;
78     if (!type) {
79         GTypeInfo info = {
80             sizeof(SPPencilContextClass),
81             NULL, NULL,
82             (GClassInitFunc) sp_pencil_context_class_init,
83             NULL, NULL,
84             sizeof(SPPencilContext),
85             4,
86             (GInstanceInitFunc) sp_pencil_context_init,
87             NULL,   /* value_table */
88         };
89         type = g_type_register_static(SP_TYPE_DRAW_CONTEXT, "SPPencilContext", &info, (GTypeFlags)0);
90     }
91     return type;
92 }
94 /**
95  * Initialize SPPencilContext vtable.
96  */
97 static void
98 sp_pencil_context_class_init(SPPencilContextClass *klass)
99 {
100     GObjectClass *object_class;
101     SPEventContextClass *event_context_class;
103     object_class = (GObjectClass *) klass;
104     event_context_class = (SPEventContextClass *) klass;
106     pencil_parent_class = (SPDrawContextClass*)g_type_class_peek_parent(klass);
108     object_class->dispose = sp_pencil_context_dispose;
110     event_context_class->setup = sp_pencil_context_setup;
111     event_context_class->root_handler = sp_pencil_context_root_handler;
114 /**
115  * Callback to initialize SPPencilContext object.
116  */
117 static void
118 sp_pencil_context_init(SPPencilContext *pc)
120     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
122     event_context->cursor_shape = cursor_pencil_xpm;
123     event_context->hot_x = 4;
124     event_context->hot_y = 4;
126     pc->npoints = 0;
127     pc->state = SP_PENCIL_CONTEXT_IDLE;
128     pc->req_tangent = Geom::Point(0, 0);
130     // since SPPencilContext is not properly constructed...
131     pc->sketch_interpolation = Geom::Piecewise<Geom::D2<Geom::SBasis> >();
132     pc->sketch_n = 0;
135 /**
136  * Callback to setup SPPencilContext object.
137  */
138 static void
139 sp_pencil_context_setup(SPEventContext *ec)
141     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
142     if (prefs->getBool("/tools/freehand/pencil/selcue")) {
143         ec->enableSelectionCue();
144     }
146     if (((SPEventContextClass *) pencil_parent_class)->setup) {
147         ((SPEventContextClass *) pencil_parent_class)->setup(ec);
148     }
150     SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
151     pc->is_drawing = false;
153     pc->anchor_statusbar = false;
156 static void
157 sp_pencil_context_dispose(GObject *object)
159     G_OBJECT_CLASS(pencil_parent_class)->dispose(object);
162 /** Snaps new node relative to the previous node. */
163 static void
164 spdc_endpoint_snap(SPPencilContext const *pc, Geom::Point &p, guint const state)
166     if ((state & GDK_CONTROL_MASK)) { //CTRL enables constrained snapping
167         spdc_endpoint_snap_rotation(pc, p, pc->p[0], state);
168     } else {
169         if (!(state & GDK_SHIFT_MASK)) { //SHIFT disables all snapping, except the angular snapping above
170                                          //After all, the user explicitely asked for angular snapping by
171                                          //pressing CTRL
172             spdc_endpoint_snap_free(pc, p, state);
173         }
174     }
177 /**
178  * Callback for handling all pencil context events.
179  */
180 gint
181 sp_pencil_context_root_handler(SPEventContext *const ec, GdkEvent *event)
183     SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
185     gint ret = FALSE;
187     switch (event->type) {
188         case GDK_BUTTON_PRESS:
189             ret = pencil_handle_button_press(pc, event->button);
190             break;
192         case GDK_MOTION_NOTIFY:
193             ret = pencil_handle_motion_notify(pc, event->motion);
194             break;
196         case GDK_BUTTON_RELEASE:
197             ret = pencil_handle_button_release(pc, event->button);
198             break;
200         case GDK_KEY_PRESS:
201             ret = pencil_handle_key_press(pc, get_group0_keyval (&event->key), event->key.state);
202             break;
204         case GDK_KEY_RELEASE:
205             ret = pencil_handle_key_release(pc, get_group0_keyval (&event->key), event->key.state);
206             break;
208         default:
209             break;
210     }
212     if (!ret) {
213         gint (*const parent_root_handler)(SPEventContext *, GdkEvent *)
214             = ((SPEventContextClass *) pencil_parent_class)->root_handler;
215         if (parent_root_handler) {
216             ret = parent_root_handler(ec, event);
217         }
218     }
220     return ret;
223 static gint
224 pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent)
226     gint ret = FALSE;
227     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
228     if ( bevent.button == 1  && !event_context->space_panning) {
230         SPDrawContext *dc = SP_DRAW_CONTEXT (pc);
231         SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
232         Inkscape::Selection *selection = sp_desktop_selection(desktop);
234         if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
235             return TRUE;
236         }
238         if (!pc->grab) {
239             /* Grab mouse, so release will not pass unnoticed */
240             pc->grab = SP_CANVAS_ITEM(desktop->acetate);
241             sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK   |
242                                             GDK_BUTTON_RELEASE_MASK |
243                                             GDK_POINTER_MOTION_MASK  ),
244                                 NULL, bevent.time);
245         }
247         Geom::Point const button_w(bevent.x, bevent.y);
249         /* Find desktop coordinates */
250         Geom::Point p = pc->desktop->w2d(button_w);
252         /* Test whether we hit any anchor. */
253         SPDrawAnchor *anchor = spdc_test_inside(pc, button_w);
255         pencil_drag_origin_w = Geom::Point(bevent.x,bevent.y);
256         pencil_within_tolerance = true;
258         switch (pc->state) {
259             case SP_PENCIL_CONTEXT_ADDLINE:
260                 /* Current segment will be finished with release */
261                 ret = TRUE;
262                 break;
263             default:
264                 /* Set first point of sequence */
265                 SnapManager &m = desktop->namedview->snap_manager;
267                 if (bevent.state & GDK_CONTROL_MASK) {
268                     m.setup(desktop);
269                     if (!(bevent.state & GDK_SHIFT_MASK)) {
270                         m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE);
271                       }
272                     spdc_create_single_dot(event_context, p, "/tools/freehand/pencil", bevent.state);
273                     m.unSetup();
274                     ret = true;
275                     break;
276                 }
277                 if (anchor) {
278                     p = anchor->dp;
279                     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path"));
280                 } else {
281                     m.setup(desktop);
282                     if (!(bevent.state & GDK_SHIFT_MASK)) {
283                         // This is the first click of a new curve; deselect item so that
284                         // this curve is not combined with it (unless it is drawn from its
285                         // anchor, which is handled by the sibling branch above)
286                         selection->clear();
287                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path"));
288                         m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE);
289                     } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) {
290                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path"));
291                         m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE);
292                     }
293                     m.unSetup();
294                 }
295                 pc->sa = anchor;
296                 spdc_set_startpoint(pc, p);
297                 ret = TRUE;
298                 break;
299         }
301         pc->is_drawing = true;
302     }
303     return ret;
306 static gint
307 pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent)
309     SPDesktop *const dt = pc->desktop;
311     if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) {
312         // mouse was accidentally moved during Ctrl+click;
313         // ignore the motion and create a single point
314         pc->is_drawing = false;
315         return TRUE;
316     }
317     gint ret = FALSE;
319     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
320     if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
321         // allow scrolling
322         return FALSE;
323     }
325     if ( ( mevent.state & GDK_BUTTON1_MASK ) && !pc->grab && pc->is_drawing) {
326         /* Grab mouse, so release will not pass unnoticed */
327         pc->grab = SP_CANVAS_ITEM(dt->acetate);
328         sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK   |
329                                         GDK_BUTTON_RELEASE_MASK |
330                                         GDK_POINTER_MOTION_MASK  ),
331                             NULL, mevent.time);
332     }
334     /* Find desktop coordinates */
335     Geom::Point p = dt->w2d(Geom::Point(mevent.x, mevent.y));
337     /* Test whether we hit any anchor. */
338     SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(mevent.x, mevent.y));
340     if (pencil_within_tolerance) {
341         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
342         gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
343         if ( Geom::LInfty( Geom::Point(mevent.x,mevent.y) - pencil_drag_origin_w ) < tolerance ) {
344             return FALSE;   // Do not drag if we're within tolerance from origin.
345         }
346     }
348     // Once the user has moved farther than tolerance from the original location
349     // (indicating they intend to move the object, not click), then always process the
350     // motion notify coordinates as given (no snapping back to origin)
351     pencil_within_tolerance = false;
353     switch (pc->state) {
354         case SP_PENCIL_CONTEXT_ADDLINE:
355             /* Set red endpoint */
356             if (anchor) {
357                 p = anchor->dp;
358             } else {
359                 Geom::Point ptnr(p);
360                 spdc_endpoint_snap(pc, ptnr, mevent.state);
361                 p = ptnr;
362             }
363             spdc_set_endpoint(pc, p);
364             ret = TRUE;
365             break;
366         default:
367             /* We may be idle or already freehand */
368             if ( mevent.state & GDK_BUTTON1_MASK && pc->is_drawing ) {
369                 if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
370                     sp_event_context_discard_delayed_snap_event(event_context);
371                 }
372                 pc->state = SP_PENCIL_CONTEXT_FREEHAND;
374                 if ( !pc->sa && !pc->green_anchor ) {
375                     /* Create green anchor */
376                     pc->green_anchor = sp_draw_anchor_new(pc, pc->green_curve, TRUE, pc->p[0]);
377                 }
378                 if (anchor) {
379                     p = anchor->dp;
380                 }
382                 if ( pc->npoints != 0) { // buttonpress may have happened before we entered draw context!
383                     if (pc->ps.size() == 0) {
384                         // Only in freehand mode we have to add the first point also to pc->ps (apparently)
385                         // - We cannot add this point in spdc_set_startpoint, because we only need it for freehand
386                         // - We cannot do this in the button press handler because at that point we don't know yet
387                         //   wheter we're going into freehand mode or not
388                         pc->ps.push_back(pc->p[0]);
389                     }
390                     spdc_add_freehand_point(pc, p, mevent.state);
391                     ret = TRUE;
392                 }
394                 if (anchor && !pc->anchor_statusbar) {
395                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path."));
396                     pc->anchor_statusbar = true;
397                 } else if (!anchor && pc->anchor_statusbar) {
398                     pc->_message_context->clear();
399                     pc->anchor_statusbar = false;
400                 } else if (!anchor) {
401                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path"));
402                 }
404             } else {
405                 if (anchor && !pc->anchor_statusbar) {
406                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point."));
407                     pc->anchor_statusbar = true;
408                 } else if (!anchor && pc->anchor_statusbar) {
409                     pc->_message_context->clear();
410                     pc->anchor_statusbar = false;
411                 }
412             }
414             // Show the pre-snap indicator to communicate to the user where we would snap to if he/she were to
415             // a) press the mousebutton to start a freehand drawing, or
416             // b) release the mousebutton to finish a freehand drawing
417             if (!sp_event_context_knot_mouseover(pc)) {
418                 SnapManager &m = dt->namedview->snap_manager;
419                 m.setup(dt);
420                 m.preSnap(Inkscape::SnapCandidatePoint(p, Inkscape::SNAPSOURCE_NODE_HANDLE));
421                 m.unSetup();
422             }
423             break;
424     }
425     return ret;
428 static gint
429 pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
431     gint ret = FALSE;
433     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
434     if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
435         SPDesktop *const dt = pc->desktop;
437         pc->is_drawing = false;
439         /* Find desktop coordinates */
440         Geom::Point p = dt->w2d(Geom::Point(revent.x, revent.y));
442         /* Test whether we hit any anchor. */
443         SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(revent.x,
444                                                               revent.y));
446         switch (pc->state) {
447             case SP_PENCIL_CONTEXT_IDLE:
448                 /* Releasing button in idle mode means single click */
449                 /* We have already set up start point/anchor in button_press */
450                 if (!(revent.state & GDK_CONTROL_MASK)) {
451                     // Ctrl+click creates a single point so only set context in ADDLINE mode when Ctrl isn't pressed
452                     pc->state = SP_PENCIL_CONTEXT_ADDLINE;
453                 }
454                 ret = TRUE;
455                 break;
456             case SP_PENCIL_CONTEXT_ADDLINE:
457                 /* Finish segment now */
458                 if (anchor) {
459                     p = anchor->dp;
460                 } else {
461                     spdc_endpoint_snap(pc, p, revent.state);
462                 }
463                 pc->ea = anchor;
464                 spdc_set_endpoint(pc, p);
465                 spdc_finish_endpoint(pc);
466                 pc->state = SP_PENCIL_CONTEXT_IDLE;
467                 sp_event_context_discard_delayed_snap_event(event_context);
468                 ret = TRUE;
469                 break;
470             case SP_PENCIL_CONTEXT_FREEHAND:
471                 if (revent.state & GDK_MOD1_MASK) {
472                     /* sketch mode: interpolate the sketched path and improve the current output path with the new interpolation. don't finish sketch */
474                     sketch_interpolate(pc);
476                     if (pc->green_anchor) {
477                         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
478                     }
480                     pc->state = SP_PENCIL_CONTEXT_SKETCH;
481                 } else {
482                     /* Finish segment now */
483                     /// \todo fixme: Clean up what follows (Lauris)
484                     if (anchor) {
485                         p = anchor->dp;
486                     } else {
487                         Geom::Point p_end = p;
488                         spdc_endpoint_snap(pc, p_end, revent.state);
489                         if (p_end != p) {
490                             // then we must have snapped!
491                             spdc_add_freehand_point(pc, p_end, revent.state);
492                         }
493                     }
495                     pc->ea = anchor;
496                     /* Write curves to object */
498                     dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));
500                     interpolate(pc);
501                     spdc_concat_colors_and_flush(pc, FALSE);
502                     pc->sa = NULL;
503                     pc->ea = NULL;
504                     if (pc->green_anchor) {
505                         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
506                     }
507                     pc->state = SP_PENCIL_CONTEXT_IDLE;
508                     // reset sketch mode too
509                     pc->sketch_n = 0;
510                 }
511                 ret = TRUE;
512                 break;
513             case SP_PENCIL_CONTEXT_SKETCH:
514             default:
515                 break;
516         }
518         if (pc->grab) {
519             /* Release grab now */
520             sp_canvas_item_ungrab(pc->grab, revent.time);
521             pc->grab = NULL;
522         }
524         ret = TRUE;
525     }
526     return ret;
529 static void
530 pencil_cancel (SPPencilContext *const pc)
532     if (pc->grab) {
533         /* Release grab now */
534         sp_canvas_item_ungrab(pc->grab, 0);
535         pc->grab = NULL;
536     }
538     pc->is_drawing = false;
539     pc->state = SP_PENCIL_CONTEXT_IDLE;
540     sp_event_context_discard_delayed_snap_event(SP_EVENT_CONTEXT(pc));
542     pc->red_curve->reset();
543     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
544     while (pc->green_bpaths) {
545         gtk_object_destroy(GTK_OBJECT(pc->green_bpaths->data));
546         pc->green_bpaths = g_slist_remove(pc->green_bpaths, pc->green_bpaths->data);
547     }
548     pc->green_curve->reset();
549     if (pc->green_anchor) {
550         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
551     }
553     pc->_message_context->clear();
554     pc->_message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled"));
556     sp_canvas_end_forced_full_redraws(pc->desktop->canvas);
559 static gint
560 pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state)
562     gint ret = FALSE;
563     switch (keyval) {
564         case GDK_Up:
565         case GDK_Down:
566         case GDK_KP_Up:
567         case GDK_KP_Down:
568             // Prevent the zoom field from activation.
569             if (!mod_ctrl_only(state)) {
570                 ret = TRUE;
571             }
572             break;
573         case GDK_Escape:
574             if (pc->npoints != 0) {
575                 // if drawing, cancel, otherwise pass it up for deselecting
576                 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
577                     pencil_cancel (pc);
578                     ret = TRUE;
579                 }
580             }
581             break;
582         case GDK_z:
583         case GDK_Z:
584             if (mod_ctrl_only(state) && pc->npoints != 0) {
585                 // if drawing, cancel, otherwise pass it up for undo
586                 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
587                     pencil_cancel (pc);
588                     ret = TRUE;
589                 }
590             }
591             break;
592         case GDK_g:
593         case GDK_G:
594             if (mod_shift_only(state)) {
595                 sp_selection_to_guides(SP_EVENT_CONTEXT(pc)->desktop);
596                 ret = true;
597             }
598             break;
599         case GDK_Alt_L:
600         case GDK_Alt_R:
601         case GDK_Meta_L:
602         case GDK_Meta_R:
603             if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
604                 pc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("<b>Sketch mode</b>: holding <b>Alt</b> interpolates between sketched paths. Release <b>Alt</b> to finalize."));
605             }
606             break;
607         default:
608             break;
609     }
610     return ret;
613 static gint
614 pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const /*state*/)
616     gint ret = FALSE;
617     switch (keyval) {
618         case GDK_Alt_L:
619         case GDK_Alt_R:
620         case GDK_Meta_L:
621         case GDK_Meta_R:
622             if (pc->state == SP_PENCIL_CONTEXT_SKETCH) {
623                 spdc_concat_colors_and_flush(pc, FALSE);
624                 pc->sketch_n = 0;
625                 pc->sa = NULL;
626                 pc->ea = NULL;
627                 if (pc->green_anchor) {
628                     pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
629                 }
630                 pc->state = SP_PENCIL_CONTEXT_IDLE;
631                 sp_event_context_discard_delayed_snap_event(SP_EVENT_CONTEXT(pc));
632                 pc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand sketch"));
633                 ret = TRUE;
634             }
635             break;
636         default:
637             break;
638     }
639     return ret;
642 /**
643  * Reset points and set new starting point.
644  */
645 static void
646 spdc_set_startpoint(SPPencilContext *const pc, Geom::Point const p)
648     pc->npoints = 0;
649     pc->red_curve_is_valid = false;
650     if (in_svg_plane(p)) {
651         pc->p[pc->npoints++] = p;
652     }
655 /**
656  * Change moving endpoint position.
657  * <ul>
658  * <li>Ctrl constrains to moving to H/V direction, snapping in given direction.
659  * <li>Otherwise we snap freely to whatever attractors are available.
660  * </ul>
661  *
662  * Number of points is (re)set to 2 always, 2nd point is modified.
663  * We change RED curve.
664  */
665 static void
666 spdc_set_endpoint(SPPencilContext *const pc, Geom::Point const p)
668     if (pc->npoints == 0) {
669         return;
670         /* May occur if first point wasn't in SVG plane (e.g. weird w2d transform, perhaps from bad
671          * zoom setting).
672          */
673     }
674     g_return_if_fail( pc->npoints > 0 );
676     pc->red_curve->reset();
677     if ( ( p == pc->p[0] )
678          || !in_svg_plane(p) )
679     {
680         pc->npoints = 1;
681     } else {
682         pc->p[1] = p;
683         pc->npoints = 2;
685         pc->red_curve->moveto(pc->p[0]);
686         pc->red_curve->lineto(pc->p[1]);
687         pc->red_curve_is_valid = true;
689         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
690     }
693 /**
694  * Finalize addline.
695  *
696  * \todo
697  * fixme: I'd like remove red reset from concat colors (lauris).
698  * Still not sure, how it will make most sense.
699  */
700 static void
701 spdc_finish_endpoint(SPPencilContext *const pc)
703     if ( ( pc->red_curve->is_empty() )
704          || ( *(pc->red_curve->first_point()) == *(pc->red_curve->second_point())   ) )
705     {
706         pc->red_curve->reset();
707         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
708     } else {
709         /* Write curves to object. */
710         spdc_concat_colors_and_flush(pc, FALSE);
711         pc->sa = NULL;
712         pc->ea = NULL;
713     }
717 static void
718 spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint /*state*/)
720     g_assert( pc->npoints > 0 );
721     g_return_if_fail(unsigned(pc->npoints) < G_N_ELEMENTS(pc->p));
723     if ( ( p != pc->p[ pc->npoints - 1 ] )
724          && in_svg_plane(p) )
725     {
726         pc->ps.push_back(p);
727         pc->p[pc->npoints++] = p;
728         fit_and_split(pc);
729     }
732 static inline double
733 square(double const x)
735     return x * x;
738 static void
739 interpolate(SPPencilContext *pc)
741     if ( pc->ps.size() <= 1 ) {
742         return;
743     }
745     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
746     double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
747     double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
748                                                tol) * exp(0.2*tol - 2);
750     g_assert(is_zero(pc->req_tangent)
751              || is_unit_vector(pc->req_tangent));
752     Geom::Point const tHatEnd(0, 0);
754     guint n_points  = pc->ps.size();
755     pc->green_curve->reset();
756     pc->red_curve->reset();
757     pc->red_curve_is_valid = false;
759     Geom::Point * b = g_new(Geom::Point, 4*n_points);
760     Geom::Point * points = g_new(Geom::Point, 4*n_points);
761     for (unsigned int i = 0; i < pc->ps.size(); i++) {
762         points[i] = pc->ps[i];
763     }
765     // worst case gives us a segment per point
766     int max_segs = 4*n_points;
768     int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
769                                              tolerance_sq, max_segs);
771     if ( n_segs > 0)
772     {
773         /* Fit and draw and reset state */
774         pc->green_curve->moveto(b[0]);
775         for (int c = 0; c < n_segs; c++) {
776             pc->green_curve->curveto(b[4*c+1], b[4*c+2], b[4*c+3]);
777         }
778         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
780         /* Fit and draw and copy last point */
781         g_assert(!pc->green_curve->is_empty());
783         /* Set up direction of next curve. */
784         {
785             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
786             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
787             pc->p[0] = last_seg->finalPoint();
788             pc->npoints = 1;
789             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
790             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
791                                 ? Geom::Point(0, 0)
792                                 : Geom::unit_vector(req_vec) );
793         }
794     }
795     g_free(b);
796     g_free(points);
797     pc->ps.clear();
801 /* interpolates the sketched curve and tweaks the current sketch interpolation*/
802 static void
803 sketch_interpolate(SPPencilContext *pc)
805     if ( pc->ps.size() <= 1 ) {
806         return;
807     }
809     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
810     double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
811     double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
812                                                tol) * exp(0.2*tol - 2);
814     bool average_all_sketches = prefs->getBool("/tools/freehand/pencil/average_all_sketches", true);
816     g_assert(is_zero(pc->req_tangent)
817              || is_unit_vector(pc->req_tangent));
818     Geom::Point const tHatEnd(0, 0);
820     guint n_points  = pc->ps.size();
821     pc->red_curve->reset();
822     pc->red_curve_is_valid = false;
824     Geom::Point * b = g_new(Geom::Point, 4*n_points);
825     Geom::Point * points = g_new(Geom::Point, 4*n_points);
826     for (unsigned i = 0; i < pc->ps.size(); i++) {
827         points[i] = pc->ps[i];
828     }
830     // worst case gives us a segment per point
831     int max_segs = 4*n_points;
833     int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
834                                              tolerance_sq, max_segs);
836     if ( n_segs > 0)
837     {
838         Geom::Path fit(b[0]);
839         for (int c = 0; c < n_segs; c++) {
840             fit.appendNew<Geom::CubicBezier>(b[4*c+1], b[4*c+2], b[4*c+3]);
841         }
842         Geom::Piecewise<Geom::D2<Geom::SBasis> > fit_pwd2 = fit.toPwSb();
844         double t =0.;
845         if ( pc->sketch_n > 0 ) {
846             if (average_all_sketches) {
847                 // Average = (sum of all) / n
848                 //         = (sum of all + new one) / n+1
849                 //         = ((old average)*n + new one) / n+1
850                 t = pc->sketch_n / (pc->sketch_n + 1.);
851             } else {
852                 t = 0.5;
853             }
854             pc->sketch_interpolation = Geom::lerp(t, fit_pwd2, pc->sketch_interpolation);
855             // simplify path, to eliminate small segments
856             Path *path = new Path;
857             path->LoadPathVector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
858             path->Simplify(0.5);
859             Geom::PathVector *pathv = path->MakePathVector();
860             pc->sketch_interpolation = (*pathv)[0].toPwSb();
861             delete path;
862             delete pathv;
863         } else {
864             pc->sketch_interpolation = fit_pwd2;
865         }
866         pc->sketch_n++;
868         pc->green_curve->reset();
869         pc->green_curve->set_pathvector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
870         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
872         /* Fit and draw and copy last point */
873         g_assert(!pc->green_curve->is_empty());
875         /* Set up direction of next curve. */
876         {
877             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
878             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
879             pc->p[0] = last_seg->finalPoint();
880             pc->npoints = 1;
881             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
882             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
883                                 ? Geom::Point(0, 0)
884                                 : Geom::unit_vector(req_vec) );
885         }
886     }
887     g_free(b);
888     g_free(points);
889     pc->ps.clear();
892 static void
893 fit_and_split(SPPencilContext *pc)
895     g_assert( pc->npoints > 1 );
897     double const tolerance_sq = 0;
899     Geom::Point b[4];
900     g_assert(is_zero(pc->req_tangent)
901              || is_unit_vector(pc->req_tangent));
902     Geom::Point const tHatEnd(0, 0);
903     int const n_segs = Geom::bezier_fit_cubic_full(b, NULL, pc->p, pc->npoints,
904                                                 pc->req_tangent, tHatEnd,
905                                                 tolerance_sq, 1);
906     if ( n_segs > 0
907          && unsigned(pc->npoints) < G_N_ELEMENTS(pc->p) )
908     {
909         /* Fit and draw and reset state */
910         pc->red_curve->reset();
911         pc->red_curve->moveto(b[0]);
912         pc->red_curve->curveto(b[1], b[2], b[3]);
913         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
914         pc->red_curve_is_valid = true;
915     } else {
916         /* Fit and draw and copy last point */
918         g_assert(!pc->red_curve->is_empty());
920         /* Set up direction of next curve. */
921         {
922             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->red_curve->last_segment());
923             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
924             pc->p[0] = last_seg->finalPoint();
925             pc->npoints = 1;
926             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
927             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
928                                 ? Geom::Point(0, 0)
929                                 : Geom::unit_vector(req_vec) );
930         }
932         pc->green_curve->append_continuous(pc->red_curve, 0.0625);
933         SPCurve *curve = pc->red_curve->copy();
935         /// \todo fixme:
936         SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(pc->desktop), curve);
937         curve->unref();
938         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), pc->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
940         pc->green_bpaths = g_slist_prepend(pc->green_bpaths, cshape);
942         pc->red_curve_is_valid = false;
943     }
947 /*
948   Local Variables:
949   mode:c++
950   c-file-style:"stroustrup"
951   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
952   indent-tabs-mode:nil
953   fill-column:99
954   End:
955 */
956 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :