Code

add accessor for the waiting_cursor flag (sorry for the recompile)
[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         Geom::Point const button_w(bevent.x, bevent.y);
240         /* Find desktop coordinates */
241         Geom::Point p = pc->desktop->w2d(button_w);
243         /* Test whether we hit any anchor. */
244         SPDrawAnchor *anchor = spdc_test_inside(pc, button_w);
246         pencil_drag_origin_w = Geom::Point(bevent.x,bevent.y);
247         pencil_within_tolerance = true;
249         switch (pc->state) {
250             case SP_PENCIL_CONTEXT_ADDLINE:
251                 /* Current segment will be finished with release */
252                 ret = TRUE;
253                 break;
254             default:
255                 /* Set first point of sequence */
256                 SnapManager &m = desktop->namedview->snap_manager;
257                                 m.setup(desktop);
258                                 sp_canvas_set_snap_delay_active(desktop->canvas, true);
260                 if (bevent.state & GDK_CONTROL_MASK) {
261                         if (!(bevent.state & GDK_SHIFT_MASK)) {
262                                 m.freeSnapReturnByRef(Inkscape::SnapPreferences::SNAPPOINT_NODE, p);
263                         }
264                                         spdc_create_single_dot(event_context, p, "/tools/freehand/pencil", bevent.state);
265                                         sp_canvas_set_snap_delay_active(desktop->canvas, false);
266                                         ret = true;
267                     break;
268                 }
269                 if (anchor) {
270                     p = anchor->dp;
271                     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path"));
272                 } else {
274                     if (!(bevent.state & GDK_SHIFT_MASK)) {
275                                                 // This is the first click of a new curve; deselect item so that
276                         // this curve is not combined with it (unless it is drawn from its
277                         // anchor, which is handled by the sibling branch above)
278                         selection->clear();
279                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path"));
280                         m.freeSnapReturnByRef(Inkscape::SnapPreferences::SNAPPOINT_NODE, p);
281                     } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) {
282                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path"));
283                         m.freeSnapReturnByRef(Inkscape::SnapPreferences::SNAPPOINT_NODE, p);
284                     }
285                 }
286                 pc->sa = anchor;
287                 spdc_set_startpoint(pc, p);
288                 ret = TRUE;
289                 break;
290         }
292         pc->is_drawing = true;
293     }
294     return ret;
297 static gint
298 pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent)
300         SPDesktop *const dt = pc->desktop;
302         if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) {
303         // mouse was accidentally moved during Ctrl+click;
304         // ignore the motion and create a single point
305         pc->is_drawing = false;
306         return TRUE;
307     }
308     gint ret = FALSE;
310     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
311     if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
312         // allow scrolling
313         return FALSE;
314     }
316     if ( ( mevent.state & GDK_BUTTON1_MASK ) && !pc->grab && pc->is_drawing) {
317         /* Grab mouse, so release will not pass unnoticed */
318         pc->grab = SP_CANVAS_ITEM(dt->acetate);
319         sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK   |
320                                         GDK_BUTTON_RELEASE_MASK |
321                                         GDK_POINTER_MOTION_MASK  ),
322                             NULL, mevent.time);
323     }
325     /* Find desktop coordinates */
326     Geom::Point p = dt->w2d(Geom::Point(mevent.x, mevent.y));
328     /* Test whether we hit any anchor. */
329     SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(mevent.x, mevent.y));
331     if (pencil_within_tolerance) {
332         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
333         gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
334         if ( Geom::LInfty( Geom::Point(mevent.x,mevent.y) - pencil_drag_origin_w ) < tolerance ) {
335             return FALSE;   // Do not drag if we're within tolerance from origin.
336         }
337     }
339     // Once the user has moved farther than tolerance from the original location
340     // (indicating they intend to move the object, not click), then always process the
341     // motion notify coordinates as given (no snapping back to origin)
342     pencil_within_tolerance = false;
344     switch (pc->state) {
345         case SP_PENCIL_CONTEXT_ADDLINE:
346             /* Set red endpoint */
347             if (anchor) {
348                 p = anchor->dp;
349             } else {
350                 Geom::Point ptnr(p);
351                 spdc_endpoint_snap(pc, ptnr, mevent.state);
352                 p = ptnr;
353             }
354             spdc_set_endpoint(pc, p);
355             ret = TRUE;
356             break;
357         default:
358             /* We may be idle or already freehand */
359             if ( mevent.state & GDK_BUTTON1_MASK && pc->is_drawing ) {
360                 if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
361                         sp_canvas_set_snap_delay_active(dt->canvas, false);
362                 }
363                 pc->state = SP_PENCIL_CONTEXT_FREEHAND;
365                 if ( !pc->sa && !pc->green_anchor ) {
366                     /* Create green anchor */
367                     pc->green_anchor = sp_draw_anchor_new(pc, pc->green_curve, TRUE, pc->p[0]);
368                 }
369                 /** \todo
370                  * fixme: I am not sure whether we want to snap to anchors
371                  * in middle of freehand (Lauris)
372                  */
373                 if (anchor) {
374                     p = anchor->dp;
375                 }
377                 if ( pc->npoints != 0) { // buttonpress may have happened before we entered draw context!
378                                         spdc_add_freehand_point(pc, p, mevent.state);
379                                         ret = TRUE;
380                 }
382                 if (anchor && !pc->anchor_statusbar) {
383                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path."));
384                     pc->anchor_statusbar = true;
385                 } else if (!anchor && pc->anchor_statusbar) {
386                     pc->_message_context->clear();
387                     pc->anchor_statusbar = false;
388                 } else if (!anchor) {
389                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path"));
390                 }
392             } else {
393                 if (anchor && !pc->anchor_statusbar) {
394                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point."));
395                     pc->anchor_statusbar = true;
396                 } else if (!anchor && pc->anchor_statusbar) {
397                     pc->_message_context->clear();
398                     pc->anchor_statusbar = false;
399                 }
400             }
401             break;
402     }
403     return ret;
406 static gint
407 pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
409     gint ret = FALSE;
411     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
412     if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
413         SPDesktop *const dt = pc->desktop;
415         pc->is_drawing = false;
417         /* Find desktop coordinates */
418         Geom::Point p = dt->w2d(Geom::Point(revent.x, revent.y));
420         /* Test whether we hit any anchor. */
421         SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(revent.x,
422                                                               revent.y));
424         switch (pc->state) {
425             case SP_PENCIL_CONTEXT_IDLE:
426                 /* Releasing button in idle mode means single click */
427                 /* We have already set up start point/anchor in button_press */
428                 if (!(revent.state & GDK_CONTROL_MASK)) {
429                     // Ctrl+click creates a single point so only set context in ADDLINE mode when Ctrl isn't pressed
430                     pc->state = SP_PENCIL_CONTEXT_ADDLINE;
431                     //sp_canvas_set_snap_delay_active(dt->canvas, true);
432                 }
433                 ret = TRUE;
434                 break;
435             case SP_PENCIL_CONTEXT_ADDLINE:
436                 /* Finish segment now */
437                 if (anchor) {
438                     p = anchor->dp;
439                 } else {
440                     spdc_endpoint_snap(pc, p, revent.state);
441                 }
442                 pc->ea = anchor;
443                 spdc_set_endpoint(pc, p);
444                 spdc_finish_endpoint(pc);
445                 pc->state = SP_PENCIL_CONTEXT_IDLE;
446                 sp_canvas_set_snap_delay_active(dt->canvas, false);
447                 ret = TRUE;
448                 break;
449             case SP_PENCIL_CONTEXT_FREEHAND:
450                 if (revent.state & GDK_MOD1_MASK) {
451                     /* sketch mode: interpolate the sketched path and improve the current output path with the new interpolation. don't finish sketch */
453                     sketch_interpolate(pc);
455                     if (pc->green_anchor) {
456                         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
457                     }
459                     pc->state = SP_PENCIL_CONTEXT_SKETCH;
460                     //sp_canvas_set_snap_delay_active(dt->canvas, true);
461                 } else {
462                     /* Finish segment now */
463                     /// \todo fixme: Clean up what follows (Lauris)
464                     if (anchor) {
465                         p = anchor->dp;
466                     }
467                     pc->ea = anchor;
468                     /* Write curves to object */
470                     dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));
472                     interpolate(pc);
473                     spdc_concat_colors_and_flush(pc, FALSE);
474                     pc->sa = NULL;
475                     pc->ea = NULL;
476                     if (pc->green_anchor) {
477                         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
478                     }
479                     pc->state = SP_PENCIL_CONTEXT_IDLE;
480                     // sp_canvas_set_snap_delay_active(dt->canvas, false);
481                     // reset sketch mode too
482                     pc->sketch_n = 0;
483                 }
484                 ret = TRUE;
485                 break;
486             case SP_PENCIL_CONTEXT_SKETCH:
487             default:
488                 break;
489         }
491         if (pc->grab) {
492             /* Release grab now */
493             sp_canvas_item_ungrab(pc->grab, revent.time);
494             pc->grab = NULL;
495         }
497         ret = TRUE;
498     }
499     return ret;
502 static void
503 pencil_cancel (SPPencilContext *const pc)
505     if (pc->grab) {
506         /* Release grab now */
507         sp_canvas_item_ungrab(pc->grab, 0);
508         pc->grab = NULL;
509     }
511     pc->is_drawing = false;
512     pc->state = SP_PENCIL_CONTEXT_IDLE;
513     sp_canvas_set_snap_delay_active(pc->desktop->canvas, false);
515     pc->red_curve->reset();
516     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
517     while (pc->green_bpaths) {
518         gtk_object_destroy(GTK_OBJECT(pc->green_bpaths->data));
519         pc->green_bpaths = g_slist_remove(pc->green_bpaths, pc->green_bpaths->data);
520     }
521     pc->green_curve->reset();
522     if (pc->green_anchor) {
523         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
524     }
526     pc->_message_context->clear();
527     pc->_message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled"));
529     sp_canvas_end_forced_full_redraws(pc->desktop->canvas);
532 static gint
533 pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state)
535     gint ret = FALSE;
536     switch (keyval) {
537         case GDK_Up:
538         case GDK_Down:
539         case GDK_KP_Up:
540         case GDK_KP_Down:
541             // Prevent the zoom field from activation.
542             if (!mod_ctrl_only(state)) {
543                 ret = TRUE;
544             }
545             break;
546         case GDK_Escape:
547             if (pc->npoints != 0) {
548                 // if drawing, cancel, otherwise pass it up for deselecting
549                 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
550                     pencil_cancel (pc);
551                     ret = TRUE;
552                 }
553             }
554             break;
555         case GDK_z:
556         case GDK_Z:
557             if (mod_ctrl_only(state) && pc->npoints != 0) {
558                 // if drawing, cancel, otherwise pass it up for undo
559                 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
560                     pencil_cancel (pc);
561                     ret = TRUE;
562                 }
563             }
564             break;
565         case GDK_g:
566         case GDK_G:
567             if (mod_shift_only(state)) {
568                 sp_selection_to_guides(SP_EVENT_CONTEXT(pc)->desktop);
569                 ret = true;
570             }
571             break;
572         case GDK_Alt_L:
573         case GDK_Alt_R:
574         case GDK_Meta_L:
575         case GDK_Meta_R:
576             if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
577                 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."));
578             }
579             break;
580         default:
581             break;
582     }
583     return ret;
586 static gint
587 pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const /*state*/)
589     gint ret = FALSE;
590     switch (keyval) {
591         case GDK_Alt_L:
592         case GDK_Alt_R:
593         case GDK_Meta_L:
594         case GDK_Meta_R:
595             if (pc->state == SP_PENCIL_CONTEXT_SKETCH) {
596                 spdc_concat_colors_and_flush(pc, FALSE);
597                 pc->sketch_n = 0;
598                 pc->sa = NULL;
599                 pc->ea = NULL;
600                 if (pc->green_anchor) {
601                     pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
602                 }
603                 pc->state = SP_PENCIL_CONTEXT_IDLE;
604                 sp_canvas_set_snap_delay_active(pc->desktop->canvas, false);
605                 pc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand sketch"));
606                 ret = TRUE;
607             }
608             break;
609         default:
610             break;
611     }
612     return ret;
615 /**
616  * Reset points and set new starting point.
617  */
618 static void
619 spdc_set_startpoint(SPPencilContext *const pc, Geom::Point const p)
621     pc->npoints = 0;
622     pc->red_curve_is_valid = false;
623     if (in_svg_plane(p)) {
624         pc->p[pc->npoints++] = p;
625     }
628 /**
629  * Change moving endpoint position.
630  * <ul>
631  * <li>Ctrl constrains to moving to H/V direction, snapping in given direction.
632  * <li>Otherwise we snap freely to whatever attractors are available.
633  * </ul>
634  *
635  * Number of points is (re)set to 2 always, 2nd point is modified.
636  * We change RED curve.
637  */
638 static void
639 spdc_set_endpoint(SPPencilContext *const pc, Geom::Point const p)
641     if (pc->npoints == 0) {
642         return;
643         /* May occur if first point wasn't in SVG plane (e.g. weird w2d transform, perhaps from bad
644          * zoom setting).
645          */
646     }
647     g_return_if_fail( pc->npoints > 0 );
649     pc->red_curve->reset();
650     if ( ( p == pc->p[0] )
651          || !in_svg_plane(p) )
652     {
653         pc->npoints = 1;
654     } else {
655         pc->p[1] = p;
656         pc->npoints = 2;
658         pc->red_curve->moveto(pc->p[0]);
659         pc->red_curve->lineto(pc->p[1]);
660         pc->red_curve_is_valid = true;
662         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
663     }
666 /**
667  * Finalize addline.
668  *
669  * \todo
670  * fixme: I'd like remove red reset from concat colors (lauris).
671  * Still not sure, how it will make most sense.
672  */
673 static void
674 spdc_finish_endpoint(SPPencilContext *const pc)
676     if ( ( pc->red_curve->is_empty() )
677          || ( *(pc->red_curve->first_point()) == *(pc->red_curve->second_point())   ) )
678     {
679         pc->red_curve->reset();
680         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
681     } else {
682         /* Write curves to object. */
683         spdc_concat_colors_and_flush(pc, FALSE);
684         pc->sa = NULL;
685         pc->ea = NULL;
686     }
690 static void
691 spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint /*state*/)
693     g_assert( pc->npoints > 0 );
694     g_return_if_fail(unsigned(pc->npoints) < G_N_ELEMENTS(pc->p));
696     if ( ( p != pc->p[ pc->npoints - 1 ] )
697          && in_svg_plane(p) )
698     {
699         pc->ps.push_back(p);
700         pc->p[pc->npoints++] = p;
701         fit_and_split(pc);
702     }
705 static inline double
706 square(double const x)
708     return x * x;
711 static void
712 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     if ( pc->ps.size() <= 1 ) {
779         return;
780     }
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(t, fit_pwd2, pc->sketch_interpolation);
828             // simplify path, to eliminate small segments
829             Path *path = new Path;
830             path->LoadPathVector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
831             path->Simplify(0.5);
832             Geom::PathVector *pathv = path->MakePathVector();
833             pc->sketch_interpolation = (*pathv)[0].toPwSb();
834             delete path;
835             delete pathv;
836         } else {
837             pc->sketch_interpolation = fit_pwd2;
838         }
839         pc->sketch_n++;
841         pc->green_curve->reset();
842         pc->green_curve->set_pathvector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
843         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
845         /* Fit and draw and copy last point */
846         g_assert(!pc->green_curve->is_empty());
848         /* Set up direction of next curve. */
849         {
850             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
851             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
852             pc->p[0] = last_seg->finalPoint();
853             pc->npoints = 1;
854             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
855             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
856                                 ? Geom::Point(0, 0)
857                                 : Geom::unit_vector(req_vec) );
858         }
859     }
860     g_free(b);
861     g_free(points);
862     pc->ps.clear();
865 static void
866 fit_and_split(SPPencilContext *pc)
868     g_assert( pc->npoints > 1 );
870     double const tolerance_sq = 0;
872     Geom::Point b[4];
873     g_assert(is_zero(pc->req_tangent)
874              || is_unit_vector(pc->req_tangent));
875     Geom::Point const tHatEnd(0, 0);
876     int const n_segs = Geom::bezier_fit_cubic_full(b, NULL, pc->p, pc->npoints,
877                                                 pc->req_tangent, tHatEnd,
878                                                 tolerance_sq, 1);
879     if ( n_segs > 0
880          && unsigned(pc->npoints) < G_N_ELEMENTS(pc->p) )
881     {
882         /* Fit and draw and reset state */
883         pc->red_curve->reset();
884         pc->red_curve->moveto(b[0]);
885         pc->red_curve->curveto(b[1], b[2], b[3]);
886         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
887         pc->red_curve_is_valid = true;
888     } else {
889         /* Fit and draw and copy last point */
891         g_assert(!pc->red_curve->is_empty());
893         /* Set up direction of next curve. */
894         {
895             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->red_curve->last_segment());
896             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
897             pc->p[0] = last_seg->finalPoint();
898             pc->npoints = 1;
899             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
900             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
901                                 ? Geom::Point(0, 0)
902                                 : Geom::unit_vector(req_vec) );
903         }
905         pc->green_curve->append_continuous(pc->red_curve, 0.0625);
906         SPCurve *curve = pc->red_curve->copy();
908         /// \todo fixme:
909         SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(pc->desktop), curve);
910         curve->unref();
911         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), pc->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
913         pc->green_bpaths = g_slist_prepend(pc->green_bpaths, cshape);
915         pc->red_curve_is_valid = false;
916     }
920 /*
921   Local Variables:
922   mode:c++
923   c-file-style:"stroustrup"
924   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
925   indent-tabs-mode:nil
926   fill-column:99
927   End:
928 */
929 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :