Code

Split SPCanvasItem and SPCanvasGroup to individual .h files. Removed forward header.
[inkscape.git] / src / dyna-draw-context.cpp
1 /*
2  * Handwriting-like drawing mode
3  *
4  * Authors:
5  *   Mitsuru Oka <oka326@parkcity.ne.jp>
6  *   Lauris Kaplinski <lauris@kaplinski.com>
7  *   bulia byak <buliabyak@users.sf.net>
8  *   MenTaLguY <mental@rydia.net>
9  *   Abhishek Sharma
10  *
11  * The original dynadraw code:
12  *   Paul Haeberli <paul@sgi.com>
13  *
14  * Copyright (C) 1998 The Free Software Foundation
15  * Copyright (C) 1999-2005 authors
16  * Copyright (C) 2001-2002 Ximian, Inc.
17  * Copyright (C) 2005-2007 bulia byak
18  * Copyright (C) 2006 MenTaLguY
19  *
20  * Released under GNU GPL, read the file 'COPYING' for more information
21  */
23 #define noDYNA_DRAW_VERBOSE
25 #include "config.h"
27 #include <gtk/gtk.h>
28 #include <gdk/gdkkeysyms.h>
29 #include <glibmm/i18n.h>
30 #include <string>
31 #include <cstring>
32 #include <numeric>
34 #include "svg/svg.h"
35 #include "display/canvas-bpath.h"
36 #include <2geom/isnan.h>
37 #include <2geom/pathvector.h>
38 #include <2geom/bezier-utils.h>
39 #include "display/curve.h"
40 #include <glib/gmem.h>
41 #include "macros.h"
42 #include "document.h"
43 #include "selection.h"
44 #include "desktop.h"
45 #include "desktop-events.h"
46 #include "desktop-handles.h"
47 #include "desktop-style.h"
48 #include "message-context.h"
49 #include "preferences.h"
50 #include "pixmaps/cursor-calligraphy.xpm"
51 #include "xml/repr.h"
52 #include "context-fns.h"
53 #include "sp-item.h"
54 #include "inkscape.h"
55 #include "color.h"
56 #include "splivarot.h"
57 #include "sp-item-group.h"
58 #include "sp-shape.h"
59 #include "sp-path.h"
60 #include "sp-text.h"
61 #include "display/sp-canvas.h"
62 #include "display/canvas-bpath.h"
63 #include "display/canvas-arena.h"
64 #include "livarot/Shape.h"
66 #include "dyna-draw-context.h"
68 using Inkscape::DocumentUndo;
70 #define DDC_RED_RGBA 0xff0000ff
72 #define TOLERANCE_CALLIGRAPHIC 0.1
74 #define DYNA_EPSILON 0.5e-6
75 #define DYNA_EPSILON_START 0.5e-2
76 #define DYNA_VEL_START 1e-5
78 #define DYNA_MIN_WIDTH 1.0e-6
80 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
81 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
82 static void sp_dyna_draw_context_dispose(GObject *object);
84 static void sp_dyna_draw_context_setup(SPEventContext *ec);
85 static void sp_dyna_draw_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *value);
86 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
88 static void clear_current(SPDynaDrawContext *dc);
89 static void set_to_accumulated(SPDynaDrawContext *dc, bool unionize, bool subtract);
90 static void add_cap(SPCurve *curve, Geom::Point const &from, Geom::Point const &to, double rounding);
91 static bool accumulate_calligraphic(SPDynaDrawContext *dc);
93 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
95 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, Geom::Point p);
96 static Geom::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, Geom::Point v);
97 static Geom::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, Geom::Point n);
98 static void draw_temporary_box(SPDynaDrawContext *dc);
101 static SPEventContextClass *dd_parent_class = 0;
103 GType sp_dyna_draw_context_get_type(void)
105     static GType type = 0;
106     if (!type) {
107         GTypeInfo info = {
108             sizeof(SPDynaDrawContextClass),
109             0, // base_init
110             0, // base_finalize
111             (GClassInitFunc)sp_dyna_draw_context_class_init,
112             0, // class_finalize
113             0, // class_data
114             sizeof(SPDynaDrawContext),
115             0, // n_preallocs
116             (GInstanceInitFunc)sp_dyna_draw_context_init,
117             0 // value_table
118         };
119         type = g_type_register_static(SP_TYPE_COMMON_CONTEXT, "SPDynaDrawContext", &info, static_cast<GTypeFlags>(0));
120     }
121     return type;
124 static void
125 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
127     GObjectClass *object_class = (GObjectClass *) klass;
128     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
130     dd_parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
132     object_class->dispose = sp_dyna_draw_context_dispose;
134     event_context_class->setup = sp_dyna_draw_context_setup;
135     event_context_class->set = sp_dyna_draw_context_set;
136     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
139 static void
140 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
142     ddc->cursor_shape = cursor_calligraphy_xpm;
143     ddc->hot_x = 4;
144     ddc->hot_y = 4;
146     ddc->vel_thin = 0.1;
147     ddc->flatness = 0.9;
148     ddc->cap_rounding = 0.0;
150     ddc->abs_width = false;
151     ddc->keep_selected = true;
153     ddc->hatch_spacing = 0;
154     ddc->hatch_spacing_step = 0;
155     new (&ddc->hatch_pointer_past) std::list<double>();
156     new (&ddc->hatch_nearest_past) std::list<double>();
157     new (&ddc->inertia_vectors) std::list<Geom::Point>();
158     new (&ddc->hatch_vectors) std::list<Geom::Point>();
159     ddc->hatch_last_nearest = Geom::Point(0,0);
160     ddc->hatch_last_pointer = Geom::Point(0,0);
161     ddc->hatch_escaped = false;
162     ddc->hatch_area = NULL;
163     ddc->hatch_item = NULL;
164     ddc->hatch_livarot_path = NULL;
166     ddc->trace_bg = false;
167     ddc->just_started_drawing = false;
170 static void
171 sp_dyna_draw_context_dispose(GObject *object)
173     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
175     if (ddc->hatch_area) {
176         gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
177         ddc->hatch_area = NULL;
178     }
181     G_OBJECT_CLASS(dd_parent_class)->dispose(object);
183     ddc->hatch_pointer_past.~list();
184     ddc->hatch_nearest_past.~list();
185     ddc->inertia_vectors.~list();
186     ddc->hatch_vectors.~list();
189 static void
190 sp_dyna_draw_context_setup(SPEventContext *ec)
192     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
194     if (((SPEventContextClass *) dd_parent_class)->setup)
195         ((SPEventContextClass *) dd_parent_class)->setup(ec);
197     ddc->accumulated = new SPCurve();
198     ddc->currentcurve = new SPCurve();
200     ddc->cal1 = new SPCurve();
201     ddc->cal2 = new SPCurve();
203     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
204     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
205     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
206     /* fixme: Cannot we cascade it to root more clearly? */
207     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
209     {
210         /* TODO: this can be done either with an arcto, and should maybe also be put in a general file (other tools use this as well) */
211         SPCurve *c = new SPCurve();
212         const double C1 = 0.552;
213         c->moveto(-1,0);
214         c->curveto(-1, C1, -C1, 1, 0, 1 );
215         c->curveto(C1, 1, 1, C1, 1, 0 );
216         c->curveto(1, -C1, C1, -1, 0, -1 );
217         c->curveto(-C1, -1, -1, -C1, -1, 0 );
218         c->closepath();
219         ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
220         c->unref();
221         sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
222         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
223         sp_canvas_item_hide(ddc->hatch_area);
224     }
226     sp_event_context_read(ec, "mass");
227     sp_event_context_read(ec, "wiggle");
228     sp_event_context_read(ec, "angle");
229     sp_event_context_read(ec, "width");
230     sp_event_context_read(ec, "thinning");
231     sp_event_context_read(ec, "tremor");
232     sp_event_context_read(ec, "flatness");
233     sp_event_context_read(ec, "tracebackground");
234     sp_event_context_read(ec, "usepressure");
235     sp_event_context_read(ec, "usetilt");
236     sp_event_context_read(ec, "abs_width");
237     sp_event_context_read(ec, "keep_selected");
238     sp_event_context_read(ec, "cap_rounding");
240     ddc->is_drawing = false;
241     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
243     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
244     if (prefs->getBool("/tools/calligraphic/selcue")) {
245         ec->enableSelectionCue();
246     }
249 static void
250 sp_dyna_draw_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val)
252     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
253     Glib::ustring path = val->getEntryName();
255     if (path == "tracebackground") {
256         ddc->trace_bg = val->getBool();
257     } else if (path == "keep_selected") {
258         ddc->keep_selected = val->getBool();
259     } else {
260         //pass on up to parent class to handle common attributes.
261         if ( dd_parent_class->set ) {
262             dd_parent_class->set(ec, val);
263         }
264     }
266     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
269 static double
270 flerp(double f0, double f1, double p)
272     return f0 + ( f1 - f0 ) * p;
275 /* Get normalized point */
276 static Geom::Point
277 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, Geom::Point v)
279     Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
280     double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
281     return Geom::Point(( v[Geom::X] - drect.min()[Geom::X] ) / max,  ( v[Geom::Y] - drect.min()[Geom::Y] ) / max);
284 /* Get view point */
285 static Geom::Point
286 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, Geom::Point n)
288     Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
289     double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
290     return Geom::Point(n[Geom::X] * max + drect.min()[Geom::X], n[Geom::Y] * max + drect.min()[Geom::Y]);
293 static void
294 sp_dyna_draw_reset(SPDynaDrawContext *dc, Geom::Point p)
296     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
297     dc->vel = Geom::Point(0,0);
298     dc->vel_max = 0;
299     dc->acc = Geom::Point(0,0);
300     dc->ang = Geom::Point(0,0);
301     dc->del = Geom::Point(0,0);
304 static void
305 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
307     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
308         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
309     else
310         dc->pressure = DDC_DEFAULT_PRESSURE;
312     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
313         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
314     else
315         dc->xtilt = DDC_DEFAULT_TILT;
317     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
318         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
319     else
320         dc->ytilt = DDC_DEFAULT_TILT;
324 static gboolean
325 sp_dyna_draw_apply(SPDynaDrawContext *dc, Geom::Point p)
327     Geom::Point n = sp_dyna_draw_get_npoint(dc, p);
329     /* Calculate mass and drag */
330     double const mass = flerp(1.0, 160.0, dc->mass);
331     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
333     /* Calculate force and acceleration */
334     Geom::Point force = n - dc->cur;
336     // If force is below the absolute threshold DYNA_EPSILON,
337     // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
338     // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
339     // discard this move.
340     // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
341     // especially bothersome at the start of the stroke where we don't yet have the inertia to
342     // smooth them out.
343     if ( Geom::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && Geom::L2(force) < DYNA_EPSILON_START)) {
344         return FALSE;
345     }
347     dc->acc = force / mass;
349     /* Calculate new velocity */
350     dc->vel += dc->acc;
352     if (Geom::L2(dc->vel) > dc->vel_max)
353         dc->vel_max = Geom::L2(dc->vel);
355     /* Calculate angle of drawing tool */
357     double a1;
358     if (dc->usetilt) {
359         // 1a. calculate nib angle from input device tilt:
360         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
362         if (length > 0) {
363             Geom::Point ang1 = Geom::Point(dc->ytilt/length, dc->xtilt/length);
364             a1 = atan2(ang1);
365         }
366         else
367             a1 = 0.0;
368     }
369     else {
370         // 1b. fixed dc->angle (absolutely flat nib):
371         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
372         Geom::Point ang1 = Geom::Point(-sin(radians),  cos(radians));
373         a1 = atan2(ang1);
374     }
376     // 2. perpendicular to dc->vel (absolutely non-flat nib):
377     gdouble const mag_vel = Geom::L2(dc->vel);
378     if ( mag_vel < DYNA_EPSILON ) {
379         return FALSE;
380     }
381     Geom::Point ang2 = Geom::rot90(dc->vel) / mag_vel;
383     // 3. Average them using flatness parameter:
384     // calculate angles
385     double a2 = atan2(ang2);
386     // flip a2 to force it to be in the same half-circle as a1
387     bool flipped = false;
388     if (fabs (a2-a1) > 0.5*M_PI) {
389         a2 += M_PI;
390         flipped = true;
391     }
392     // normalize a2
393     if (a2 > M_PI)
394         a2 -= 2*M_PI;
395     if (a2 < -M_PI)
396         a2 += 2*M_PI;
397     // find the flatness-weighted bisector angle, unflip if a2 was flipped
398     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
399     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
401     // Try to detect a sudden flip when the new angle differs too much from the previous for the
402     // current velocity; in that case discard this move
403     double angle_delta = Geom::L2(Geom::Point (cos (new_ang), sin (new_ang)) - dc->ang);
404     if ( angle_delta / Geom::L2(dc->vel) > 4000 ) {
405         return FALSE;
406     }
408     // convert to point
409     dc->ang = Geom::Point (cos (new_ang), sin (new_ang));
411 //    g_print ("force %g  acc %g  vel_max %g  vel %g  a1 %g  a2 %g  new_ang %g\n", Geom::L2(force), Geom::L2(dc->acc), dc->vel_max, Geom::L2(dc->vel), a1, a2, new_ang);
413     /* Apply drag */
414     dc->vel *= 1.0 - drag;
416     /* Update position */
417     dc->last = dc->cur;
418     dc->cur += dc->vel;
420     return TRUE;
423 static void
424 sp_dyna_draw_brush(SPDynaDrawContext *dc)
426     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
428     // How much velocity thins strokestyle
429     double vel_thin = flerp (0, 160, dc->vel_thin);
431     // Influence of pressure on thickness
432     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
434     // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
435     // drag)
436     Geom::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
437     Geom::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush);
439     double trace_thick = 1;
440     if (dc->trace_bg) {
441         // pick single pixel
442         NRPixBlock pb;
443         int x = (int) floor(brush_w[Geom::X]);
444         int y = (int) floor(brush_w[Geom::Y]);
445         nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
446         sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
447         const unsigned char *s = NR_PIXBLOCK_PX(&pb);
448         double R = s[0] / 255.0;
449         double G = s[1] / 255.0;
450         double B = s[2] / 255.0;
451         double A = s[3] / 255.0;
452         double max = MAX (MAX (R, G), B);
453         double min = MIN (MIN (R, G), B);
454         double L = A * (max + min)/2 + (1 - A); // blend with white bg
455         trace_thick = 1 - L;
456         //g_print ("L %g thick %g\n", L, trace_thick);
457     }
459     double width = (pressure_thick * trace_thick - vel_thin * Geom::L2(dc->vel)) * dc->width;
461     double tremble_left = 0, tremble_right = 0;
462     if (dc->tremor > 0) {
463         // obtain two normally distributed random variables, using polar Box-Muller transform
464         double x1, x2, w, y1, y2;
465         do {
466             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
467             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
468             w = x1 * x1 + x2 * x2;
469         } while ( w >= 1.0 );
470         w = sqrt( (-2.0 * log( w ) ) / w );
471         y1 = x1 * w;
472         y2 = x2 * w;
474         // deflect both left and right edges randomly and independently, so that:
475         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
476         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
477         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
478         // comparatively smooth and slow ones excessively jittery
479         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
480         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
481     }
483     if ( width < 0.02 * dc->width ) {
484         width = 0.02 * dc->width;
485     }
487     double dezoomify_factor = 0.05 * 1000;
488     if (!dc->abs_width) {
489         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
490     }
492     Geom::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
493     Geom::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
495     dc->point1[dc->npoints] = brush + del_left;
496     dc->point2[dc->npoints] = brush - del_right;
498     dc->del = 0.5*(del_left + del_right);
500     dc->npoints++;
503 void
504 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
506     desktop->setToolboxAdjustmentValue (id, value);
509 static void
510 calligraphic_cancel(SPDynaDrawContext *dc)
512     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
513     dc->dragging = FALSE;
514     dc->is_drawing = false;
515     sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
516             /* Remove all temporary line segments */
517             while (dc->segments) {
518                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
519                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
520             }
521             /* reset accumulated curve */
522             dc->accumulated->reset();
523             clear_current(dc);
524             if (dc->repr) {
525                 dc->repr = NULL;
526             }
530 gint
531 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
532                                   GdkEvent *event)
534     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
535     SPDesktop *desktop = event_context->desktop;
537     gint ret = FALSE;
539     switch (event->type) {
540         case GDK_BUTTON_PRESS:
541             if (event->button.button == 1 && !event_context->space_panning) {
543                 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
545                 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
546                     return TRUE;
547                 }
549                 dc->accumulated->reset();
550                 if (dc->repr) {
551                     dc->repr = NULL;
552                 }
554                 /* initialize first point */
555                 dc->npoints = 0;
557                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
558                                     ( GDK_KEY_PRESS_MASK |
559                                       GDK_BUTTON_RELEASE_MASK |
560                                       GDK_POINTER_MOTION_MASK |
561                                       GDK_BUTTON_PRESS_MASK ),
562                                     NULL,
563                                     event->button.time);
565                 ret = TRUE;
567                 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
568                 dc->is_drawing = true;
569                 dc->just_started_drawing = true;
570             }
571             break;
572         case GDK_MOTION_NOTIFY:
573         {
574             Geom::Point const motion_w(event->motion.x,
575                                      event->motion.y);
576             Geom::Point motion_dt(desktop->w2d(motion_w));
577             sp_dyna_draw_extinput(dc, event);
579             dc->_message_context->clear();
581             // for hatching:
582             double hatch_dist = 0;
583             Geom::Point hatch_unit_vector(0,0);
584             Geom::Point nearest(0,0);
585             Geom::Point pointer(0,0);
586             Geom::Matrix motion_to_curve(Geom::identity());
588             if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
590                 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
591                 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
592                     // One item selected, and it's a path;
593                     // let's try to track it as a guide
595                     if (selected != dc->hatch_item) {
596                         dc->hatch_item = selected;
597                         if (dc->hatch_livarot_path)
598                             delete dc->hatch_livarot_path;
599                         dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
600                         dc->hatch_livarot_path->ConvertWithBackData(0.01);
601                     }
603                     // calculate pointer point in the guide item's coords
604                     motion_to_curve = selected->dt2i_affine() * selected->i2doc_affine();
605                     pointer = motion_dt * motion_to_curve;
607                     // calculate the nearest point on the guide path
608                     boost::optional<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
609                     nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
612                     // distance from pointer to nearest
613                     hatch_dist = Geom::L2(pointer - nearest);
614                     // unit-length vector
615                     hatch_unit_vector = (pointer - nearest)/hatch_dist;
617                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
618                 } else {
619                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
620                 }
621             }
623             if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
624                 dc->dragging = TRUE;
626                 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
628 #define HATCH_VECTOR_ELEMENTS 12
629 #define INERTIA_ELEMENTS 24
630 #define SPEED_ELEMENTS 12
631 #define SPEED_MIN 0.3
632 #define SPEED_NORMAL 0.35
633 #define INERTIA_FORCE 0.5
635                     // speed is the movement of the nearest point along the guide path, divided by
636                     // the movement of the pointer at the same period; it is averaged for the last
637                     // SPEED_ELEMENTS motion events.  Normally, as you track the guide path, speed
638                     // is about 1, i.e. the nearest point on the path is moved by about the same
639                     // distance as the pointer. If the speed starts to decrease, we are losing
640                     // contact with the guide; if it drops below SPEED_MIN, we are on our own and
641                     // not attracted to guide anymore. Most often this happens when you have
642                     // tracked to the end of a guide calligraphic stroke and keep moving
643                     // further. We try to handle this situation gracefully: not stick with the
644                     // guide forever but let go of it smoothly and without sharp jerks (non-zero
645                     // mass recommended; with zero mass, jerks are still quite noticeable).
647                     double speed = 1;
648                     if (Geom::L2(dc->hatch_last_nearest) != 0) {
649                         // the distance nearest moved since the last motion event
650                         double nearest_moved = Geom::L2(nearest - dc->hatch_last_nearest);
651                         // the distance pointer moved since the last motion event
652                         double pointer_moved = Geom::L2(pointer - dc->hatch_last_pointer);
653                         // store them in stacks limited to SPEED_ELEMENTS
654                         dc->hatch_nearest_past.push_front(nearest_moved);
655                         if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
656                             dc->hatch_nearest_past.pop_back();
657                         dc->hatch_pointer_past.push_front(pointer_moved);
658                         if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
659                             dc->hatch_pointer_past.pop_back();
661                         // If the stacks are full,
662                         if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
663                             // calculate the sums of all stored movements
664                             double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
665                             double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
666                             // and divide to get the speed
667                             speed = nearest_sum/pointer_sum;
668                             //g_print ("nearest sum %g  pointer_sum %g  speed %g\n", nearest_sum, pointer_sum, speed);
669                         }
670                     }
672                     if (   dc->hatch_escaped  // already escaped, do not reattach
673                         || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
674                         || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
675                         ) {
676                         // We are NOT attracted to the guide!
678                         //g_print ("\nlast_nearest %g %g   nearest %g %g  pointer %g %g  pos %d %g\n", dc->last_nearest[Geom::X], dc->last_nearest[Geom::Y], nearest[Geom::X], nearest[Geom::Y], pointer[Geom::X], pointer[Geom::Y], position->piece, position->t);
680                         // Remember hatch_escaped so we don't get
681                         // attracted again until the end of this stroke
682                         dc->hatch_escaped = true;
684                         if (dc->inertia_vectors.size() >= INERTIA_ELEMENTS/2) { // move by inertia
685                             Geom::Point moved_past_escape = motion_dt - dc->inertia_vectors.front();
686                             Geom::Point inertia = 
687                                 dc->inertia_vectors.front() - dc->inertia_vectors.back();
689                             double dot = Geom::dot (moved_past_escape, inertia);
690                             dot /= Geom::L2(moved_past_escape) * Geom::L2(inertia);
692                             if (dot > 0) { // mouse is still moving in approx the same direction
693                                 Geom::Point should_have_moved = 
694                                     (inertia) * (1/Geom::L2(inertia)) * Geom::L2(moved_past_escape);
695                                 motion_dt = dc->inertia_vectors.front() + 
696                                     (INERTIA_FORCE * should_have_moved + (1 - INERTIA_FORCE) * moved_past_escape);
697                             }
698                         }
700                     } else {
702                         // Calculate angle cosine of this vector-to-guide and all past vectors
703                         // summed, to detect if we accidentally flipped to the other side of the
704                         // guide
705                         Geom::Point hatch_vector_accumulated = std::accumulate 
706                             (dc->hatch_vectors.begin(), dc->hatch_vectors.end(), Geom::Point(0,0));
707                         double dot = Geom::dot (pointer - nearest, hatch_vector_accumulated);
708                         dot /= Geom::L2(pointer - nearest) * Geom::L2(hatch_vector_accumulated);
710                         if (dc->hatch_spacing != 0) { // spacing was already set
711                             double target;
712                             if (speed > SPEED_NORMAL) {
713                                 // all ok, strictly obey the spacing
714                                 target = dc->hatch_spacing;
715                             } else {
716                                 // looks like we're starting to lose speed,
717                                 // so _gradually_ let go attraction to prevent jerks
718                                 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;
719                             }
720                             if (!IS_NAN(dot) && dot < -0.5) {// flip
721                                 target = -target;
722                             }
724                             // This is the track pointer that we will use instead of the real one
725                             Geom::Point new_pointer = nearest + target * hatch_unit_vector;
727                             // some limited feedback: allow persistent pulling to slightly change
728                             // the spacing
729                             dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
731                             // return it to the desktop coords
732                             motion_dt = new_pointer * motion_to_curve.inverse();
734                             if (speed >= SPEED_NORMAL) {
735                                 dc->inertia_vectors.push_front(motion_dt);
736                                 if (dc->inertia_vectors.size() > INERTIA_ELEMENTS)
737                                     dc->inertia_vectors.pop_back();
738                             }
740                         } else {
741                             // this is the first motion event, set the dist
742                             dc->hatch_spacing = hatch_dist;
743                         }
745                         // remember last points
746                         dc->hatch_last_pointer = pointer;
747                         dc->hatch_last_nearest = nearest;
749                         dc->hatch_vectors.push_front(pointer - nearest);
750                         if (dc->hatch_vectors.size() > HATCH_VECTOR_ELEMENTS)
751                             dc->hatch_vectors.pop_back();
752                     }
754                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
756                 } else {
757                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
758                 }
760                 if (dc->just_started_drawing) {
761                     dc->just_started_drawing = false;
762                     sp_dyna_draw_reset(dc, motion_dt);
763                 }
765                 if (!sp_dyna_draw_apply(dc, motion_dt)) {
766                     ret = TRUE;
767                     break;
768                 }
770                 if ( dc->cur != dc->last ) {
771                     sp_dyna_draw_brush(dc);
772                     g_assert( dc->npoints > 0 );
773                     fit_and_split(dc, FALSE);
774                 }
775                 ret = TRUE;
776             }
778             // Draw the hatching circle if necessary
779             if (event->motion.state & GDK_CONTROL_MASK) {
780                 if (dc->hatch_spacing == 0 && hatch_dist != 0) {
781                     // Haven't set spacing yet: gray, center free, update radius live
782                     Geom::Point c = desktop->w2d(motion_w);
783                     Geom::Matrix const sm (Geom::Scale(hatch_dist, hatch_dist) * Geom::Translate(c));
784                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
785                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
786                     sp_canvas_item_show(dc->hatch_area);
787                 } else if (dc->dragging && !dc->hatch_escaped) {
788                     // Tracking: green, center snapped, fixed radius
789                     Geom::Point c = motion_dt;
790                     Geom::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
791                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
792                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
793                     sp_canvas_item_show(dc->hatch_area);
794                 } else if (dc->dragging && dc->hatch_escaped) {
795                     // Tracking escaped: red, center free, fixed radius
796                     Geom::Point c = motion_dt;
797                     Geom::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
799                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
800                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
801                     sp_canvas_item_show(dc->hatch_area);
802                 } else {
803                     // Not drawing but spacing set: gray, center snapped, fixed radius
804                     Geom::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
805                     if (!IS_NAN(c[Geom::X]) && !IS_NAN(c[Geom::Y])) {
806                         Geom::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
807                         sp_canvas_item_affine_absolute(dc->hatch_area, sm);
808                         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
809                         sp_canvas_item_show(dc->hatch_area);
810                     }
811                 }
812             } else {
813                 sp_canvas_item_hide(dc->hatch_area);
814             }
815         }
816         break;
819     case GDK_BUTTON_RELEASE:
820     {
821         Geom::Point const motion_w(event->button.x, event->button.y);
822         Geom::Point const motion_dt(desktop->w2d(motion_w));
824         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
825         sp_canvas_end_forced_full_redraws(desktop->canvas);
826         dc->is_drawing = false;
828         if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
829             dc->dragging = FALSE;
831             sp_dyna_draw_apply(dc, motion_dt);
833             /* Remove all temporary line segments */
834             while (dc->segments) {
835                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
836                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
837             }
839             /* Create object */
840             fit_and_split(dc, TRUE);
841             if (accumulate_calligraphic(dc))
842                 set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK, event->button.state & GDK_MOD1_MASK); // performs document_done
843             else
844                 g_warning ("Failed to create path: invalid data in dc->cal1 or dc->cal2");
846             /* reset accumulated curve */
847             dc->accumulated->reset();
849             clear_current(dc);
850             if (dc->repr) {
851                 dc->repr = NULL;
852             }
854             if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
855             if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
856             if (!dc->inertia_vectors.empty()) dc->inertia_vectors.clear();
857             if (!dc->hatch_vectors.empty()) dc->hatch_vectors.clear();
858             dc->hatch_last_nearest = Geom::Point(0,0);
859             dc->hatch_last_pointer = Geom::Point(0,0);
860             dc->hatch_escaped = false;
861             dc->hatch_item = NULL;
862             dc->hatch_livarot_path = NULL;
863             dc->just_started_drawing = false;
865             if (dc->hatch_spacing != 0 && !dc->keep_selected) {
866                 // we do not select the newly drawn path, so increase spacing by step
867                 if (dc->hatch_spacing_step == 0) {
868                     dc->hatch_spacing_step = dc->hatch_spacing;
869                 }
870                 dc->hatch_spacing += dc->hatch_spacing_step;
871             }
873             dc->_message_context->clear();
874             ret = TRUE;
875         }
876         break;
877     }
879     case GDK_KEY_PRESS:
880         switch (get_group0_keyval (&event->key)) {
881         case GDK_Up:
882         case GDK_KP_Up:
883             if (!MOD__CTRL_ONLY) {
884                 dc->angle += 5.0;
885                 if (dc->angle > 90.0)
886                     dc->angle = 90.0;
887                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
888                 ret = TRUE;
889             }
890             break;
891         case GDK_Down:
892         case GDK_KP_Down:
893             if (!MOD__CTRL_ONLY) {
894                 dc->angle -= 5.0;
895                 if (dc->angle < -90.0)
896                     dc->angle = -90.0;
897                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
898                 ret = TRUE;
899             }
900             break;
901         case GDK_Right:
902         case GDK_KP_Right:
903             if (!MOD__CTRL_ONLY) {
904                 dc->width += 0.01;
905                 if (dc->width > 1.0)
906                     dc->width = 1.0;
907                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
908                 ret = TRUE;
909             }
910             break;
911         case GDK_Left:
912         case GDK_KP_Left:
913             if (!MOD__CTRL_ONLY) {
914                 dc->width -= 0.01;
915                 if (dc->width < 0.01)
916                     dc->width = 0.01;
917                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
918                 ret = TRUE;
919             }
920             break;
921         case GDK_Home:
922         case GDK_KP_Home:
923             dc->width = 0.01;
924             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
925             ret = TRUE;
926             break;
927         case GDK_End:
928         case GDK_KP_End:
929             dc->width = 1.0;
930             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
931             ret = TRUE;
932             break;
933         case GDK_x:
934         case GDK_X:
935             if (MOD__ALT_ONLY) {
936                 desktop->setToolboxFocusTo ("altx-calligraphy");
937                 ret = TRUE;
938             }
939             break;
940         case GDK_Escape:
941             if (dc->is_drawing) {
942                 // if drawing, cancel, otherwise pass it up for deselecting
943                 calligraphic_cancel (dc);
944                 ret = TRUE;
945             }
946             break;
947         case GDK_z:
948         case GDK_Z:
949             if (MOD__CTRL_ONLY && dc->is_drawing) {
950                 // if drawing, cancel, otherwise pass it up for undo
951                 calligraphic_cancel (dc);
952                 ret = TRUE;
953             }
954             break;
955         default:
956             break;
957         }
958         break;
960     case GDK_KEY_RELEASE:
961         switch (get_group0_keyval(&event->key)) {
962             case GDK_Control_L:
963             case GDK_Control_R:
964                 dc->_message_context->clear();
965                 dc->hatch_spacing = 0;
966                 dc->hatch_spacing_step = 0;
967                 break;
968             default:
969                 break;
970         }
972     default:
973         break;
974     }
976     if (!ret) {
977         if (((SPEventContextClass *) dd_parent_class)->root_handler) {
978             ret = ((SPEventContextClass *) dd_parent_class)->root_handler(event_context, event);
979         }
980     }
982     return ret;
986 static void
987 clear_current(SPDynaDrawContext *dc)
989     /* reset bpath */
990     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
991     /* reset curve */
992     dc->currentcurve->reset();
993     dc->cal1->reset();
994     dc->cal2->reset();
995     /* reset points */
996     dc->npoints = 0;
999 static void
1000 set_to_accumulated(SPDynaDrawContext *dc, bool unionize, bool subtract)
1002     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1004     if (!dc->accumulated->is_empty()) {
1005         if (!dc->repr) {
1006             /* Create object */
1007             Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc();
1008             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1010             /* Set style */
1011             sp_desktop_apply_style_tool (desktop, repr, "/tools/calligraphic", false);
1013             dc->repr = repr;
1015             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
1016             Inkscape::GC::release(dc->repr);
1017             item->transform = SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse();
1018             item->updateRepr();
1019         }
1020         Geom::PathVector pathv = dc->accumulated->get_pathvector() * desktop->dt2doc();
1021         gchar *str = sp_svg_write_path(pathv);
1022         g_assert( str != NULL );
1023         dc->repr->setAttribute("d", str);
1024         g_free(str);
1026         if (unionize) {
1027             sp_desktop_selection(desktop)->add(dc->repr);
1028             sp_selected_path_union_skip_undo(desktop);
1029         } else if (subtract) {
1030             sp_desktop_selection(desktop)->add(dc->repr);
1031             sp_selected_path_diff_skip_undo(desktop);
1032         } else {
1033             if (dc->keep_selected) {
1034                 sp_desktop_selection(desktop)->set(dc->repr);
1035             }
1036         }
1038     } else {
1039         if (dc->repr) {
1040             sp_repr_unparent(dc->repr);
1041         }
1042         dc->repr = NULL;
1043     }
1045     DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC,
1046                        _("Draw calligraphic stroke"));
1049 static void
1050 add_cap(SPCurve *curve,
1051         Geom::Point const &from,
1052         Geom::Point const &to,
1053         double rounding)
1055     if (Geom::L2( to - from ) > DYNA_EPSILON) {
1056         Geom::Point vel = rounding * Geom::rot90( to - from ) / sqrt(2.0);
1057         double mag = Geom::L2(vel);
1059         Geom::Point v = mag * Geom::rot90( to - from ) / Geom::L2( to - from );
1060         curve->curveto(from + v, to + v, to);
1061     }
1064 static bool
1065 accumulate_calligraphic(SPDynaDrawContext *dc)
1067         if (
1068             dc->cal1->is_empty() ||
1069             dc->cal2->is_empty() ||
1070             (dc->cal1->get_segment_count() <= 0) ||
1071             dc->cal1->first_path()->closed()
1072             ) {
1073             dc->cal1->reset();
1074             dc->cal2->reset();
1075             return false; // failure
1076         }
1078         SPCurve *rev_cal2 = dc->cal2->create_reverse();
1079         if (
1080             (rev_cal2->get_segment_count() <= 0) ||
1081             rev_cal2->first_path()->closed()
1082             ) {
1083             rev_cal2->unref();
1084             dc->cal1->reset();
1085             dc->cal2->reset();
1086             return false; // failure
1087         }
1089         Geom::CubicBezier const * dc_cal1_firstseg  = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->first_segment() );
1090         Geom::CubicBezier const * rev_cal2_firstseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->first_segment() );
1091         Geom::CubicBezier const * dc_cal1_lastseg   = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->last_segment() );
1092         Geom::CubicBezier const * rev_cal2_lastseg  = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->last_segment() );
1094         if (
1095             !dc_cal1_firstseg ||
1096             !rev_cal2_firstseg ||
1097             !dc_cal1_lastseg ||
1098             !rev_cal2_lastseg
1099             ) {
1100             rev_cal2->unref();
1101             dc->cal1->reset();
1102             dc->cal2->reset();
1103             return false; // failure
1104         }
1106         dc->accumulated->reset(); /*  Is this required ?? */
1108         dc->accumulated->append(dc->cal1, false);
1110         add_cap(dc->accumulated, (*dc_cal1_lastseg)[3], (*rev_cal2_firstseg)[0], dc->cap_rounding);
1112         dc->accumulated->append(rev_cal2, true);
1114         add_cap(dc->accumulated, (*rev_cal2_lastseg)[3], (*dc_cal1_firstseg)[0], dc->cap_rounding);
1116         dc->accumulated->closepath();
1118         rev_cal2->unref();
1120         dc->cal1->reset();
1121         dc->cal2->reset();
1123         return true; // success
1126 static double square(double const x)
1128     return x * x;
1131 static void
1132 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1134     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1136     double const tolerance_sq = square( desktop->w2d().descrim() * TOLERANCE_CALLIGRAPHIC );
1138 #ifdef DYNA_DRAW_VERBOSE
1139     g_print("[F&S:R=%c]", release?'T':'F');
1140 #endif
1142     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1143         return; // just clicked
1145     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1146 #define BEZIER_SIZE       4
1147 #define BEZIER_MAX_BEZIERS  8
1148 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1150 #ifdef DYNA_DRAW_VERBOSE
1151         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1152                 dc->npoints, release ? "TRUE" : "FALSE");
1153 #endif
1155         /* Current calligraphic */
1156         if ( dc->cal1->is_empty() || dc->cal2->is_empty() ) {
1157             /* dc->npoints > 0 */
1158             /* g_print("calligraphics(1|2) reset\n"); */
1159             dc->cal1->reset();
1160             dc->cal2->reset();
1162             dc->cal1->moveto(dc->point1[0]);
1163             dc->cal2->moveto(dc->point2[0]);
1164         }
1166         Geom::Point b1[BEZIER_MAX_LENGTH];
1167         gint const nb1 = Geom::bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1168                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1169         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1171         Geom::Point b2[BEZIER_MAX_LENGTH];
1172         gint const nb2 = Geom::bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1173                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1174         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1176         if ( nb1 != -1 && nb2 != -1 ) {
1177             /* Fit and draw and reset state */
1178 #ifdef DYNA_DRAW_VERBOSE
1179             g_print("nb1:%d nb2:%d\n", nb1, nb2);
1180 #endif
1181             /* CanvasShape */
1182             if (! release) {
1183                 dc->currentcurve->reset();
1184                 dc->currentcurve->moveto(b1[0]);
1185                 for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1186                     dc->currentcurve->curveto(bp1[1], bp1[2], bp1[3]);
1187                 }
1188                 dc->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]);
1189                 for (Geom::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1190                     dc->currentcurve->curveto(bp2[2], bp2[1], bp2[0]);
1191                 }
1192                 // FIXME: dc->segments is always NULL at this point??
1193                 if (!dc->segments) { // first segment
1194                     add_cap(dc->currentcurve, b2[0], b1[0], dc->cap_rounding);
1195                 }
1196                 dc->currentcurve->closepath();
1197                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1198             }
1200             /* Current calligraphic */
1201             for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1202                 dc->cal1->curveto(bp1[1], bp1[2], bp1[3]);
1203             }
1204             for (Geom::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1205                 dc->cal2->curveto(bp2[1], bp2[2], bp2[3]);
1206             }
1207         } else {
1208             /* fixme: ??? */
1209 #ifdef DYNA_DRAW_VERBOSE
1210             g_print("[fit_and_split] failed to fit-cubic.\n");
1211 #endif
1212             draw_temporary_box(dc);
1214             for (gint i = 1; i < dc->npoints; i++) {
1215                 dc->cal1->lineto(dc->point1[i]);
1216             }
1217             for (gint i = 1; i < dc->npoints; i++) {
1218                 dc->cal2->lineto(dc->point2[i]);
1219             }
1220         }
1222         /* Fit and draw and copy last point */
1223 #ifdef DYNA_DRAW_VERBOSE
1224         g_print("[%d]Yup\n", dc->npoints);
1225 #endif
1226         if (!release) {
1227             g_assert(!dc->currentcurve->is_empty());
1229             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(desktop),
1230                                                    SP_TYPE_CANVAS_BPATH,
1231                                                    NULL);
1232             SPCurve *curve = dc->currentcurve->copy();
1233             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1234             curve->unref();
1236             guint32 fillColor = sp_desktop_get_color_tool (desktop, "/tools/calligraphic", true);
1237             //guint32 strokeColor = sp_desktop_get_color_tool (desktop, "/tools/calligraphic", false);
1238             double opacity = sp_desktop_get_master_opacity_tool (desktop, "/tools/calligraphic");
1239             double fillOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/calligraphic", true);
1240             //double strokeOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/calligraphic", false);
1241             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1242             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1243             //sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), ((strokeColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*strokeOpacity)), 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1244             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1245             /* fixme: Cannot we cascade it to root more clearly? */
1246             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), desktop);
1248             dc->segments = g_slist_prepend(dc->segments, cbp);
1249         }
1251         dc->point1[0] = dc->point1[dc->npoints - 1];
1252         dc->point2[0] = dc->point2[dc->npoints - 1];
1253         dc->npoints = 1;
1254     } else {
1255         draw_temporary_box(dc);
1256     }
1259 static void
1260 draw_temporary_box(SPDynaDrawContext *dc)
1262     dc->currentcurve->reset();
1264     dc->currentcurve->moveto(dc->point2[dc->npoints-1]);
1265     for (gint i = dc->npoints-2; i >= 0; i--) {
1266         dc->currentcurve->lineto(dc->point2[i]);
1267     }
1268     for (gint i = 0; i < dc->npoints; i++) {
1269         dc->currentcurve->lineto(dc->point1[i]);
1270     }
1272     if (dc->npoints >= 2) {
1273         add_cap(dc->currentcurve, dc->point1[dc->npoints-1], dc->point2[dc->npoints-1], dc->cap_rounding);
1274     }
1276     dc->currentcurve->closepath();
1277     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1280 /*
1281   Local Variables:
1282   mode:c++
1283   c-file-style:"stroustrup"
1284   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1285   indent-tabs-mode:nil
1286   fill-column:99
1287   End:
1288 */
1289 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :