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;
112 }
114 /**
115 * Callback to initialize SPPencilContext object.
116 */
117 static void
118 sp_pencil_context_init(SPPencilContext *pc)
119 {
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;
133 }
135 /**
136 * Callback to setup SPPencilContext object.
137 */
138 static void
139 sp_pencil_context_setup(SPEventContext *ec)
140 {
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;
154 }
156 static void
157 sp_pencil_context_dispose(GObject *object)
158 {
159 G_OBJECT_CLASS(pencil_parent_class)->dispose(object);
160 }
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)
165 {
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 }
175 }
177 /**
178 * Callback for handling all pencil context events.
179 */
180 gint
181 sp_pencil_context_root_handler(SPEventContext *const ec, GdkEvent *event)
182 {
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;
221 }
223 static gint
224 pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent)
225 {
226 gint ret = FALSE;
227 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
228 if ( bevent.button == 1 && !event_context->space_panning) {
230 SPDrawContext *dc = SP_DRAW_CONTEXT (pc);
231 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
232 Inkscape::Selection *selection = sp_desktop_selection(desktop);
234 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
235 return TRUE;
236 }
238 if (!pc->grab) {
239 /* Grab mouse, so release will not pass unnoticed */
240 pc->grab = SP_CANVAS_ITEM(desktop->acetate);
241 sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK |
242 GDK_BUTTON_RELEASE_MASK |
243 GDK_POINTER_MOTION_MASK ),
244 NULL, bevent.time);
245 }
247 Geom::Point const button_w(bevent.x, bevent.y);
249 /* Find desktop coordinates */
250 Geom::Point p = pc->desktop->w2d(button_w);
252 /* Test whether we hit any anchor. */
253 SPDrawAnchor *anchor = spdc_test_inside(pc, button_w);
255 pencil_drag_origin_w = Geom::Point(bevent.x,bevent.y);
256 pencil_within_tolerance = true;
258 switch (pc->state) {
259 case SP_PENCIL_CONTEXT_ADDLINE:
260 /* Current segment will be finished with release */
261 ret = TRUE;
262 break;
263 default:
264 /* Set first point of sequence */
265 SnapManager &m = desktop->namedview->snap_manager;
266 m.setup(desktop);
268 if (bevent.state & GDK_CONTROL_MASK) {
269 if (!(bevent.state & GDK_SHIFT_MASK)) {
270 m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE);
271 }
272 spdc_create_single_dot(event_context, p, "/tools/freehand/pencil", bevent.state);
273 ret = true;
274 break;
275 }
276 if (anchor) {
277 p = anchor->dp;
278 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path"));
279 } else {
281 if (!(bevent.state & GDK_SHIFT_MASK)) {
282 // This is the first click of a new curve; deselect item so that
283 // this curve is not combined with it (unless it is drawn from its
284 // anchor, which is handled by the sibling branch above)
285 selection->clear();
286 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path"));
287 m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE);
288 } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) {
289 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path"));
290 m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE);
291 }
292 }
293 m.unSetup();
294 pc->sa = anchor;
295 spdc_set_startpoint(pc, p);
296 ret = TRUE;
297 break;
298 }
300 pc->is_drawing = true;
301 }
302 return ret;
303 }
305 static gint
306 pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent)
307 {
308 SPDesktop *const dt = pc->desktop;
310 if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) {
311 // mouse was accidentally moved during Ctrl+click;
312 // ignore the motion and create a single point
313 pc->is_drawing = false;
314 return TRUE;
315 }
316 gint ret = FALSE;
318 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
319 if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
320 // allow scrolling
321 return FALSE;
322 }
324 if ( ( mevent.state & GDK_BUTTON1_MASK ) && !pc->grab && pc->is_drawing) {
325 /* Grab mouse, so release will not pass unnoticed */
326 pc->grab = SP_CANVAS_ITEM(dt->acetate);
327 sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK |
328 GDK_BUTTON_RELEASE_MASK |
329 GDK_POINTER_MOTION_MASK ),
330 NULL, mevent.time);
331 }
333 /* Find desktop coordinates */
334 Geom::Point p = dt->w2d(Geom::Point(mevent.x, mevent.y));
336 /* Test whether we hit any anchor. */
337 SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(mevent.x, mevent.y));
339 if (pencil_within_tolerance) {
340 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
341 gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
342 if ( Geom::LInfty( Geom::Point(mevent.x,mevent.y) - pencil_drag_origin_w ) < tolerance ) {
343 return FALSE; // Do not drag if we're within tolerance from origin.
344 }
345 }
347 // Once the user has moved farther than tolerance from the original location
348 // (indicating they intend to move the object, not click), then always process the
349 // motion notify coordinates as given (no snapping back to origin)
350 pencil_within_tolerance = false;
352 switch (pc->state) {
353 case SP_PENCIL_CONTEXT_ADDLINE:
354 /* Set red endpoint */
355 if (anchor) {
356 p = anchor->dp;
357 } else {
358 Geom::Point ptnr(p);
359 spdc_endpoint_snap(pc, ptnr, mevent.state);
360 p = ptnr;
361 }
362 spdc_set_endpoint(pc, p);
363 ret = TRUE;
364 break;
365 default:
366 /* We may be idle or already freehand */
367 if ( mevent.state & GDK_BUTTON1_MASK && pc->is_drawing ) {
368 if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
369 sp_event_context_discard_delayed_snap_event(event_context);
370 }
371 pc->state = SP_PENCIL_CONTEXT_FREEHAND;
373 if ( !pc->sa && !pc->green_anchor ) {
374 /* Create green anchor */
375 pc->green_anchor = sp_draw_anchor_new(pc, pc->green_curve, TRUE, pc->p[0]);
376 }
377 if (anchor) {
378 p = anchor->dp;
379 }
381 if ( pc->npoints != 0) { // buttonpress may have happened before we entered draw context!
382 if (pc->ps.size() == 0) {
383 // Only in freehand mode we have to add the first point also to pc->ps (apparently)
384 // - We cannot add this point in spdc_set_startpoint, because we only need it for freehand
385 // - We cannot do this in the button press handler because at that point we don't know yet
386 // wheter we're going into freehand mode or not
387 pc->ps.push_back(pc->p[0]);
388 }
389 spdc_add_freehand_point(pc, p, mevent.state);
390 ret = TRUE;
391 }
393 if (anchor && !pc->anchor_statusbar) {
394 pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path."));
395 pc->anchor_statusbar = true;
396 } else if (!anchor && pc->anchor_statusbar) {
397 pc->_message_context->clear();
398 pc->anchor_statusbar = false;
399 } else if (!anchor) {
400 pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path"));
401 }
403 } else {
404 if (anchor && !pc->anchor_statusbar) {
405 pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point."));
406 pc->anchor_statusbar = true;
407 } else if (!anchor && pc->anchor_statusbar) {
408 pc->_message_context->clear();
409 pc->anchor_statusbar = false;
410 }
411 }
413 // Show the pre-snap indicator to communicate to the user where we would snap to if he/she were to
414 // a) press the mousebutton to start a freehand drawing, or
415 // b) release the mousebutton to finish a freehand drawing
416 if (!sp_event_context_knot_mouseover(pc)) {
417 SnapManager &m = dt->namedview->snap_manager;
418 m.setup(dt);
419 m.preSnap(Inkscape::SnapCandidatePoint(p, Inkscape::SNAPSOURCE_NODE_HANDLE));
420 m.unSetup();
421 }
422 break;
423 }
424 return ret;
425 }
427 static gint
428 pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
429 {
430 gint ret = FALSE;
432 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
433 if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
434 SPDesktop *const dt = pc->desktop;
436 pc->is_drawing = false;
438 /* Find desktop coordinates */
439 Geom::Point p = dt->w2d(Geom::Point(revent.x, revent.y));
441 /* Test whether we hit any anchor. */
442 SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(revent.x,
443 revent.y));
445 switch (pc->state) {
446 case SP_PENCIL_CONTEXT_IDLE:
447 /* Releasing button in idle mode means single click */
448 /* We have already set up start point/anchor in button_press */
449 if (!(revent.state & GDK_CONTROL_MASK)) {
450 // Ctrl+click creates a single point so only set context in ADDLINE mode when Ctrl isn't pressed
451 pc->state = SP_PENCIL_CONTEXT_ADDLINE;
452 }
453 ret = TRUE;
454 break;
455 case SP_PENCIL_CONTEXT_ADDLINE:
456 /* Finish segment now */
457 if (anchor) {
458 p = anchor->dp;
459 } else {
460 spdc_endpoint_snap(pc, p, revent.state);
461 }
462 pc->ea = anchor;
463 spdc_set_endpoint(pc, p);
464 spdc_finish_endpoint(pc);
465 pc->state = SP_PENCIL_CONTEXT_IDLE;
466 sp_event_context_discard_delayed_snap_event(event_context);
467 ret = TRUE;
468 break;
469 case SP_PENCIL_CONTEXT_FREEHAND:
470 if (revent.state & GDK_MOD1_MASK) {
471 /* sketch mode: interpolate the sketched path and improve the current output path with the new interpolation. don't finish sketch */
473 sketch_interpolate(pc);
475 if (pc->green_anchor) {
476 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
477 }
479 pc->state = SP_PENCIL_CONTEXT_SKETCH;
480 } else {
481 /* Finish segment now */
482 /// \todo fixme: Clean up what follows (Lauris)
483 if (anchor) {
484 p = anchor->dp;
485 } else {
486 Geom::Point p_end = p;
487 spdc_endpoint_snap(pc, p_end, revent.state);
488 if (p_end != p) {
489 // then we must have snapped!
490 spdc_add_freehand_point(pc, p_end, revent.state);
491 }
492 }
494 pc->ea = anchor;
495 /* Write curves to object */
497 dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));
499 interpolate(pc);
500 spdc_concat_colors_and_flush(pc, FALSE);
501 pc->sa = NULL;
502 pc->ea = NULL;
503 if (pc->green_anchor) {
504 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
505 }
506 pc->state = SP_PENCIL_CONTEXT_IDLE;
507 // reset sketch mode too
508 pc->sketch_n = 0;
509 }
510 ret = TRUE;
511 break;
512 case SP_PENCIL_CONTEXT_SKETCH:
513 default:
514 break;
515 }
517 if (pc->grab) {
518 /* Release grab now */
519 sp_canvas_item_ungrab(pc->grab, revent.time);
520 pc->grab = NULL;
521 }
523 ret = TRUE;
524 }
525 return ret;
526 }
528 static void
529 pencil_cancel (SPPencilContext *const pc)
530 {
531 if (pc->grab) {
532 /* Release grab now */
533 sp_canvas_item_ungrab(pc->grab, 0);
534 pc->grab = NULL;
535 }
537 pc->is_drawing = false;
538 pc->state = SP_PENCIL_CONTEXT_IDLE;
539 sp_event_context_discard_delayed_snap_event(SP_EVENT_CONTEXT(pc));
541 pc->red_curve->reset();
542 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
543 while (pc->green_bpaths) {
544 gtk_object_destroy(GTK_OBJECT(pc->green_bpaths->data));
545 pc->green_bpaths = g_slist_remove(pc->green_bpaths, pc->green_bpaths->data);
546 }
547 pc->green_curve->reset();
548 if (pc->green_anchor) {
549 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
550 }
552 pc->_message_context->clear();
553 pc->_message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled"));
555 sp_canvas_end_forced_full_redraws(pc->desktop->canvas);
556 }
558 static gint
559 pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state)
560 {
561 gint ret = FALSE;
562 switch (keyval) {
563 case GDK_Up:
564 case GDK_Down:
565 case GDK_KP_Up:
566 case GDK_KP_Down:
567 // Prevent the zoom field from activation.
568 if (!mod_ctrl_only(state)) {
569 ret = TRUE;
570 }
571 break;
572 case GDK_Escape:
573 if (pc->npoints != 0) {
574 // if drawing, cancel, otherwise pass it up for deselecting
575 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
576 pencil_cancel (pc);
577 ret = TRUE;
578 }
579 }
580 break;
581 case GDK_z:
582 case GDK_Z:
583 if (mod_ctrl_only(state) && pc->npoints != 0) {
584 // if drawing, cancel, otherwise pass it up for undo
585 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
586 pencil_cancel (pc);
587 ret = TRUE;
588 }
589 }
590 break;
591 case GDK_g:
592 case GDK_G:
593 if (mod_shift_only(state)) {
594 sp_selection_to_guides(SP_EVENT_CONTEXT(pc)->desktop);
595 ret = true;
596 }
597 break;
598 case GDK_Alt_L:
599 case GDK_Alt_R:
600 case GDK_Meta_L:
601 case GDK_Meta_R:
602 if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
603 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."));
604 }
605 break;
606 default:
607 break;
608 }
609 return ret;
610 }
612 static gint
613 pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const /*state*/)
614 {
615 gint ret = FALSE;
616 switch (keyval) {
617 case GDK_Alt_L:
618 case GDK_Alt_R:
619 case GDK_Meta_L:
620 case GDK_Meta_R:
621 if (pc->state == SP_PENCIL_CONTEXT_SKETCH) {
622 spdc_concat_colors_and_flush(pc, FALSE);
623 pc->sketch_n = 0;
624 pc->sa = NULL;
625 pc->ea = NULL;
626 if (pc->green_anchor) {
627 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
628 }
629 pc->state = SP_PENCIL_CONTEXT_IDLE;
630 sp_event_context_discard_delayed_snap_event(SP_EVENT_CONTEXT(pc));
631 pc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand sketch"));
632 ret = TRUE;
633 }
634 break;
635 default:
636 break;
637 }
638 return ret;
639 }
641 /**
642 * Reset points and set new starting point.
643 */
644 static void
645 spdc_set_startpoint(SPPencilContext *const pc, Geom::Point const p)
646 {
647 pc->npoints = 0;
648 pc->red_curve_is_valid = false;
649 if (in_svg_plane(p)) {
650 pc->p[pc->npoints++] = p;
651 }
652 }
654 /**
655 * Change moving endpoint position.
656 * <ul>
657 * <li>Ctrl constrains to moving to H/V direction, snapping in given direction.
658 * <li>Otherwise we snap freely to whatever attractors are available.
659 * </ul>
660 *
661 * Number of points is (re)set to 2 always, 2nd point is modified.
662 * We change RED curve.
663 */
664 static void
665 spdc_set_endpoint(SPPencilContext *const pc, Geom::Point const p)
666 {
667 if (pc->npoints == 0) {
668 return;
669 /* May occur if first point wasn't in SVG plane (e.g. weird w2d transform, perhaps from bad
670 * zoom setting).
671 */
672 }
673 g_return_if_fail( pc->npoints > 0 );
675 pc->red_curve->reset();
676 if ( ( p == pc->p[0] )
677 || !in_svg_plane(p) )
678 {
679 pc->npoints = 1;
680 } else {
681 pc->p[1] = p;
682 pc->npoints = 2;
684 pc->red_curve->moveto(pc->p[0]);
685 pc->red_curve->lineto(pc->p[1]);
686 pc->red_curve_is_valid = true;
688 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
689 }
690 }
692 /**
693 * Finalize addline.
694 *
695 * \todo
696 * fixme: I'd like remove red reset from concat colors (lauris).
697 * Still not sure, how it will make most sense.
698 */
699 static void
700 spdc_finish_endpoint(SPPencilContext *const pc)
701 {
702 if ( ( pc->red_curve->is_empty() )
703 || ( *(pc->red_curve->first_point()) == *(pc->red_curve->second_point()) ) )
704 {
705 pc->red_curve->reset();
706 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
707 } else {
708 /* Write curves to object. */
709 spdc_concat_colors_and_flush(pc, FALSE);
710 pc->sa = NULL;
711 pc->ea = NULL;
712 }
713 }
716 static void
717 spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint /*state*/)
718 {
719 g_assert( pc->npoints > 0 );
720 g_return_if_fail(unsigned(pc->npoints) < G_N_ELEMENTS(pc->p));
722 if ( ( p != pc->p[ pc->npoints - 1 ] )
723 && in_svg_plane(p) )
724 {
725 pc->ps.push_back(p);
726 pc->p[pc->npoints++] = p;
727 fit_and_split(pc);
728 }
729 }
731 static inline double
732 square(double const x)
733 {
734 return x * x;
735 }
737 static void
738 interpolate(SPPencilContext *pc)
739 {
740 if ( pc->ps.size() <= 1 ) {
741 return;
742 }
744 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
745 double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
746 double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
747 tol) * exp(0.2*tol - 2);
749 g_assert(is_zero(pc->req_tangent)
750 || is_unit_vector(pc->req_tangent));
751 Geom::Point const tHatEnd(0, 0);
753 guint n_points = pc->ps.size();
754 pc->green_curve->reset();
755 pc->red_curve->reset();
756 pc->red_curve_is_valid = false;
758 Geom::Point * b = g_new(Geom::Point, 4*n_points);
759 Geom::Point * points = g_new(Geom::Point, 4*n_points);
760 for (unsigned int i = 0; i < pc->ps.size(); i++) {
761 points[i] = pc->ps[i];
762 }
764 // worst case gives us a segment per point
765 int max_segs = 4*n_points;
767 int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
768 tolerance_sq, max_segs);
770 if ( n_segs > 0)
771 {
772 /* Fit and draw and reset state */
773 pc->green_curve->moveto(b[0]);
774 for (int c = 0; c < n_segs; c++) {
775 pc->green_curve->curveto(b[4*c+1], b[4*c+2], b[4*c+3]);
776 }
777 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
779 /* Fit and draw and copy last point */
780 g_assert(!pc->green_curve->is_empty());
782 /* Set up direction of next curve. */
783 {
784 Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
785 g_assert( last_seg ); // Relevance: validity of (*last_seg)[2]
786 pc->p[0] = last_seg->finalPoint();
787 pc->npoints = 1;
788 Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
789 pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
790 ? Geom::Point(0, 0)
791 : Geom::unit_vector(req_vec) );
792 }
793 }
794 g_free(b);
795 g_free(points);
796 pc->ps.clear();
797 }
800 /* interpolates the sketched curve and tweaks the current sketch interpolation*/
801 static void
802 sketch_interpolate(SPPencilContext *pc)
803 {
804 if ( pc->ps.size() <= 1 ) {
805 return;
806 }
808 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
809 double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
810 double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
811 tol) * exp(0.2*tol - 2);
813 bool average_all_sketches = prefs->getBool("/tools/freehand/pencil/average_all_sketches", true);
815 g_assert(is_zero(pc->req_tangent)
816 || is_unit_vector(pc->req_tangent));
817 Geom::Point const tHatEnd(0, 0);
819 guint n_points = pc->ps.size();
820 pc->red_curve->reset();
821 pc->red_curve_is_valid = false;
823 Geom::Point * b = g_new(Geom::Point, 4*n_points);
824 Geom::Point * points = g_new(Geom::Point, 4*n_points);
825 for (unsigned i = 0; i < pc->ps.size(); i++) {
826 points[i] = pc->ps[i];
827 }
829 // worst case gives us a segment per point
830 int max_segs = 4*n_points;
832 int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
833 tolerance_sq, max_segs);
835 if ( n_segs > 0)
836 {
837 Geom::Path fit(b[0]);
838 for (int c = 0; c < n_segs; c++) {
839 fit.appendNew<Geom::CubicBezier>(b[4*c+1], b[4*c+2], b[4*c+3]);
840 }
841 Geom::Piecewise<Geom::D2<Geom::SBasis> > fit_pwd2 = fit.toPwSb();
843 double t =0.;
844 if ( pc->sketch_n > 0 ) {
845 if (average_all_sketches) {
846 // Average = (sum of all) / n
847 // = (sum of all + new one) / n+1
848 // = ((old average)*n + new one) / n+1
849 t = pc->sketch_n / (pc->sketch_n + 1.);
850 } else {
851 t = 0.5;
852 }
853 pc->sketch_interpolation = Geom::lerp(t, fit_pwd2, pc->sketch_interpolation);
854 // simplify path, to eliminate small segments
855 Path *path = new Path;
856 path->LoadPathVector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
857 path->Simplify(0.5);
858 Geom::PathVector *pathv = path->MakePathVector();
859 pc->sketch_interpolation = (*pathv)[0].toPwSb();
860 delete path;
861 delete pathv;
862 } else {
863 pc->sketch_interpolation = fit_pwd2;
864 }
865 pc->sketch_n++;
867 pc->green_curve->reset();
868 pc->green_curve->set_pathvector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
869 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
871 /* Fit and draw and copy last point */
872 g_assert(!pc->green_curve->is_empty());
874 /* Set up direction of next curve. */
875 {
876 Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
877 g_assert( last_seg ); // Relevance: validity of (*last_seg)[2]
878 pc->p[0] = last_seg->finalPoint();
879 pc->npoints = 1;
880 Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
881 pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
882 ? Geom::Point(0, 0)
883 : Geom::unit_vector(req_vec) );
884 }
885 }
886 g_free(b);
887 g_free(points);
888 pc->ps.clear();
889 }
891 static void
892 fit_and_split(SPPencilContext *pc)
893 {
894 g_assert( pc->npoints > 1 );
896 double const tolerance_sq = 0;
898 Geom::Point b[4];
899 g_assert(is_zero(pc->req_tangent)
900 || is_unit_vector(pc->req_tangent));
901 Geom::Point const tHatEnd(0, 0);
902 int const n_segs = Geom::bezier_fit_cubic_full(b, NULL, pc->p, pc->npoints,
903 pc->req_tangent, tHatEnd,
904 tolerance_sq, 1);
905 if ( n_segs > 0
906 && unsigned(pc->npoints) < G_N_ELEMENTS(pc->p) )
907 {
908 /* Fit and draw and reset state */
909 pc->red_curve->reset();
910 pc->red_curve->moveto(b[0]);
911 pc->red_curve->curveto(b[1], b[2], b[3]);
912 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
913 pc->red_curve_is_valid = true;
914 } else {
915 /* Fit and draw and copy last point */
917 g_assert(!pc->red_curve->is_empty());
919 /* Set up direction of next curve. */
920 {
921 Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->red_curve->last_segment());
922 g_assert( last_seg ); // Relevance: validity of (*last_seg)[2]
923 pc->p[0] = last_seg->finalPoint();
924 pc->npoints = 1;
925 Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
926 pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
927 ? Geom::Point(0, 0)
928 : Geom::unit_vector(req_vec) );
929 }
931 pc->green_curve->append_continuous(pc->red_curve, 0.0625);
932 SPCurve *curve = pc->red_curve->copy();
934 /// \todo fixme:
935 SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(pc->desktop), curve);
936 curve->unref();
937 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), pc->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
939 pc->green_bpaths = g_slist_prepend(pc->green_bpaths, cshape);
941 pc->red_curve_is_valid = false;
942 }
943 }
946 /*
947 Local Variables:
948 mode:c++
949 c-file-style:"stroustrup"
950 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
951 indent-tabs-mode:nil
952 fill-column:99
953 End:
954 */
955 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :