Code

fix parameter ranges, copyedit
[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                 SnapManager &m = desktop->namedview->snap_manager;
256                                 m.setup(desktop);
257                                 sp_canvas_set_snap_delay_active(desktop->canvas, true);
259                 if (bevent.state & GDK_CONTROL_MASK) {
260                         if (!(bevent.state & GDK_SHIFT_MASK)) {
261                                 m.freeSnapReturnByRef(Inkscape::SnapPreferences::SNAPPOINT_NODE, p);
262                         }
263                                         spdc_create_single_dot(event_context, p, "/tools/freehand/pencil", bevent.state);
264                                         sp_canvas_set_snap_delay_active(desktop->canvas, false);
265                                         ret = true;
266                     break;
267                 }
268                 if (anchor) {
269                     p = anchor->dp;
270                     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path"));
271                 } else {
273                     if (!(bevent.state & GDK_SHIFT_MASK)) {
274                                                 // This is the first click of a new curve; deselect item so that
275                         // this curve is not combined with it (unless it is drawn from its
276                         // anchor, which is handled by the sibling branch above)
277                         selection->clear();
278                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path"));
279                         m.freeSnapReturnByRef(Inkscape::SnapPreferences::SNAPPOINT_NODE, p);
280                     } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) {
281                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path"));
282                         m.freeSnapReturnByRef(Inkscape::SnapPreferences::SNAPPOINT_NODE, p);
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         SPDesktop *const dt = pc->desktop;
301         if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) {
302         // mouse was accidentally moved during Ctrl+click;
303         // ignore the motion and create a single point
304         pc->is_drawing = false;
305         return TRUE;
306     }
307     gint ret = FALSE;
309     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
310     if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
311         // allow scrolling
312         return FALSE;
313     }
315     if ( ( mevent.state & GDK_BUTTON1_MASK ) && !pc->grab && pc->is_drawing) {
316         /* Grab mouse, so release will not pass unnoticed */
317         pc->grab = SP_CANVAS_ITEM(dt->acetate);
318         sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK   |
319                                         GDK_BUTTON_RELEASE_MASK |
320                                         GDK_POINTER_MOTION_MASK  ),
321                             NULL, mevent.time);
322     }
324     /* Find desktop coordinates */
325     Geom::Point p = dt->w2d(Geom::Point(mevent.x, mevent.y));
327     /* Test whether we hit any anchor. */
328     SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(mevent.x, mevent.y));
330     if (pencil_within_tolerance) {
331         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
332         gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
333         if ( Geom::LInfty( Geom::Point(mevent.x,mevent.y) - pencil_drag_origin_w ) < tolerance ) {
334             return FALSE;   // Do not drag if we're within tolerance from origin.
335         }
336     }
338     // Once the user has moved farther than tolerance from the original location
339     // (indicating they intend to move the object, not click), then always process the
340     // motion notify coordinates as given (no snapping back to origin)
341     pencil_within_tolerance = false;
343     switch (pc->state) {
344         case SP_PENCIL_CONTEXT_ADDLINE:
345             /* Set red endpoint */
346             if (anchor) {
347                 p = anchor->dp;
348             } else {
349                 Geom::Point ptnr(p);
350                 spdc_endpoint_snap(pc, ptnr, mevent.state);
351                 p = ptnr;
352             }
353             spdc_set_endpoint(pc, p);
354             ret = TRUE;
355             break;
356         default:
357             /* We may be idle or already freehand */
358             if ( mevent.state & GDK_BUTTON1_MASK && pc->is_drawing ) {
359                 if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
360                         sp_canvas_set_snap_delay_active(dt->canvas, false);
361                 }
362                 pc->state = SP_PENCIL_CONTEXT_FREEHAND;
364                 if ( !pc->sa && !pc->green_anchor ) {
365                     /* Create green anchor */
366                     pc->green_anchor = sp_draw_anchor_new(pc, pc->green_curve, TRUE, pc->p[0]);
367                 }
368                 /** \todo
369                  * fixme: I am not sure whether we want to snap to anchors
370                  * in middle of freehand (Lauris)
371                  */
372                 if (anchor) {
373                     p = anchor->dp;
374                 }
376                 if ( pc->npoints != 0) { // buttonpress may have happened before we entered draw context!
377                                         spdc_add_freehand_point(pc, p, mevent.state);
378                                         ret = TRUE;
379                 }
381                 if (anchor && !pc->anchor_statusbar) {
382                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path."));
383                     pc->anchor_statusbar = true;
384                 } else if (!anchor && pc->anchor_statusbar) {
385                     pc->_message_context->clear();
386                     pc->anchor_statusbar = false;
387                 } else if (!anchor) {
388                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path"));
389                 }
391             } else {
392                 if (anchor && !pc->anchor_statusbar) {
393                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point."));
394                     pc->anchor_statusbar = true;
395                 } else if (!anchor && pc->anchor_statusbar) {
396                     pc->_message_context->clear();
397                     pc->anchor_statusbar = false;
398                 }
399             }
400             break;
401     }
402     return ret;
405 static gint
406 pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
408     gint ret = FALSE;
410     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
411     if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
412         SPDesktop *const dt = pc->desktop;
414         pc->is_drawing = false;
416         /* Find desktop coordinates */
417         Geom::Point p = dt->w2d(Geom::Point(revent.x, revent.y));
419         /* Test whether we hit any anchor. */
420         SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(revent.x,
421                                                               revent.y));
423         switch (pc->state) {
424             case SP_PENCIL_CONTEXT_IDLE:
425                 /* Releasing button in idle mode means single click */
426                 /* We have already set up start point/anchor in button_press */
427                 if (!(revent.state & GDK_CONTROL_MASK)) {
428                     // Ctrl+click creates a single point so only set context in ADDLINE mode when Ctrl isn't pressed
429                     pc->state = SP_PENCIL_CONTEXT_ADDLINE;
430                     //sp_canvas_set_snap_delay_active(dt->canvas, true);
431                 }
432                 ret = TRUE;
433                 break;
434             case SP_PENCIL_CONTEXT_ADDLINE:
435                 /* Finish segment now */
436                 if (anchor) {
437                     p = anchor->dp;
438                 } else {
439                     spdc_endpoint_snap(pc, p, revent.state);
440                 }
441                 pc->ea = anchor;
442                 spdc_set_endpoint(pc, p);
443                 spdc_finish_endpoint(pc);
444                 pc->state = SP_PENCIL_CONTEXT_IDLE;
445                 sp_canvas_set_snap_delay_active(dt->canvas, false);
446                 ret = TRUE;
447                 break;
448             case SP_PENCIL_CONTEXT_FREEHAND:
449                 if (revent.state & GDK_MOD1_MASK) {
450                     /* sketch mode: interpolate the sketched path and improve the current output path with the new interpolation. don't finish sketch */
452                     sketch_interpolate(pc);
454                     if (pc->green_anchor) {
455                         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
456                     }
458                     pc->state = SP_PENCIL_CONTEXT_SKETCH;
459                     //sp_canvas_set_snap_delay_active(dt->canvas, true);
460                 } else {
461                     /* Finish segment now */
462                     /// \todo fixme: Clean up what follows (Lauris)
463                     if (anchor) {
464                         p = anchor->dp;
465                     }
466                     pc->ea = anchor;
467                     /* Write curves to object */
469                     dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));
471                     interpolate(pc);
472                     spdc_concat_colors_and_flush(pc, FALSE);
473                     pc->sa = NULL;
474                     pc->ea = NULL;
475                     if (pc->green_anchor) {
476                         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
477                     }
478                     pc->state = SP_PENCIL_CONTEXT_IDLE;
479                     // sp_canvas_set_snap_delay_active(dt->canvas, false);
480                     // reset sketch mode too
481                     pc->sketch_n = 0;
482                 }
483                 ret = TRUE;
484                 break;
485             case SP_PENCIL_CONTEXT_SKETCH:
486             default:
487                 break;
488         }
490         if (pc->grab) {
491             /* Release grab now */
492             sp_canvas_item_ungrab(pc->grab, revent.time);
493             pc->grab = NULL;
494         }
496         ret = TRUE;
497     }
498     return ret;
501 static void
502 pencil_cancel (SPPencilContext *const pc)
504     if (pc->grab) {
505         /* Release grab now */
506         sp_canvas_item_ungrab(pc->grab, 0);
507         pc->grab = NULL;
508     }
510     pc->is_drawing = false;
511     pc->state = SP_PENCIL_CONTEXT_IDLE;
512     sp_canvas_set_snap_delay_active(pc->desktop->canvas, false);
514     pc->red_curve->reset();
515     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
516     while (pc->green_bpaths) {
517         gtk_object_destroy(GTK_OBJECT(pc->green_bpaths->data));
518         pc->green_bpaths = g_slist_remove(pc->green_bpaths, pc->green_bpaths->data);
519     }
520     pc->green_curve->reset();
521     if (pc->green_anchor) {
522         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
523     }
525     pc->_message_context->clear();
526     pc->_message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled"));
528     sp_canvas_end_forced_full_redraws(pc->desktop->canvas);
531 static gint
532 pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state)
534     gint ret = FALSE;
535     switch (keyval) {
536         case GDK_Up:
537         case GDK_Down:
538         case GDK_KP_Up:
539         case GDK_KP_Down:
540             // Prevent the zoom field from activation.
541             if (!mod_ctrl_only(state)) {
542                 ret = TRUE;
543             }
544             break;
545         case GDK_Escape:
546             if (pc->npoints != 0) {
547                 // if drawing, cancel, otherwise pass it up for deselecting
548                 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
549                     pencil_cancel (pc);
550                     ret = TRUE;
551                 }
552             }
553             break;
554         case GDK_z:
555         case GDK_Z:
556             if (mod_ctrl_only(state) && pc->npoints != 0) {
557                 // if drawing, cancel, otherwise pass it up for undo
558                 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
559                     pencil_cancel (pc);
560                     ret = TRUE;
561                 }
562             }
563             break;
564         case GDK_g:
565         case GDK_G:
566             if (mod_shift_only(state)) {
567                 sp_selection_to_guides(SP_EVENT_CONTEXT(pc)->desktop);
568                 ret = true;
569             }
570             break;
571         case GDK_Alt_L:
572         case GDK_Alt_R:
573         case GDK_Meta_L:
574         case GDK_Meta_R:
575             if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
576                 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."));
577             }
578             break;
579         default:
580             break;
581     }
582     return ret;
585 static gint
586 pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const /*state*/)
588     gint ret = FALSE;
589     switch (keyval) {
590         case GDK_Alt_L:
591         case GDK_Alt_R:
592         case GDK_Meta_L:
593         case GDK_Meta_R:
594             if (pc->state == SP_PENCIL_CONTEXT_SKETCH) {
595                 spdc_concat_colors_and_flush(pc, FALSE);
596                 pc->sketch_n = 0;
597                 pc->sa = NULL;
598                 pc->ea = NULL;
599                 if (pc->green_anchor) {
600                     pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
601                 }
602                 pc->state = SP_PENCIL_CONTEXT_IDLE;
603                 sp_canvas_set_snap_delay_active(pc->desktop->canvas, false);
604                 pc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand sketch"));
605                 ret = TRUE;
606             }
607             break;
608         default:
609             break;
610     }
611     return ret;
614 /**
615  * Reset points and set new starting point.
616  */
617 static void
618 spdc_set_startpoint(SPPencilContext *const pc, Geom::Point const p)
620     pc->npoints = 0;
621     pc->red_curve_is_valid = false;
622     if (in_svg_plane(p)) {
623         pc->p[pc->npoints++] = p;
624     }
627 /**
628  * Change moving endpoint position.
629  * <ul>
630  * <li>Ctrl constrains to moving to H/V direction, snapping in given direction.
631  * <li>Otherwise we snap freely to whatever attractors are available.
632  * </ul>
633  *
634  * Number of points is (re)set to 2 always, 2nd point is modified.
635  * We change RED curve.
636  */
637 static void
638 spdc_set_endpoint(SPPencilContext *const pc, Geom::Point const p)
640     if (pc->npoints == 0) {
641         return;
642         /* May occur if first point wasn't in SVG plane (e.g. weird w2d transform, perhaps from bad
643          * zoom setting).
644          */
645     }
646     g_return_if_fail( pc->npoints > 0 );
648     pc->red_curve->reset();
649     if ( ( p == pc->p[0] )
650          || !in_svg_plane(p) )
651     {
652         pc->npoints = 1;
653     } else {
654         pc->p[1] = p;
655         pc->npoints = 2;
657         pc->red_curve->moveto(pc->p[0]);
658         pc->red_curve->lineto(pc->p[1]);
659         pc->red_curve_is_valid = true;
661         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
662     }
665 /**
666  * Finalize addline.
667  *
668  * \todo
669  * fixme: I'd like remove red reset from concat colors (lauris).
670  * Still not sure, how it will make most sense.
671  */
672 static void
673 spdc_finish_endpoint(SPPencilContext *const pc)
675     if ( ( pc->red_curve->is_empty() )
676          || ( *(pc->red_curve->first_point()) == *(pc->red_curve->second_point())   ) )
677     {
678         pc->red_curve->reset();
679         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
680     } else {
681         /* Write curves to object. */
682         spdc_concat_colors_and_flush(pc, FALSE);
683         pc->sa = NULL;
684         pc->ea = NULL;
685     }
689 static void
690 spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint /*state*/)
692     g_assert( pc->npoints > 0 );
693     g_return_if_fail(unsigned(pc->npoints) < G_N_ELEMENTS(pc->p));
695     if ( ( p != pc->p[ pc->npoints - 1 ] )
696          && in_svg_plane(p) )
697     {
698         pc->ps.push_back(p);
699         pc->p[pc->npoints++] = p;
700         fit_and_split(pc);
701     }
704 static inline double
705 square(double const x)
707     return x * x;
710 static void
711 interpolate(SPPencilContext *pc)
714     if ( pc->ps.size() <= 1 ) {
715         return;
716     }
718     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
719     double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
720     double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
721                                                tol) * exp(0.2*tol - 2);
723     g_assert(is_zero(pc->req_tangent)
724              || is_unit_vector(pc->req_tangent));
725     Geom::Point const tHatEnd(0, 0);
727     guint n_points  = pc->ps.size();
728     pc->green_curve->reset();
729     pc->red_curve->reset();
730     pc->red_curve_is_valid = false;
732     Geom::Point * b = g_new(Geom::Point, 4*n_points);
733     Geom::Point * points = g_new(Geom::Point, 4*n_points);
734     for (unsigned int i = 0; i < pc->ps.size(); i++) {
735         points[i] = pc->ps[i];
736     }
738     // worst case gives us a segment per point
739     int max_segs = 4*n_points;
741     int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
742                                              tolerance_sq, max_segs);
744     if ( n_segs > 0)
745     {
746         /* Fit and draw and reset state */
747         pc->green_curve->moveto(b[0]);
748         for (int c = 0; c < n_segs; c++) {
749             pc->green_curve->curveto(b[4*c+1], b[4*c+2], b[4*c+3]);
750         }
751         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
753         /* Fit and draw and copy last point */
754         g_assert(!pc->green_curve->is_empty());
756         /* Set up direction of next curve. */
757         {
758             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
759             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
760             pc->p[0] = last_seg->finalPoint();
761             pc->npoints = 1;
762             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
763             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
764                                 ? Geom::Point(0, 0)
765                                 : Geom::unit_vector(req_vec) );
766         }
767     }
768     g_free(b);
769     g_free(points);
770     pc->ps.clear();
774 /* interpolates the sketched curve and tweaks the current sketch interpolation*/
775 static void
776 sketch_interpolate(SPPencilContext *pc)
778     g_assert( pc->ps.size() > 1 );
780     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
781     double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
782     double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
783                                                tol) * exp(0.2*tol - 2);
785     bool average_all_sketches = prefs->getBool("/tools/freehand/pencil/average_all_sketches", true);
787     g_assert(is_zero(pc->req_tangent)
788              || is_unit_vector(pc->req_tangent));
789     Geom::Point const tHatEnd(0, 0);
791     guint n_points  = pc->ps.size();
792     pc->red_curve->reset();
793     pc->red_curve_is_valid = false;
795     Geom::Point * b = g_new(Geom::Point, 4*n_points);
796     Geom::Point * points = g_new(Geom::Point, 4*n_points);
797     for (unsigned i = 0; i < pc->ps.size(); i++) {
798         points[i] = pc->ps[i];
799     }
801     // worst case gives us a segment per point
802     int max_segs = 4*n_points;
804     int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
805                                              tolerance_sq, max_segs);
807     if ( n_segs > 0)
808     {
809         Geom::Path fit(b[0]);
810         for (int c = 0; c < n_segs; c++) {
811             fit.appendNew<Geom::CubicBezier>(b[4*c+1], b[4*c+2], b[4*c+3]);
812         }
813         Geom::Piecewise<Geom::D2<Geom::SBasis> > fit_pwd2 = fit.toPwSb();
815         double t =0.;
816         if ( pc->sketch_n > 0 ) {
817             if (average_all_sketches) {
818                 // Average = (sum of all) / n
819                 //         = (sum of all + new one) / n+1
820                 //         = ((old average)*n + new one) / n+1
821                 t = pc->sketch_n / (pc->sketch_n + 1.);
822             } else {
823                 t = 0.5;
824             }
825             pc->sketch_interpolation = Geom::lerp(t, fit_pwd2, pc->sketch_interpolation);
826         } else {
827             pc->sketch_interpolation = fit_pwd2;
828         }
829         pc->sketch_n++;
831         pc->green_curve->reset();
832         pc->green_curve->set_pathvector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
833         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
835         /* Fit and draw and copy last point */
836         g_assert(!pc->green_curve->is_empty());
838         /* Set up direction of next curve. */
839         {
840             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
841             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
842             pc->p[0] = last_seg->finalPoint();
843             pc->npoints = 1;
844             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
845             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
846                                 ? Geom::Point(0, 0)
847                                 : Geom::unit_vector(req_vec) );
848         }
849     }
850     g_free(b);
851     g_free(points);
852     pc->ps.clear();
855 static void
856 fit_and_split(SPPencilContext *pc)
858     g_assert( pc->npoints > 1 );
860     double const tolerance_sq = 0;
862     Geom::Point b[4];
863     g_assert(is_zero(pc->req_tangent)
864              || is_unit_vector(pc->req_tangent));
865     Geom::Point const tHatEnd(0, 0);
866     int const n_segs = Geom::bezier_fit_cubic_full(b, NULL, pc->p, pc->npoints,
867                                                 pc->req_tangent, tHatEnd,
868                                                 tolerance_sq, 1);
869     if ( n_segs > 0
870          && unsigned(pc->npoints) < G_N_ELEMENTS(pc->p) )
871     {
872         /* Fit and draw and reset state */
873         pc->red_curve->reset();
874         pc->red_curve->moveto(b[0]);
875         pc->red_curve->curveto(b[1], b[2], b[3]);
876         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
877         pc->red_curve_is_valid = true;
878     } else {
879         /* Fit and draw and copy last point */
881         g_assert(!pc->red_curve->is_empty());
883         /* Set up direction of next curve. */
884         {
885             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->red_curve->last_segment());
886             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
887             pc->p[0] = last_seg->finalPoint();
888             pc->npoints = 1;
889             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
890             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
891                                 ? Geom::Point(0, 0)
892                                 : Geom::unit_vector(req_vec) );
893         }
895         pc->green_curve->append_continuous(pc->red_curve, 0.0625);
896         SPCurve *curve = pc->red_curve->copy();
898         /// \todo fixme:
899         SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(pc->desktop), curve);
900         curve->unref();
901         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), pc->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
903         pc->green_bpaths = g_slist_prepend(pc->green_bpaths, cshape);
905         pc->red_curve_is_valid = false;
906     }
910 /*
911   Local Variables:
912   mode:c++
913   c-file-style:"stroustrup"
914   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
915   indent-tabs-mode:nil
916   fill-column:99
917   End:
918 */
919 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :