Code

- The snap-delay mechanism should now be more robust. From now on, it must be turned...
[inkscape.git] / src / dyna-draw-context.cpp
1 #define __SP_DYNA_DRAW_CONTEXT_C__
3 /*
4  * Handwriting-like drawing mode
5  *
6  * Authors:
7  *   Mitsuru Oka <oka326@parkcity.ne.jp>
8  *   Lauris Kaplinski <lauris@kaplinski.com>
9  *   bulia byak <buliabyak@users.sf.net>
10  *   MenTaLguY <mental@rydia.net>
11  *
12  * The original dynadraw code:
13  *   Paul Haeberli <paul@sgi.com>
14  *
15  * Copyright (C) 1998 The Free Software Foundation
16  * Copyright (C) 1999-2005 authors
17  * Copyright (C) 2001-2002 Ximian, Inc.
18  * Copyright (C) 2005-2007 bulia byak
19  * Copyright (C) 2006 MenTaLguY
20  *
21  * Released under GNU GPL, read the file 'COPYING' for more information
22  */
24 #define noDYNA_DRAW_VERBOSE
26 #include "config.h"
28 #include <gtk/gtk.h>
29 #include <gdk/gdkkeysyms.h>
30 #include <glibmm/i18n.h>
31 #include <string>
32 #include <cstring>
33 #include <numeric>
35 #include "svg/svg.h"
36 #include "display/canvas-bpath.h"
37 #include <2geom/isnan.h>
38 #include <2geom/pathvector.h>
39 #include <2geom/bezier-utils.h>
40 #include "display/curve.h"
41 #include <glib/gmem.h>
42 #include "macros.h"
43 #include "document.h"
44 #include "selection.h"
45 #include "desktop.h"
46 #include "desktop-events.h"
47 #include "desktop-handles.h"
48 #include "desktop-affine.h"
49 #include "desktop-style.h"
50 #include "message-context.h"
51 #include "preferences.h"
52 #include "pixmaps/cursor-calligraphy.xpm"
53 #include "xml/repr.h"
54 #include "context-fns.h"
55 #include "sp-item.h"
56 #include "inkscape.h"
57 #include "color.h"
58 #include "splivarot.h"
59 #include "sp-item-group.h"
60 #include "sp-shape.h"
61 #include "sp-path.h"
62 #include "sp-text.h"
63 #include "display/canvas-bpath.h"
64 #include "display/canvas-arena.h"
65 #include "livarot/Shape.h"
67 #include "dyna-draw-context.h"
69 #define DDC_RED_RGBA 0xff0000ff
71 #define TOLERANCE_CALLIGRAPHIC 0.1
73 #define DYNA_EPSILON 0.5e-6
74 #define DYNA_EPSILON_START 0.5e-2
75 #define DYNA_VEL_START 1e-5
77 #define DYNA_MIN_WIDTH 1.0e-6
79 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
80 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
81 static void sp_dyna_draw_context_dispose(GObject *object);
83 static void sp_dyna_draw_context_setup(SPEventContext *ec);
84 static void sp_dyna_draw_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *value);
85 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
87 static void clear_current(SPDynaDrawContext *dc);
88 static void set_to_accumulated(SPDynaDrawContext *dc, bool unionize);
89 static void add_cap(SPCurve *curve, Geom::Point const &from, Geom::Point const &to, double rounding);
90 static bool accumulate_calligraphic(SPDynaDrawContext *dc);
92 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
94 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, Geom::Point p);
95 static Geom::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, Geom::Point v);
96 static Geom::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, Geom::Point n);
97 static void draw_temporary_box(SPDynaDrawContext *dc);
100 static SPEventContextClass *dd_parent_class = 0;
102 GType sp_dyna_draw_context_get_type(void)
104     static GType type = 0;
105     if (!type) {
106         GTypeInfo info = {
107             sizeof(SPDynaDrawContextClass),
108             0, // base_init
109             0, // base_finalize
110             (GClassInitFunc)sp_dyna_draw_context_class_init,
111             0, // class_finalize
112             0, // class_data
113             sizeof(SPDynaDrawContext),
114             0, // n_preallocs
115             (GInstanceInitFunc)sp_dyna_draw_context_init,
116             0 // value_table
117         };
118         type = g_type_register_static(SP_TYPE_COMMON_CONTEXT, "SPDynaDrawContext", &info, static_cast<GTypeFlags>(0));
119     }
120     return type;
123 static void
124 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
126     GObjectClass *object_class = (GObjectClass *) klass;
127     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
129     dd_parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
131     object_class->dispose = sp_dyna_draw_context_dispose;
133     event_context_class->setup = sp_dyna_draw_context_setup;
134     event_context_class->set = sp_dyna_draw_context_set;
135     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
138 static void
139 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
141     ddc->cursor_shape = cursor_calligraphy_xpm;
142     ddc->hot_x = 4;
143     ddc->hot_y = 4;
145     ddc->vel_thin = 0.1;
146     ddc->flatness = 0.9;
147     ddc->cap_rounding = 0.0;
149     ddc->abs_width = false;
150     ddc->keep_selected = true;
152     ddc->hatch_spacing = 0;
153     ddc->hatch_spacing_step = 0;
154     new (&ddc->hatch_pointer_past) std::list<double>();
155     new (&ddc->hatch_nearest_past) std::list<double>();
156     new (&ddc->inertia_vectors) std::list<Geom::Point>();
157     new (&ddc->hatch_vectors) std::list<Geom::Point>();
158     ddc->hatch_last_nearest = Geom::Point(0,0);
159     ddc->hatch_last_pointer = Geom::Point(0,0);
160     ddc->hatch_escaped = false;
161     ddc->hatch_area = NULL;
162     ddc->hatch_item = NULL;
163     ddc->hatch_livarot_path = NULL;
165     ddc->trace_bg = false;
166     ddc->just_started_drawing = false;
169 static void
170 sp_dyna_draw_context_dispose(GObject *object)
172     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
174     if (ddc->hatch_area) {
175         gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
176         ddc->hatch_area = NULL;
177     }
180     G_OBJECT_CLASS(dd_parent_class)->dispose(object);
182     ddc->hatch_pointer_past.~list();
183     ddc->hatch_nearest_past.~list();
184     ddc->inertia_vectors.~list();
185     ddc->hatch_vectors.~list();
188 static void
189 sp_dyna_draw_context_setup(SPEventContext *ec)
191     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
193     if (((SPEventContextClass *) dd_parent_class)->setup)
194         ((SPEventContextClass *) dd_parent_class)->setup(ec);
196     ddc->accumulated = new SPCurve();
197     ddc->currentcurve = new SPCurve();
199     ddc->cal1 = new SPCurve();
200     ddc->cal2 = new SPCurve();
202     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
203     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
204     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
205     /* fixme: Cannot we cascade it to root more clearly? */
206     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
208     {
209         /* 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) */
210         SPCurve *c = new SPCurve();
211         const double C1 = 0.552;
212         c->moveto(-1,0);
213         c->curveto(-1, C1, -C1, 1, 0, 1 );
214         c->curveto(C1, 1, 1, C1, 1, 0 );
215         c->curveto(1, -C1, C1, -1, 0, -1 );
216         c->curveto(-C1, -1, -1, -C1, -1, 0 );
217         c->closepath();
218         ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
219         c->unref();
220         sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
221         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
222         sp_canvas_item_hide(ddc->hatch_area);
223     }
225     sp_event_context_read(ec, "mass");
226     sp_event_context_read(ec, "wiggle");
227     sp_event_context_read(ec, "angle");
228     sp_event_context_read(ec, "width");
229     sp_event_context_read(ec, "thinning");
230     sp_event_context_read(ec, "tremor");
231     sp_event_context_read(ec, "flatness");
232     sp_event_context_read(ec, "tracebackground");
233     sp_event_context_read(ec, "usepressure");
234     sp_event_context_read(ec, "usetilt");
235     sp_event_context_read(ec, "abs_width");
236     sp_event_context_read(ec, "keep_selected");
237     sp_event_context_read(ec, "cap_rounding");
239     ddc->is_drawing = false;
240     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
242     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
243     if (prefs->getBool("/tools/calligraphic/selcue")) {
244         ec->enableSelectionCue();
245     }
248 static void
249 sp_dyna_draw_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val)
251     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
252     Glib::ustring path = val->getEntryName();
254     if (path == "tracebackground") {
255         ddc->trace_bg = val->getBool();
256     } else if (path == "keep_selected") {
257         ddc->keep_selected = val->getBool();
258     } else {
259         //pass on up to parent class to handle common attributes.
260         if ( dd_parent_class->set ) {
261             dd_parent_class->set(ec, val);
262         }
263     }
265     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
268 static double
269 flerp(double f0, double f1, double p)
271     return f0 + ( f1 - f0 ) * p;
274 /* Get normalized point */
275 static Geom::Point
276 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, Geom::Point v)
278     Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
279     double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
280     return Geom::Point(( v[Geom::X] - drect.min()[Geom::X] ) / max,  ( v[Geom::Y] - drect.min()[Geom::Y] ) / max);
283 /* Get view point */
284 static Geom::Point
285 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, Geom::Point n)
287     Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
288     double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
289     return Geom::Point(n[Geom::X] * max + drect.min()[Geom::X], n[Geom::Y] * max + drect.min()[Geom::Y]);
292 static void
293 sp_dyna_draw_reset(SPDynaDrawContext *dc, Geom::Point p)
295     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
296     dc->vel = Geom::Point(0,0);
297     dc->vel_max = 0;
298     dc->acc = Geom::Point(0,0);
299     dc->ang = Geom::Point(0,0);
300     dc->del = Geom::Point(0,0);
303 static void
304 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
306     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
307         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
308     else
309         dc->pressure = DDC_DEFAULT_PRESSURE;
311     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
312         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
313     else
314         dc->xtilt = DDC_DEFAULT_TILT;
316     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
317         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
318     else
319         dc->ytilt = DDC_DEFAULT_TILT;
323 static gboolean
324 sp_dyna_draw_apply(SPDynaDrawContext *dc, Geom::Point p)
326     Geom::Point n = sp_dyna_draw_get_npoint(dc, p);
328     /* Calculate mass and drag */
329     double const mass = flerp(1.0, 160.0, dc->mass);
330     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
332     /* Calculate force and acceleration */
333     Geom::Point force = n - dc->cur;
335     // If force is below the absolute threshold DYNA_EPSILON,
336     // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
337     // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
338     // discard this move.
339     // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
340     // especially bothersome at the start of the stroke where we don't yet have the inertia to
341     // smooth them out.
342     if ( Geom::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && Geom::L2(force) < DYNA_EPSILON_START)) {
343         return FALSE;
344     }
346     dc->acc = force / mass;
348     /* Calculate new velocity */
349     dc->vel += dc->acc;
351     if (Geom::L2(dc->vel) > dc->vel_max)
352         dc->vel_max = Geom::L2(dc->vel);
354     /* Calculate angle of drawing tool */
356     double a1;
357     if (dc->usetilt) {
358         // 1a. calculate nib angle from input device tilt:
359         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
361         if (length > 0) {
362             Geom::Point ang1 = Geom::Point(dc->ytilt/length, dc->xtilt/length);
363             a1 = atan2(ang1);
364         }
365         else
366             a1 = 0.0;
367     }
368     else {
369         // 1b. fixed dc->angle (absolutely flat nib):
370         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
371         Geom::Point ang1 = Geom::Point(-sin(radians),  cos(radians));
372         a1 = atan2(ang1);
373     }
375     // 2. perpendicular to dc->vel (absolutely non-flat nib):
376     gdouble const mag_vel = Geom::L2(dc->vel);
377     if ( mag_vel < DYNA_EPSILON ) {
378         return FALSE;
379     }
380     Geom::Point ang2 = Geom::rot90(dc->vel) / mag_vel;
382     // 3. Average them using flatness parameter:
383     // calculate angles
384     double a2 = atan2(ang2);
385     // flip a2 to force it to be in the same half-circle as a1
386     bool flipped = false;
387     if (fabs (a2-a1) > 0.5*M_PI) {
388         a2 += M_PI;
389         flipped = true;
390     }
391     // normalize a2
392     if (a2 > M_PI)
393         a2 -= 2*M_PI;
394     if (a2 < -M_PI)
395         a2 += 2*M_PI;
396     // find the flatness-weighted bisector angle, unflip if a2 was flipped
397     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
398     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
400     // Try to detect a sudden flip when the new angle differs too much from the previous for the
401     // current velocity; in that case discard this move
402     double angle_delta = Geom::L2(Geom::Point (cos (new_ang), sin (new_ang)) - dc->ang);
403     if ( angle_delta / Geom::L2(dc->vel) > 4000 ) {
404         return FALSE;
405     }
407     // convert to point
408     dc->ang = Geom::Point (cos (new_ang), sin (new_ang));
410 //    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);
412     /* Apply drag */
413     dc->vel *= 1.0 - drag;
415     /* Update position */
416     dc->last = dc->cur;
417     dc->cur += dc->vel;
419     return TRUE;
422 static void
423 sp_dyna_draw_brush(SPDynaDrawContext *dc)
425     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
427     // How much velocity thins strokestyle
428     double vel_thin = flerp (0, 160, dc->vel_thin);
430     // Influence of pressure on thickness
431     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
433     // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
434     // drag)
435     Geom::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
436     Geom::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush);
438     double trace_thick = 1;
439     if (dc->trace_bg) {
440         // pick single pixel
441         NRPixBlock pb;
442         int x = (int) floor(brush_w[Geom::X]);
443         int y = (int) floor(brush_w[Geom::Y]);
444         nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
445         sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
446         const unsigned char *s = NR_PIXBLOCK_PX(&pb);
447         double R = s[0] / 255.0;
448         double G = s[1] / 255.0;
449         double B = s[2] / 255.0;
450         double A = s[3] / 255.0;
451         double max = MAX (MAX (R, G), B);
452         double min = MIN (MIN (R, G), B);
453         double L = A * (max + min)/2 + (1 - A); // blend with white bg
454         trace_thick = 1 - L;
455         //g_print ("L %g thick %g\n", L, trace_thick);
456     }
458     double width = (pressure_thick * trace_thick - vel_thin * Geom::L2(dc->vel)) * dc->width;
460     double tremble_left = 0, tremble_right = 0;
461     if (dc->tremor > 0) {
462         // obtain two normally distributed random variables, using polar Box-Muller transform
463         double x1, x2, w, y1, y2;
464         do {
465             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
466             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
467             w = x1 * x1 + x2 * x2;
468         } while ( w >= 1.0 );
469         w = sqrt( (-2.0 * log( w ) ) / w );
470         y1 = x1 * w;
471         y2 = x2 * w;
473         // deflect both left and right edges randomly and independently, so that:
474         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
475         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
476         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
477         // comparatively smooth and slow ones excessively jittery
478         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
479         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
480     }
482     if ( width < 0.02 * dc->width ) {
483         width = 0.02 * dc->width;
484     }
486     double dezoomify_factor = 0.05 * 1000;
487     if (!dc->abs_width) {
488         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
489     }
491     Geom::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
492     Geom::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
494     dc->point1[dc->npoints] = brush + del_left;
495     dc->point2[dc->npoints] = brush - del_right;
497     dc->del = 0.5*(del_left + del_right);
499     dc->npoints++;
502 void
503 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
505     desktop->setToolboxAdjustmentValue (id, value);
508 static void
509 calligraphic_cancel(SPDynaDrawContext *dc)
511     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
512     dc->dragging = FALSE;
513     dc->is_drawing = false;
514     sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
515             /* Remove all temporary line segments */
516             while (dc->segments) {
517                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
518                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
519             }
520             /* reset accumulated curve */
521             dc->accumulated->reset();
522             clear_current(dc);
523             if (dc->repr) {
524                 dc->repr = NULL;
525             }
529 gint
530 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
531                                   GdkEvent *event)
533     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
534     SPDesktop *desktop = event_context->desktop;
536     gint ret = FALSE;
538     switch (event->type) {
539         case GDK_BUTTON_PRESS:
540             if (event->button.button == 1 && !event_context->space_panning) {
542                 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
544                 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
545                     return TRUE;
546                 }
548                 dc->accumulated->reset();
549                 if (dc->repr) {
550                     dc->repr = NULL;
551                 }
553                 /* initialize first point */
554                 dc->npoints = 0;
556                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
557                                     ( GDK_KEY_PRESS_MASK |
558                                       GDK_BUTTON_RELEASE_MASK |
559                                       GDK_POINTER_MOTION_MASK |
560                                       GDK_BUTTON_PRESS_MASK ),
561                                     NULL,
562                                     event->button.time);
564                 ret = TRUE;
566                 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
567                 dc->is_drawing = true;
568                 dc->just_started_drawing = true;
569             }
570             break;
571         case GDK_MOTION_NOTIFY:
572         {
573             Geom::Point const motion_w(event->motion.x,
574                                      event->motion.y);
575             Geom::Point motion_dt(desktop->w2d(motion_w));
576             sp_dyna_draw_extinput(dc, event);
578             dc->_message_context->clear();
580             // for hatching:
581             double hatch_dist = 0;
582             Geom::Point hatch_unit_vector(0,0);
583             Geom::Point nearest(0,0);
584             Geom::Point pointer(0,0);
585             Geom::Matrix motion_to_curve(Geom::identity());
587             if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
589                 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
590                 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
591                     // One item selected, and it's a path;
592                     // let's try to track it as a guide
594                     if (selected != dc->hatch_item) {
595                         dc->hatch_item = selected;
596                         if (dc->hatch_livarot_path)
597                             delete dc->hatch_livarot_path;
598                         dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
599                         dc->hatch_livarot_path->ConvertWithBackData(0.01);
600                     }
602                     // calculate pointer point in the guide item's coords
603                     motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
604                     pointer = motion_dt * motion_to_curve;
606                     // calculate the nearest point on the guide path
607                     boost::optional<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
608                     nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
611                     // distance from pointer to nearest
612                     hatch_dist = Geom::L2(pointer - nearest);
613                     // unit-length vector
614                     hatch_unit_vector = (pointer - nearest)/hatch_dist;
616                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
617                 } else {
618                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
619                 }
620             }
622             if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
623                 dc->dragging = TRUE;
625                 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
627 #define HATCH_VECTOR_ELEMENTS 12
628 #define INERTIA_ELEMENTS 36
629 #define SPEED_ELEMENTS 12
630 #define SPEED_MIN 0.3
631 #define SPEED_NORMAL 0.3
633                     // speed is the movement of the nearest point along the guide path, divided by
634                     // the movement of the pointer at the same period; it is averaged for the last
635                     // SPEED_ELEMENTS motion events.  Normally, as you track the guide path, speed
636                     // is about 1, i.e. the nearest point on the path is moved by about the same
637                     // distance as the pointer. If the speed starts to decrease, we are losing
638                     // contact with the guide; if it drops below SPEED_MIN, we are on our own and
639                     // not attracted to guide anymore. Most often this happens when you have
640                     // tracked to the end of a guide calligraphic stroke and keep moving
641                     // further. We try to handle this situation gracefully: not stick with the
642                     // guide forever but let go of it smoothly and without sharp jerks (non-zero
643                     // mass recommended; with zero mass, jerks are still quite noticeable).
645                     double speed = 1;
646                     if (Geom::L2(dc->hatch_last_nearest) != 0) {
647                         // the distance nearest moved since the last motion event
648                         double nearest_moved = Geom::L2(nearest - dc->hatch_last_nearest);
649                         // the distance pointer moved since the last motion event
650                         double pointer_moved = Geom::L2(pointer - dc->hatch_last_pointer);
651                         // store them in stacks limited to SPEED_ELEMENTS
652                         dc->hatch_nearest_past.push_front(nearest_moved);
653                         if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
654                             dc->hatch_nearest_past.pop_back();
655                         dc->hatch_pointer_past.push_front(pointer_moved);
656                         if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
657                             dc->hatch_pointer_past.pop_back();
659                         // If the stacks are full,
660                         if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
661                             // calculate the sums of all stored movements
662                             double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
663                             double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
664                             // and divide to get the speed
665                             speed = nearest_sum/pointer_sum;
666                             //g_print ("nearest sum %g  pointer_sum %g  speed %g\n", nearest_sum, pointer_sum, speed);
667                         }
668                     }
670                     if (   dc->hatch_escaped  // already escaped, do not reattach
671                         || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
672                         || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
673                         ) {
674                         // We are NOT attracted to the guide!
676                         //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);
678                         // Remember hatch_escaped so we don't get
679                         // attracted again until the end of this stroke
680                         dc->hatch_escaped = true;
682                         if (dc->inertia_vectors.size() >= INERTIA_ELEMENTS/2) { // move by inertia
683                             Geom::Point moved_past_escape = motion_dt - dc->inertia_vectors.front();
684                             Geom::Point inertia = 
685                                 dc->inertia_vectors.front() - dc->inertia_vectors.back();
687                             double dot = Geom::dot (moved_past_escape, inertia);
688                             dot /= Geom::L2(moved_past_escape) * Geom::L2(inertia);
690                             if (dot > 0) { // mouse is still moving in approx the same direction
691                                 Geom::Point should_have_moved = 
692                                     (inertia) * (1/Geom::L2(inertia)) * Geom::L2(moved_past_escape);
693                                 motion_dt = dc->inertia_vectors.front() + should_have_moved;
694                             }
695                         }
697                     } else {
699                         // Calculate angle cosine of this vector-to-guide and all past vectors
700                         // summed, to detect if we accidentally flipped to the other side of the
701                         // guide
702                         Geom::Point hatch_vector_accumulated = std::accumulate 
703                             (dc->hatch_vectors.begin(), dc->hatch_vectors.end(), Geom::Point(0,0));
704                         double dot = Geom::dot (pointer - nearest, hatch_vector_accumulated);
705                         dot /= Geom::L2(pointer - nearest) * Geom::L2(hatch_vector_accumulated);
707                         if (dc->hatch_spacing != 0) { // spacing was already set
708                             double target;
709                             if (speed > SPEED_NORMAL) {
710                                 // all ok, strictly obey the spacing
711                                 target = dc->hatch_spacing;
712                             } else {
713                                 // looks like we're starting to lose speed,
714                                 // so _gradually_ let go attraction to prevent jerks
715                                 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;
716                             }
717                             if (!IS_NAN(dot) && dot < -0.5) {// flip
718                                 target = -target;
719                             }
721                             // This is the track pointer that we will use instead of the real one
722                             Geom::Point new_pointer = nearest + target * hatch_unit_vector;
724                             // some limited feedback: allow persistent pulling to slightly change
725                             // the spacing
726                             dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
728                             // return it to the desktop coords
729                             motion_dt = new_pointer * motion_to_curve.inverse();
731                             if (speed >= SPEED_NORMAL) {
732                                 dc->inertia_vectors.push_front(motion_dt);
733                                 if (dc->inertia_vectors.size() > INERTIA_ELEMENTS)
734                                     dc->inertia_vectors.pop_back();
735                             }
737                         } else {
738                             // this is the first motion event, set the dist
739                             dc->hatch_spacing = hatch_dist;
740                         }
742                         // remember last points
743                         dc->hatch_last_pointer = pointer;
744                         dc->hatch_last_nearest = nearest;
746                         dc->hatch_vectors.push_front(pointer - nearest);
747                         if (dc->hatch_vectors.size() > HATCH_VECTOR_ELEMENTS)
748                             dc->hatch_vectors.pop_back();
749                     }
751                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
753                 } else {
754                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
755                 }
757                 if (dc->just_started_drawing) {
758                     dc->just_started_drawing = false;
759                     sp_dyna_draw_reset(dc, motion_dt);
760                 }
762                 if (!sp_dyna_draw_apply(dc, motion_dt)) {
763                     ret = TRUE;
764                     break;
765                 }
767                 if ( dc->cur != dc->last ) {
768                     sp_dyna_draw_brush(dc);
769                     g_assert( dc->npoints > 0 );
770                     fit_and_split(dc, FALSE);
771                 }
772                 ret = TRUE;
773             }
775             // Draw the hatching circle if necessary
776             if (event->motion.state & GDK_CONTROL_MASK) {
777                 if (dc->hatch_spacing == 0 && hatch_dist != 0) {
778                     // Haven't set spacing yet: gray, center free, update radius live
779                     Geom::Point c = desktop->w2d(motion_w);
780                     Geom::Matrix const sm (Geom::Scale(hatch_dist, hatch_dist) * Geom::Translate(c));
781                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
782                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
783                     sp_canvas_item_show(dc->hatch_area);
784                 } else if (dc->dragging && !dc->hatch_escaped) {
785                     // Tracking: green, center snapped, fixed radius
786                     Geom::Point c = motion_dt;
787                     Geom::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
788                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
789                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
790                     sp_canvas_item_show(dc->hatch_area);
791                 } else if (dc->dragging && dc->hatch_escaped) {
792                     // Tracking escaped: red, center free, fixed radius
793                     Geom::Point c = motion_dt;
794                     Geom::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
796                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
797                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
798                     sp_canvas_item_show(dc->hatch_area);
799                 } else {
800                     // Not drawing but spacing set: gray, center snapped, fixed radius
801                     Geom::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
802                     if (!IS_NAN(c[Geom::X]) && !IS_NAN(c[Geom::Y])) {
803                         Geom::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
804                         sp_canvas_item_affine_absolute(dc->hatch_area, sm);
805                         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
806                         sp_canvas_item_show(dc->hatch_area);
807                     }
808                 }
809             } else {
810                 sp_canvas_item_hide(dc->hatch_area);
811             }
812         }
813         break;
816     case GDK_BUTTON_RELEASE:
817     {
818         Geom::Point const motion_w(event->button.x, event->button.y);
819         Geom::Point const motion_dt(desktop->w2d(motion_w));
821         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
822         sp_canvas_end_forced_full_redraws(desktop->canvas);
823         dc->is_drawing = false;
825         if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
826             dc->dragging = FALSE;
828             sp_dyna_draw_apply(dc, motion_dt);
830             /* Remove all temporary line segments */
831             while (dc->segments) {
832                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
833                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
834             }
836             /* Create object */
837             fit_and_split(dc, TRUE);
838             if (accumulate_calligraphic(dc))
839                 set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK); // performs document_done
840             else
841                 g_warning ("Failed to create path: invalid data in dc->cal1 or dc->cal2");
843             /* reset accumulated curve */
844             dc->accumulated->reset();
846             clear_current(dc);
847             if (dc->repr) {
848                 dc->repr = NULL;
849             }
851             if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
852             if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
853             if (!dc->inertia_vectors.empty()) dc->inertia_vectors.clear();
854             if (!dc->hatch_vectors.empty()) dc->hatch_vectors.clear();
855             dc->hatch_last_nearest = Geom::Point(0,0);
856             dc->hatch_last_pointer = Geom::Point(0,0);
857             dc->hatch_escaped = false;
858             dc->hatch_item = NULL;
859             dc->hatch_livarot_path = NULL;
860             dc->just_started_drawing = false;
862             if (dc->hatch_spacing != 0 && !dc->keep_selected) {
863                 // we do not select the newly drawn path, so increase spacing by step
864                 if (dc->hatch_spacing_step == 0) {
865                     dc->hatch_spacing_step = dc->hatch_spacing;
866                 }
867                 dc->hatch_spacing += dc->hatch_spacing_step;
868             }
870             dc->_message_context->clear();
871             ret = TRUE;
872         }
873         break;
874     }
876     case GDK_KEY_PRESS:
877         switch (get_group0_keyval (&event->key)) {
878         case GDK_Up:
879         case GDK_KP_Up:
880             if (!MOD__CTRL_ONLY) {
881                 dc->angle += 5.0;
882                 if (dc->angle > 90.0)
883                     dc->angle = 90.0;
884                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
885                 ret = TRUE;
886             }
887             break;
888         case GDK_Down:
889         case GDK_KP_Down:
890             if (!MOD__CTRL_ONLY) {
891                 dc->angle -= 5.0;
892                 if (dc->angle < -90.0)
893                     dc->angle = -90.0;
894                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
895                 ret = TRUE;
896             }
897             break;
898         case GDK_Right:
899         case GDK_KP_Right:
900             if (!MOD__CTRL_ONLY) {
901                 dc->width += 0.01;
902                 if (dc->width > 1.0)
903                     dc->width = 1.0;
904                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
905                 ret = TRUE;
906             }
907             break;
908         case GDK_Left:
909         case GDK_KP_Left:
910             if (!MOD__CTRL_ONLY) {
911                 dc->width -= 0.01;
912                 if (dc->width < 0.01)
913                     dc->width = 0.01;
914                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
915                 ret = TRUE;
916             }
917             break;
918         case GDK_Home:
919         case GDK_KP_Home:
920             dc->width = 0.01;
921             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
922             ret = TRUE;
923             break;
924         case GDK_End:
925         case GDK_KP_End:
926             dc->width = 1.0;
927             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
928             ret = TRUE;
929             break;
930         case GDK_x:
931         case GDK_X:
932             if (MOD__ALT_ONLY) {
933                 desktop->setToolboxFocusTo ("altx-calligraphy");
934                 ret = TRUE;
935             }
936             break;
937         case GDK_Escape:
938             if (dc->is_drawing) {
939                 // if drawing, cancel, otherwise pass it up for deselecting
940                 calligraphic_cancel (dc);
941                 ret = TRUE;
942             }
943             break;
944         case GDK_z:
945         case GDK_Z:
946             if (MOD__CTRL_ONLY && dc->is_drawing) {
947                 // if drawing, cancel, otherwise pass it up for undo
948                 calligraphic_cancel (dc);
949                 ret = TRUE;
950             }
951             break;
952         default:
953             break;
954         }
955         break;
957     case GDK_KEY_RELEASE:
958         switch (get_group0_keyval(&event->key)) {
959             case GDK_Control_L:
960             case GDK_Control_R:
961                 dc->_message_context->clear();
962                 dc->hatch_spacing = 0;
963                 dc->hatch_spacing_step = 0;
964                 break;
965             default:
966                 break;
967         }
969     default:
970         break;
971     }
973     if (!ret) {
974         if (((SPEventContextClass *) dd_parent_class)->root_handler) {
975             ret = ((SPEventContextClass *) dd_parent_class)->root_handler(event_context, event);
976         }
977     }
979     return ret;
983 static void
984 clear_current(SPDynaDrawContext *dc)
986     /* reset bpath */
987     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
988     /* reset curve */
989     dc->currentcurve->reset();
990     dc->cal1->reset();
991     dc->cal2->reset();
992     /* reset points */
993     dc->npoints = 0;
996 static void
997 set_to_accumulated(SPDynaDrawContext *dc, bool unionize)
999     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1001     if (!dc->accumulated->is_empty()) {
1002         if (!dc->repr) {
1003             /* Create object */
1004             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1005             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1007             /* Set style */
1008             sp_desktop_apply_style_tool (desktop, repr, "/tools/calligraphic", false);
1010             dc->repr = repr;
1012             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
1013             Inkscape::GC::release(dc->repr);
1014             item->transform = sp_item_i2doc_affine(SP_ITEM(desktop->currentLayer())).inverse();
1015             item->updateRepr();
1016         }
1017         Geom::PathVector pathv = dc->accumulated->get_pathvector() * sp_desktop_dt2doc_affine(desktop);
1018         gchar *str = sp_svg_write_path(pathv);
1019         g_assert( str != NULL );
1020         dc->repr->setAttribute("d", str);
1021         g_free(str);
1023         if (unionize) {
1024             sp_desktop_selection(desktop)->add(dc->repr);
1025             sp_selected_path_union_skip_undo(desktop);
1026         } else {
1027             if (dc->keep_selected) {
1028                 sp_desktop_selection(desktop)->set(dc->repr);
1029             }
1030         }
1032     } else {
1033         if (dc->repr) {
1034             sp_repr_unparent(dc->repr);
1035         }
1036         dc->repr = NULL;
1037     }
1039     sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC,
1040                      _("Draw calligraphic stroke"));
1043 static void
1044 add_cap(SPCurve *curve,
1045         Geom::Point const &from,
1046         Geom::Point const &to,
1047         double rounding)
1049     if (Geom::L2( to - from ) > DYNA_EPSILON) {
1050         Geom::Point vel = rounding * Geom::rot90( to - from ) / sqrt(2.0);
1051         double mag = Geom::L2(vel);
1053         Geom::Point v = mag * Geom::rot90( to - from ) / Geom::L2( to - from );
1054         curve->curveto(from + v, to + v, to);
1055     }
1058 static bool
1059 accumulate_calligraphic(SPDynaDrawContext *dc)
1061         if (
1062             dc->cal1->is_empty() ||
1063             dc->cal2->is_empty() ||
1064             (dc->cal1->get_segment_count() <= 0) ||
1065             dc->cal1->first_path()->closed()
1066             ) {
1067             dc->cal1->reset();
1068             dc->cal2->reset();
1069             return false; // failure
1070         }
1072         SPCurve *rev_cal2 = dc->cal2->create_reverse();
1073         if (
1074             (rev_cal2->get_segment_count() <= 0) ||
1075             rev_cal2->first_path()->closed()
1076             ) {
1077             rev_cal2->unref();
1078             dc->cal1->reset();
1079             dc->cal2->reset();
1080             return false; // failure
1081         }
1083         Geom::CubicBezier const * dc_cal1_firstseg  = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->first_segment() );
1084         Geom::CubicBezier const * rev_cal2_firstseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->first_segment() );
1085         Geom::CubicBezier const * dc_cal1_lastseg   = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->last_segment() );
1086         Geom::CubicBezier const * rev_cal2_lastseg  = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->last_segment() );
1088         if (
1089             !dc_cal1_firstseg ||
1090             !rev_cal2_firstseg ||
1091             !dc_cal1_lastseg ||
1092             !rev_cal2_lastseg
1093             ) {
1094             rev_cal2->unref();
1095             dc->cal1->reset();
1096             dc->cal2->reset();
1097             return false; // failure
1098         }
1100         dc->accumulated->reset(); /*  Is this required ?? */
1102         dc->accumulated->append(dc->cal1, false);
1104         add_cap(dc->accumulated, (*dc_cal1_lastseg)[3], (*rev_cal2_firstseg)[0], dc->cap_rounding);
1106         dc->accumulated->append(rev_cal2, true);
1108         add_cap(dc->accumulated, (*rev_cal2_lastseg)[3], (*dc_cal1_firstseg)[0], dc->cap_rounding);
1110         dc->accumulated->closepath();
1112         rev_cal2->unref();
1114         dc->cal1->reset();
1115         dc->cal2->reset();
1117         return true; // success
1120 static double square(double const x)
1122     return x * x;
1125 static void
1126 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1128     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1130     double const tolerance_sq = square( desktop->w2d().descrim() * TOLERANCE_CALLIGRAPHIC );
1132 #ifdef DYNA_DRAW_VERBOSE
1133     g_print("[F&S:R=%c]", release?'T':'F');
1134 #endif
1136     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1137         return; // just clicked
1139     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1140 #define BEZIER_SIZE       4
1141 #define BEZIER_MAX_BEZIERS  8
1142 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1144 #ifdef DYNA_DRAW_VERBOSE
1145         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1146                 dc->npoints, release ? "TRUE" : "FALSE");
1147 #endif
1149         /* Current calligraphic */
1150         if ( dc->cal1->is_empty() || dc->cal2->is_empty() ) {
1151             /* dc->npoints > 0 */
1152             /* g_print("calligraphics(1|2) reset\n"); */
1153             dc->cal1->reset();
1154             dc->cal2->reset();
1156             dc->cal1->moveto(dc->point1[0]);
1157             dc->cal2->moveto(dc->point2[0]);
1158         }
1160         Geom::Point b1[BEZIER_MAX_LENGTH];
1161         gint const nb1 = Geom::bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1162                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1163         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1165         Geom::Point b2[BEZIER_MAX_LENGTH];
1166         gint const nb2 = Geom::bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1167                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1168         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1170         if ( nb1 != -1 && nb2 != -1 ) {
1171             /* Fit and draw and reset state */
1172 #ifdef DYNA_DRAW_VERBOSE
1173             g_print("nb1:%d nb2:%d\n", nb1, nb2);
1174 #endif
1175             /* CanvasShape */
1176             if (! release) {
1177                 dc->currentcurve->reset();
1178                 dc->currentcurve->moveto(b1[0]);
1179                 for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1180                     dc->currentcurve->curveto(bp1[1], bp1[2], bp1[3]);
1181                 }
1182                 dc->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]);
1183                 for (Geom::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1184                     dc->currentcurve->curveto(bp2[2], bp2[1], bp2[0]);
1185                 }
1186                 // FIXME: dc->segments is always NULL at this point??
1187                 if (!dc->segments) { // first segment
1188                     add_cap(dc->currentcurve, b2[0], b1[0], dc->cap_rounding);
1189                 }
1190                 dc->currentcurve->closepath();
1191                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1192             }
1194             /* Current calligraphic */
1195             for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1196                 dc->cal1->curveto(bp1[1], bp1[2], bp1[3]);
1197             }
1198             for (Geom::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1199                 dc->cal2->curveto(bp2[1], bp2[2], bp2[3]);
1200             }
1201         } else {
1202             /* fixme: ??? */
1203 #ifdef DYNA_DRAW_VERBOSE
1204             g_print("[fit_and_split] failed to fit-cubic.\n");
1205 #endif
1206             draw_temporary_box(dc);
1208             for (gint i = 1; i < dc->npoints; i++) {
1209                 dc->cal1->lineto(dc->point1[i]);
1210             }
1211             for (gint i = 1; i < dc->npoints; i++) {
1212                 dc->cal2->lineto(dc->point2[i]);
1213             }
1214         }
1216         /* Fit and draw and copy last point */
1217 #ifdef DYNA_DRAW_VERBOSE
1218         g_print("[%d]Yup\n", dc->npoints);
1219 #endif
1220         if (!release) {
1221             g_assert(!dc->currentcurve->is_empty());
1223             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(desktop),
1224                                                    SP_TYPE_CANVAS_BPATH,
1225                                                    NULL);
1226             SPCurve *curve = dc->currentcurve->copy();
1227             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1228             curve->unref();
1230             guint32 fillColor = sp_desktop_get_color_tool (desktop, "/tools/calligraphic", true);
1231             //guint32 strokeColor = sp_desktop_get_color_tool (desktop, "/tools/calligraphic", false);
1232             double opacity = sp_desktop_get_master_opacity_tool (desktop, "/tools/calligraphic");
1233             double fillOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/calligraphic", true);
1234             //double strokeOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/calligraphic", false);
1235             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1236             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1237             //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);
1238             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1239             /* fixme: Cannot we cascade it to root more clearly? */
1240             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), desktop);
1242             dc->segments = g_slist_prepend(dc->segments, cbp);
1243         }
1245         dc->point1[0] = dc->point1[dc->npoints - 1];
1246         dc->point2[0] = dc->point2[dc->npoints - 1];
1247         dc->npoints = 1;
1248     } else {
1249         draw_temporary_box(dc);
1250     }
1253 static void
1254 draw_temporary_box(SPDynaDrawContext *dc)
1256     dc->currentcurve->reset();
1258     dc->currentcurve->moveto(dc->point2[dc->npoints-1]);
1259     for (gint i = dc->npoints-2; i >= 0; i--) {
1260         dc->currentcurve->lineto(dc->point2[i]);
1261     }
1262     for (gint i = 0; i < dc->npoints; i++) {
1263         dc->currentcurve->lineto(dc->point1[i]);
1264     }
1266     if (dc->npoints >= 2) {
1267         add_cap(dc->currentcurve, dc->point1[dc->npoints-1], dc->point2[dc->npoints-1], dc->cap_rounding);
1268     }
1270     dc->currentcurve->closepath();
1271     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1274 /*
1275   Local Variables:
1276   mode:c++
1277   c-file-style:"stroustrup"
1278   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1279   indent-tabs-mode:nil
1280   fill-column:99
1281   End:
1282 */
1283 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :