Code

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