Code

fix crash bug 310206
[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"
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);
56 static gint pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const state);
58 static void spdc_set_startpoint(SPPencilContext *pc, Geom::Point const p);
59 static void spdc_set_endpoint(SPPencilContext *pc, Geom::Point const p);
60 static void spdc_finish_endpoint(SPPencilContext *pc);
61 static void spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint state);
62 static void fit_and_split(SPPencilContext *pc);
63 static void interpolate(SPPencilContext *pc);
64 static void sketch_interpolate(SPPencilContext *pc);
66 static SPDrawContextClass *pencil_parent_class;
67 static Geom::Point pencil_drag_origin_w(0, 0);
68 static bool pencil_within_tolerance = false;
70 /**
71  * Register SPPencilContext class with Gdk and return its type number.
72  */
73 GType
74 sp_pencil_context_get_type()
75 {
76     static GType type = 0;
77     if (!type) {
78         GTypeInfo info = {
79             sizeof(SPPencilContextClass),
80             NULL, NULL,
81             (GClassInitFunc) sp_pencil_context_class_init,
82             NULL, NULL,
83             sizeof(SPPencilContext),
84             4,
85             (GInstanceInitFunc) sp_pencil_context_init,
86             NULL,   /* value_table */
87         };
88         type = g_type_register_static(SP_TYPE_DRAW_CONTEXT, "SPPencilContext", &info, (GTypeFlags)0);
89     }
90     return type;
91 }
93 /**
94  * Initialize SPPencilContext vtable.
95  */
96 static void
97 sp_pencil_context_class_init(SPPencilContextClass *klass)
98 {
99     GObjectClass *object_class;
100     SPEventContextClass *event_context_class;
102     object_class = (GObjectClass *) klass;
103     event_context_class = (SPEventContextClass *) klass;
105     pencil_parent_class = (SPDrawContextClass*)g_type_class_peek_parent(klass);
107     object_class->dispose = sp_pencil_context_dispose;
109     event_context_class->setup = sp_pencil_context_setup;
110     event_context_class->root_handler = sp_pencil_context_root_handler;
113 /**
114  * Callback to initialize SPPencilContext object.
115  */
116 static void
117 sp_pencil_context_init(SPPencilContext *pc)
119     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
121     event_context->cursor_shape = cursor_pencil_xpm;
122     event_context->hot_x = 4;
123     event_context->hot_y = 4;
125     pc->npoints = 0;
126     pc->state = SP_PENCIL_CONTEXT_IDLE;
127     pc->req_tangent = Geom::Point(0, 0);
129     // since SPPencilContext is not properly constructed...
130     pc->sketch_interpolation = Geom::Piecewise<Geom::D2<Geom::SBasis> >();
131     pc->sketch_n = 0;
134 /**
135  * Callback to setup SPPencilContext object.
136  */
137 static void
138 sp_pencil_context_setup(SPEventContext *ec)
140     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
141     if (prefs->getBool("/tools/freehand/pencil/selcue")) {
142         ec->enableSelectionCue();
143     }
145     if (((SPEventContextClass *) pencil_parent_class)->setup) {
146         ((SPEventContextClass *) pencil_parent_class)->setup(ec);
147     }
149     SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
150     pc->is_drawing = false;
152     pc->anchor_statusbar = false;
155 static void
156 sp_pencil_context_dispose(GObject *object)
158     G_OBJECT_CLASS(pencil_parent_class)->dispose(object);
161 /** Snaps new node relative to the previous node. */
162 static void
163 spdc_endpoint_snap(SPPencilContext const *pc, Geom::Point &p, guint const state)
165     if ((state & GDK_CONTROL_MASK)) { //CTRL enables constrained snapping
166         spdc_endpoint_snap_rotation(pc, p, pc->p[0], state);
167     } else {
168         if (!(state & GDK_SHIFT_MASK)) { //SHIFT disables all snapping, except the angular snapping above
169                                          //After all, the user explicitely asked for angular snapping by
170                                          //pressing CTRL
171             spdc_endpoint_snap_free(pc, p, state);
172         }
173     }
176 /**
177  * Callback for handling all pencil context events.
178  */
179 gint
180 sp_pencil_context_root_handler(SPEventContext *const ec, GdkEvent *event)
182     SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
184     gint ret = FALSE;
186     switch (event->type) {
187         case GDK_BUTTON_PRESS:
188             ret = pencil_handle_button_press(pc, event->button);
189             break;
191         case GDK_MOTION_NOTIFY:
192             ret = pencil_handle_motion_notify(pc, event->motion);
193             break;
195         case GDK_BUTTON_RELEASE:
196             ret = pencil_handle_button_release(pc, event->button);
197             break;
199         case GDK_KEY_PRESS:
200             ret = pencil_handle_key_press(pc, get_group0_keyval (&event->key), event->key.state);
201             break;
203         case GDK_KEY_RELEASE:
204             ret = pencil_handle_key_release(pc, get_group0_keyval (&event->key), event->key.state);
205             break;
207         default:
208             break;
209     }
211     if (!ret) {
212         gint (*const parent_root_handler)(SPEventContext *, GdkEvent *)
213             = ((SPEventContextClass *) pencil_parent_class)->root_handler;
214         if (parent_root_handler) {
215             ret = parent_root_handler(ec, event);
216         }
217     }
219     return ret;
222 static gint
223 pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent)
225     gint ret = FALSE;
226     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
227     if ( bevent.button == 1  && !event_context->space_panning) {
229         SPDrawContext *dc = SP_DRAW_CONTEXT (pc);
230         SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
231         Inkscape::Selection *selection = sp_desktop_selection(desktop);
233         if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
234             return TRUE;
235         }
237         Geom::Point const button_w(bevent.x, bevent.y);
239         /* Find desktop coordinates */
240         Geom::Point p = pc->desktop->w2d(button_w);
242         /* Test whether we hit any anchor. */
243         SPDrawAnchor *anchor = spdc_test_inside(pc, button_w);
245         pencil_drag_origin_w = Geom::Point(bevent.x,bevent.y);
246         pencil_within_tolerance = true;
248         switch (pc->state) {
249             case SP_PENCIL_CONTEXT_ADDLINE:
250                 /* Current segment will be finished with release */
251                 ret = TRUE;
252                 break;
253             default:
254                 /* Set first point of sequence */
255                 if (bevent.state & GDK_CONTROL_MASK) {
256                     spdc_create_single_dot(event_context, p, "/tools/freehand/pencil", bevent.state);
257                     ret = true;
258                     break;
259                 }
260                 if (anchor) {
261                     p = anchor->dp;
262                     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path"));
263                 } else {
265                     if (!(bevent.state & GDK_SHIFT_MASK)) {
267                         // This is the first click of a new curve; deselect item so that
268                         // this curve is not combined with it (unless it is drawn from its
269                         // anchor, which is handled by the sibling branch above)
270                         selection->clear();
271                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path"));
272                         SnapManager &m = desktop->namedview->snap_manager;
273                         m.setup(desktop);
274                         Inkscape::SnappedPoint const s = m.freeSnap(Inkscape::SnapPreferences::SNAPPOINT_NODE, p);
275                         if (s.getSnapped()) {
276                                 s.getPoint(p);
277                                 pc->prev_snap_was_succesful = true;
278                         } else {
279                                 pc->prev_snap_was_succesful = false;
280                         }
281                     } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) {
282                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path"));
283                     }
284                 }
285                 pc->sa = anchor;
286                 spdc_set_startpoint(pc, p);
287                 ret = TRUE;
288                 break;
289         }
291         pc->is_drawing = true;
292     }
293     return ret;
296 static gint
297 pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent)
299     if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) {
300         // mouse was accidentally moved during Ctrl+click;
301         // ignore the motion and create a single point
302         pc->is_drawing = false;
303         return TRUE;
304     }
305     gint ret = FALSE;
306     SPDesktop *const dt = pc->desktop;
308     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
309     if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
310         // allow scrolling
311         return FALSE;
312     }
314     if ( ( mevent.state & GDK_BUTTON1_MASK ) && !pc->grab && pc->is_drawing) {
315         /* Grab mouse, so release will not pass unnoticed */
316         pc->grab = SP_CANVAS_ITEM(dt->acetate);
317         sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK   |
318                                         GDK_BUTTON_RELEASE_MASK |
319                                         GDK_POINTER_MOTION_MASK  ),
320                             NULL, mevent.time);
321     }
323     /* Find desktop coordinates */
324     Geom::Point p = dt->w2d(Geom::Point(mevent.x, mevent.y));
326     /* Test whether we hit any anchor. */
327     SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(mevent.x, mevent.y));
329     if (pencil_within_tolerance) {
330         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
331         gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
332         if ( Geom::LInfty( Geom::Point(mevent.x,mevent.y) - pencil_drag_origin_w ) < tolerance ) {
333             return FALSE;   // Do not drag if we're within tolerance from origin.
334         }
335     }
337     // Once the user has moved farther than tolerance from the original location
338     // (indicating they intend to move the object, not click), then always process the
339     // motion notify coordinates as given (no snapping back to origin)
340     pencil_within_tolerance = false;
342     switch (pc->state) {
343         case SP_PENCIL_CONTEXT_ADDLINE:
344             /* Set red endpoint */
345             if (anchor) {
346                 p = anchor->dp;
347             } else {
348                 Geom::Point ptnr(p);
349                 spdc_endpoint_snap(pc, ptnr, mevent.state);
350                 p = ptnr;
351             }
352             spdc_set_endpoint(pc, p);
353             ret = TRUE;
354             break;
355         default:
356             /* We may be idle or already freehand */
357             if ( mevent.state & GDK_BUTTON1_MASK && pc->is_drawing ) {
358                 pc->state = SP_PENCIL_CONTEXT_FREEHAND;
359                 if ( !pc->sa && !pc->green_anchor ) {
360                     /* Create green anchor */
361                     pc->green_anchor = sp_draw_anchor_new(pc, pc->green_curve, TRUE, pc->p[0]);
362                 }
363                 /** \todo
364                  * fixme: I am not sure whether we want to snap to anchors
365                  * in middle of freehand (Lauris)
366                  */
367                 SnapManager &m = dt->namedview->snap_manager;
368                 
369                 if (anchor) {
370                     p = anchor->dp;
371                 } else if ((mevent.state & GDK_SHIFT_MASK) == 0) {
372                     m.setup(dt);
373                     Inkscape::SnappedPoint const s = m.freeSnap(Inkscape::SnapPreferences::SNAPPOINT_NODE, p);
374                     if (s.getSnapped()) {
375                         s.getPoint(p);
376                         pc->prev_snap_was_succesful = true;
377                     } else {
378                         pc->prev_snap_was_succesful = false;
379                     }
380                 }
381                 if ( pc->npoints != 0) { // buttonpress may have happened before we entered draw context!
382                         if (!(pc->prev_snap_was_succesful && m.snapprefs.getSnapPostponedGlobally())) {
383                             // When snapping is enabled but temporarily on hold because the mouse is moving 
384                         // fast, then we don't want to add nodes off-grid
385                         spdc_add_freehand_point(pc, p, mevent.state);
386                             ret = TRUE;
387                         }
388                 }
390                 if (anchor && !pc->anchor_statusbar) {
391                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path."));
392                     pc->anchor_statusbar = true;
393                 } else if (!anchor && pc->anchor_statusbar) {
394                     pc->_message_context->clear();
395                     pc->anchor_statusbar = false;
396                 } else if (!anchor) {
397                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path"));
398                 }
400             } else {
401                 if (anchor && !pc->anchor_statusbar) {
402                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point."));
403                     pc->anchor_statusbar = true;
404                 } else if (!anchor && pc->anchor_statusbar) {
405                     pc->_message_context->clear();
406                     pc->anchor_statusbar = false;
407                 }
408             }
409             break;
410     }
411     return ret;
414 static gint
415 pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
417     gint ret = FALSE;
419     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
420     if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
421         SPDesktop *const dt = pc->desktop;
423         pc->is_drawing = false;
425         /* Find desktop coordinates */
426         Geom::Point p = dt->w2d(Geom::Point(revent.x, revent.y));
428         /* Test whether we hit any anchor. */
429         SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(revent.x,
430                                                               revent.y));
432         switch (pc->state) {
433             case SP_PENCIL_CONTEXT_IDLE:
434                 /* Releasing button in idle mode means single click */
435                 /* We have already set up start point/anchor in button_press */
436                 if (!(revent.state & GDK_CONTROL_MASK)) {
437                     // Ctrl+click creates a single point so only set context in ADDLINE mode when Ctrl isn't pressed
438                     pc->state = SP_PENCIL_CONTEXT_ADDLINE;
439                 }
440                 ret = TRUE;
441                 break;
442             case SP_PENCIL_CONTEXT_ADDLINE:
443                 /* Finish segment now */
444                 if (anchor) {
445                     p = anchor->dp;
446                 } else {
447                     spdc_endpoint_snap(pc, p, revent.state);
448                 }
449                 pc->ea = anchor;
450                 spdc_set_endpoint(pc, p);
451                 spdc_finish_endpoint(pc);
452                 pc->state = SP_PENCIL_CONTEXT_IDLE;
453                 ret = TRUE;
454                 break;
455             case SP_PENCIL_CONTEXT_FREEHAND:
456                 if (revent.state & GDK_MOD1_MASK) {
457                     /* sketch mode: interpolate the sketched path and improve the current output path with the new interpolation. don't finish sketch */
459                     sketch_interpolate(pc);
461                     if (pc->green_anchor) {
462                         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
463                     }
465                     pc->state = SP_PENCIL_CONTEXT_SKETCH;
466                 } else {
467                     /* Finish segment now */
468                     /// \todo fixme: Clean up what follows (Lauris)
469                     if (anchor) {
470                         p = anchor->dp;
471                     }
472                     pc->ea = anchor;
473                     /* Write curves to object */
475                     dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));
477                     interpolate(pc);
478                     spdc_concat_colors_and_flush(pc, FALSE);
479                     pc->sa = NULL;
480                     pc->ea = NULL;
481                     if (pc->green_anchor) {
482                         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
483                     }
484                     pc->state = SP_PENCIL_CONTEXT_IDLE;
485                     // reset sketch mode too
486                     pc->sketch_n = 0;
487                 }
488                 ret = TRUE;
489                 break;
490             case SP_PENCIL_CONTEXT_SKETCH:
491             default:
492                 break;
493         }
495         if (pc->grab) {
496             /* Release grab now */
497             sp_canvas_item_ungrab(pc->grab, revent.time);
498             pc->grab = NULL;
499         }
501         ret = TRUE;
502     }
503     return ret;
506 static void
507 pencil_cancel (SPPencilContext *const pc) 
509     if (pc->grab) {
510         /* Release grab now */
511         sp_canvas_item_ungrab(pc->grab, 0);
512         pc->grab = NULL;
513     }
515     pc->is_drawing = false;
517     pc->state = SP_PENCIL_CONTEXT_IDLE;
519     pc->red_curve->reset();
520     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
521     while (pc->green_bpaths) {
522         gtk_object_destroy(GTK_OBJECT(pc->green_bpaths->data));
523         pc->green_bpaths = g_slist_remove(pc->green_bpaths, pc->green_bpaths->data);
524     }
525     pc->green_curve->reset();
526     if (pc->green_anchor) {
527         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
528     }
530     pc->_message_context->clear();
531     pc->_message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled"));
533     sp_canvas_end_forced_full_redraws(pc->desktop->canvas);
536 static gint
537 pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state)
539     gint ret = FALSE;
540     switch (keyval) {
541         case GDK_Up:
542         case GDK_Down:
543         case GDK_KP_Up:
544         case GDK_KP_Down:
545             // Prevent the zoom field from activation.
546             if (!mod_ctrl_only(state)) {
547                 ret = TRUE;
548             }
549             break;
550         case GDK_Escape:
551             if (pc->npoints != 0) {
552                 // if drawing, cancel, otherwise pass it up for deselecting
553                 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
554                     pencil_cancel (pc);
555                     ret = TRUE;
556                 }
557             }
558             break;
559         case GDK_z:
560         case GDK_Z:
561             if (mod_ctrl_only(state) && pc->npoints != 0) {
562                 // if drawing, cancel, otherwise pass it up for undo
563                 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
564                     pencil_cancel (pc);
565                     ret = TRUE;
566                 }
567             }
568             break;
569         case GDK_g:
570         case GDK_G:
571             if (mod_shift_only(state)) {
572                 sp_selection_to_guides(SP_EVENT_CONTEXT(pc)->desktop);
573                 ret = true;
574             }
575             break;
576         case GDK_Alt_L:
577         case GDK_Alt_R:
578         case GDK_Meta_L:
579         case GDK_Meta_R:
580             if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
581                 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."));
582             }
583             break;
584         default:
585             break;
586     }
587     return ret;
590 static gint
591 pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const /*state*/)
593     gint ret = FALSE;
594     switch (keyval) {
595         case GDK_Alt_L:
596         case GDK_Alt_R:
597         case GDK_Meta_L:
598         case GDK_Meta_R:
599             if (pc->state == SP_PENCIL_CONTEXT_SKETCH) {
600                 spdc_concat_colors_and_flush(pc, FALSE);
601                 pc->sketch_n = 0;
602                 pc->sa = NULL;
603                 pc->ea = NULL;
604                 if (pc->green_anchor) {
605                     pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
606                 }
607                 pc->state = SP_PENCIL_CONTEXT_IDLE;
608                 pc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand sketch"));
609                 ret = TRUE;
610             }
611             break;
612         default:
613             break;
614     }
615     return ret;
618 /**
619  * Reset points and set new starting point.
620  */
621 static void
622 spdc_set_startpoint(SPPencilContext *const pc, Geom::Point const p)
624     pc->npoints = 0;
625     pc->red_curve_is_valid = false;
626     if (in_svg_plane(p)) {
627         pc->p[pc->npoints++] = p;
628     }
631 /**
632  * Change moving endpoint position.
633  * <ul>
634  * <li>Ctrl constrains to moving to H/V direction, snapping in given direction.
635  * <li>Otherwise we snap freely to whatever attractors are available.
636  * </ul>
637  *
638  * Number of points is (re)set to 2 always, 2nd point is modified.
639  * We change RED curve.
640  */
641 static void
642 spdc_set_endpoint(SPPencilContext *const pc, Geom::Point const p)
644     if (pc->npoints == 0) {
645         return;
646         /* May occur if first point wasn't in SVG plane (e.g. weird w2d transform, perhaps from bad
647          * zoom setting).
648          */
649     }
650     g_return_if_fail( pc->npoints > 0 );
652     pc->red_curve->reset();
653     if ( ( p == pc->p[0] )
654          || !in_svg_plane(p) )
655     {
656         pc->npoints = 1;
657     } else {
658         pc->p[1] = p;
659         pc->npoints = 2;
661         pc->red_curve->moveto(pc->p[0]);
662         pc->red_curve->lineto(pc->p[1]);
663         pc->red_curve_is_valid = true;
665         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
666     }
669 /**
670  * Finalize addline.
671  *
672  * \todo
673  * fixme: I'd like remove red reset from concat colors (lauris).
674  * Still not sure, how it will make most sense.
675  */
676 static void
677 spdc_finish_endpoint(SPPencilContext *const pc)
679     if ( ( pc->red_curve->is_empty() )
680          || ( *(pc->red_curve->first_point()) == *(pc->red_curve->second_point())   ) )
681     {
682         pc->red_curve->reset();
683         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
684     } else {
685         /* Write curves to object. */
686         spdc_concat_colors_and_flush(pc, FALSE);
687         pc->sa = NULL;
688         pc->ea = NULL;
689     }
693 static void
694 spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint /*state*/)
696     g_assert( pc->npoints > 0 );
697     g_return_if_fail(unsigned(pc->npoints) < G_N_ELEMENTS(pc->p));
699     if ( ( p != pc->p[ pc->npoints - 1 ] )
700          && in_svg_plane(p) )
701     {
702         pc->ps.push_back(p);
703         pc->p[pc->npoints++] = p;
704         fit_and_split(pc);
705     }
708 static inline double
709 square(double const x)
711     return x * x;
714 static void
715 interpolate(SPPencilContext *pc)
718     g_assert( pc->ps.size() > 1 );
720     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
721     double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
722     double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() * 
723                                                tol) * exp(0.2*tol - 2);
725     g_assert(is_zero(pc->req_tangent)
726              || is_unit_vector(pc->req_tangent));
727     Geom::Point const tHatEnd(0, 0);
729     guint n_points  = pc->ps.size();
730     pc->green_curve->reset();
731     pc->red_curve->reset();
732     pc->red_curve_is_valid = false;
734     Geom::Point * b = g_new(Geom::Point, 4*n_points);
735     Geom::Point * points = g_new(Geom::Point, 4*n_points);
736     for (unsigned int i = 0; i < pc->ps.size(); i++) { 
737         points[i] = pc->ps[i];
738     }
740     // worst case gives us a segment per point
741     int max_segs = 4*n_points;
743     int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
744                                              tolerance_sq, max_segs);
746     if ( n_segs > 0)
747     {
748         /* Fit and draw and reset state */
749         pc->green_curve->moveto(b[0]);
750         for (int c = 0; c < n_segs; c++) { 
751             pc->green_curve->curveto(b[4*c+1], b[4*c+2], b[4*c+3]);
752         }
753         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
755         /* Fit and draw and copy last point */
756         g_assert(!pc->green_curve->is_empty());
758         /* Set up direction of next curve. */
759         {
760             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
761             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
762             pc->p[0] = last_seg->finalPoint();
763             pc->npoints = 1;
764             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
765             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
766                                 ? Geom::Point(0, 0)
767                                 : Geom::unit_vector(req_vec) );
768         }
769     }
770     g_free(b);
771     g_free(points);
772     pc->ps.clear();
776 /* interpolates the sketched curve and tweaks the current sketch interpolation*/
777 static void
778 sketch_interpolate(SPPencilContext *pc)
780     g_assert( pc->ps.size() > 1 );
782     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
783     double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
784     double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() * 
785                                                tol) * exp(0.2*tol - 2);
787     bool average_all_sketches = prefs->getBool("/tools/freehand/pencil/average_all_sketches", true);
789     g_assert(is_zero(pc->req_tangent)
790              || is_unit_vector(pc->req_tangent));
791     Geom::Point const tHatEnd(0, 0);
793     guint n_points  = pc->ps.size();
794     pc->red_curve->reset();
795     pc->red_curve_is_valid = false;
797     Geom::Point * b = g_new(Geom::Point, 4*n_points);
798     Geom::Point * points = g_new(Geom::Point, 4*n_points);
799     for (unsigned i = 0; i < pc->ps.size(); i++) { 
800         points[i] = pc->ps[i];
801     }
803     // worst case gives us a segment per point
804     int max_segs = 4*n_points;
806     int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
807                                              tolerance_sq, max_segs);
809     if ( n_segs > 0)
810     {
811         Geom::Path fit(b[0]);
812         for (int c = 0; c < n_segs; c++) { 
813             fit.appendNew<Geom::CubicBezier>(b[4*c+1], b[4*c+2], b[4*c+3]);
814         }
815         Geom::Piecewise<Geom::D2<Geom::SBasis> > fit_pwd2 = fit.toPwSb();
817         double t =0.;
818         if ( pc->sketch_n > 0 ) {
819             if (average_all_sketches) {
820                 // Average = (sum of all) / n
821                 //         = (sum of all + new one) / n+1
822                 //         = ((old average)*n + new one) / n+1
823                 t = pc->sketch_n / (pc->sketch_n + 1.);
824             } else {
825                 t = 0.5;
826             }
827             pc->sketch_interpolation = Geom::lerp(fit_pwd2, pc->sketch_interpolation, t);
828         } else {
829             pc->sketch_interpolation = fit_pwd2;
830         }
831         pc->sketch_n++;
833         pc->green_curve->reset();
834         pc->green_curve->set_pathvector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
835         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
837         /* Fit and draw and copy last point */
838         g_assert(!pc->green_curve->is_empty());
840         /* Set up direction of next curve. */
841         {
842             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
843             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
844             pc->p[0] = last_seg->finalPoint();
845             pc->npoints = 1;
846             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
847             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
848                                 ? Geom::Point(0, 0)
849                                 : Geom::unit_vector(req_vec) );
850         }
851     }
852     g_free(b);
853     g_free(points);
854     pc->ps.clear();
857 static void
858 fit_and_split(SPPencilContext *pc)
860     g_assert( pc->npoints > 1 );
862     double const tolerance_sq = 0;
864     Geom::Point b[4];
865     g_assert(is_zero(pc->req_tangent)
866              || is_unit_vector(pc->req_tangent));
867     Geom::Point const tHatEnd(0, 0);
868     int const n_segs = Geom::bezier_fit_cubic_full(b, NULL, pc->p, pc->npoints,
869                                                 pc->req_tangent, tHatEnd, 
870                                                 tolerance_sq, 1);
871     if ( n_segs > 0
872          && unsigned(pc->npoints) < G_N_ELEMENTS(pc->p) )
873     {
874         /* Fit and draw and reset state */
875         pc->red_curve->reset();
876         pc->red_curve->moveto(b[0]);
877         pc->red_curve->curveto(b[1], b[2], b[3]);
878         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
879         pc->red_curve_is_valid = true;
880     } else {
881         /* Fit and draw and copy last point */
883         g_assert(!pc->red_curve->is_empty());
885         /* Set up direction of next curve. */
886         {
887             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->red_curve->last_segment());
888             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
889             pc->p[0] = last_seg->finalPoint();
890             pc->npoints = 1;
891             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
892             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
893                                 ? Geom::Point(0, 0)
894                                 : Geom::unit_vector(req_vec) );
895         }
897         pc->green_curve->append_continuous(pc->red_curve, 0.0625);
898         SPCurve *curve = pc->red_curve->copy();
900         /// \todo fixme:
901         SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(pc->desktop), curve);
902         curve->unref();
903         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), pc->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
905         pc->green_bpaths = g_slist_prepend(pc->green_bpaths, cshape);
907         pc->red_curve_is_valid = false;
908     }
912 /*
913   Local Variables:
914   mode:c++
915   c-file-style:"stroustrup"
916   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
917   indent-tabs-mode:nil
918   fill-column:99
919   End:
920 */
921 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :