Code

From trunk
[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 "display/bezier-utils.h"
38 #include "display/curve.h"
39 #include <glib/gmem.h>
40 #include "macros.h"
41 #include "document.h"
42 #include "selection.h"
43 #include "desktop.h"
44 #include "desktop-events.h"
45 #include "desktop-handles.h"
46 #include "desktop-affine.h"
47 #include "desktop-style.h"
48 #include "message-context.h"
49 #include "preferences.h"
50 #include "pixmaps/cursor-calligraphy.xpm"
51 #include "libnr/nr-matrix-ops.h"
52 #include "libnr/nr-scale-translate-ops.h"
53 #include "libnr/nr-convert2geom.h"
54 #include "xml/repr.h"
55 #include "context-fns.h"
56 #include "sp-item.h"
57 #include "inkscape.h"
58 #include "color.h"
59 #include "splivarot.h"
60 #include "sp-item-group.h"
61 #include "sp-shape.h"
62 #include "sp-path.h"
63 #include "sp-text.h"
64 #include "display/canvas-bpath.h"
65 #include "display/canvas-arena.h"
66 #include "livarot/Shape.h"
67 #include <2geom/isnan.h>
68 #include <2geom/pathvector.h>
70 #include "dyna-draw-context.h"
72 #define DDC_RED_RGBA 0xff0000ff
74 #define TOLERANCE_CALLIGRAPHIC 0.1
76 #define DYNA_EPSILON 0.5e-6
77 #define DYNA_EPSILON_START 0.5e-2
78 #define DYNA_VEL_START 1e-5
80 #define DYNA_MIN_WIDTH 1.0e-6
82 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
83 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
84 static void sp_dyna_draw_context_dispose(GObject *object);
86 static void sp_dyna_draw_context_setup(SPEventContext *ec);
87 static void sp_dyna_draw_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *value);
88 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
90 static void clear_current(SPDynaDrawContext *dc);
91 static void set_to_accumulated(SPDynaDrawContext *dc, bool unionize);
92 static void add_cap(SPCurve *curve, Geom::Point const &from, Geom::Point const &to, double rounding);
93 static bool accumulate_calligraphic(SPDynaDrawContext *dc);
95 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
97 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, Geom::Point p);
98 static Geom::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, Geom::Point v);
99 static Geom::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, Geom::Point n);
100 static void draw_temporary_box(SPDynaDrawContext *dc);
103 static SPEventContextClass *dd_parent_class = 0;
105 GType sp_dyna_draw_context_get_type(void)
107     static GType type = 0;
108     if (!type) {
109         GTypeInfo info = {
110             sizeof(SPDynaDrawContextClass),
111             0, // base_init
112             0, // base_finalize
113             (GClassInitFunc)sp_dyna_draw_context_class_init,
114             0, // class_finalize
115             0, // class_data
116             sizeof(SPDynaDrawContext),
117             0, // n_preallocs
118             (GInstanceInitFunc)sp_dyna_draw_context_init,
119             0 // value_table
120         };
121         type = g_type_register_static(SP_TYPE_COMMON_CONTEXT, "SPDynaDrawContext", &info, static_cast<GTypeFlags>(0));
122     }
123     return type;
126 static void
127 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
129     GObjectClass *object_class = (GObjectClass *) klass;
130     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
132     dd_parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
134     object_class->dispose = sp_dyna_draw_context_dispose;
136     event_context_class->setup = sp_dyna_draw_context_setup;
137     event_context_class->set = sp_dyna_draw_context_set;
138     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
141 static void
142 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
144     ddc->cursor_shape = cursor_calligraphy_xpm;
145     ddc->hot_x = 4;
146     ddc->hot_y = 4;
148     ddc->vel_thin = 0.1;
149     ddc->flatness = 0.9;
150     ddc->cap_rounding = 0.0;
152     ddc->abs_width = false;
153     ddc->keep_selected = true;
155     ddc->hatch_spacing = 0;
156     ddc->hatch_spacing_step = 0;
157     new (&ddc->hatch_pointer_past) std::list<double>();
158     new (&ddc->hatch_nearest_past) std::list<double>();
159     ddc->hatch_last_nearest = Geom::Point(0,0);
160     ddc->hatch_last_pointer = Geom::Point(0,0);
161     ddc->hatch_vector_accumulated = Geom::Point(0,0);
162     ddc->hatch_escaped = false;
163     ddc->hatch_area = NULL;
164     ddc->hatch_item = NULL;
165     ddc->hatch_livarot_path = NULL;
167     ddc->trace_bg = 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();
187 static void
188 sp_dyna_draw_context_setup(SPEventContext *ec)
190     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
192     if (((SPEventContextClass *) dd_parent_class)->setup)
193         ((SPEventContextClass *) dd_parent_class)->setup(ec);
195     ddc->accumulated = new SPCurve();
196     ddc->currentcurve = new SPCurve();
198     ddc->cal1 = new SPCurve();
199     ddc->cal2 = new SPCurve();
201     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
202     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
203     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
204     /* fixme: Cannot we cascade it to root more clearly? */
205     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
207     {
208         /* 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) */
209         SPCurve *c = new SPCurve();
210         const double C1 = 0.552;
211         c->moveto(-1,0);
212         c->curveto(-1, C1, -C1, 1, 0, 1 );
213         c->curveto(C1, 1, 1, C1, 1, 0 );
214         c->curveto(1, -C1, C1, -1, 0, -1 );
215         c->curveto(-C1, -1, -1, -C1, -1, 0 );
216         c->closepath();
217         ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
218         c->unref();
219         sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
220         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
221         sp_canvas_item_hide(ddc->hatch_area);
222     }
224     sp_event_context_read(ec, "mass");
225     sp_event_context_read(ec, "wiggle");
226     sp_event_context_read(ec, "angle");
227     sp_event_context_read(ec, "width");
228     sp_event_context_read(ec, "thinning");
229     sp_event_context_read(ec, "tremor");
230     sp_event_context_read(ec, "flatness");
231     sp_event_context_read(ec, "tracebackground");
232     sp_event_context_read(ec, "usepressure");
233     sp_event_context_read(ec, "usetilt");
234     sp_event_context_read(ec, "abs_width");
235     sp_event_context_read(ec, "keep_selected");
236     sp_event_context_read(ec, "cap_rounding");
238     ddc->is_drawing = false;
239     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
241     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
242     if (prefs->getBool("/tools/calligraphic/selcue")) {
243         ec->enableSelectionCue();
244     }
247 static void
248 sp_dyna_draw_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val)
250     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
251     Glib::ustring path = val->getEntryName();
253     if (path == "tracebackground") {
254         ddc->trace_bg = val->getBool();
255     } else if (path == "keep_selected") {
256         ddc->keep_selected = val->getBool();
257     } else {
258         //pass on up to parent class to handle common attributes.
259         if ( dd_parent_class->set ) {
260             dd_parent_class->set(ec, val);
261         }
262     }
264     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
267 static double
268 flerp(double f0, double f1, double p)
270     return f0 + ( f1 - f0 ) * p;
273 /* Get normalized point */
274 static Geom::Point
275 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, Geom::Point v)
277     Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
278     double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
279     return Geom::Point(( v[Geom::X] - drect.min()[Geom::X] ) / max,  ( v[Geom::Y] - drect.min()[Geom::Y] ) / max);
282 /* Get view point */
283 static Geom::Point
284 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, Geom::Point n)
286     Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
287     double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
288     return Geom::Point(n[Geom::X] * max + drect.min()[Geom::X], n[Geom::Y] * max + drect.min()[Geom::Y]);
291 static void
292 sp_dyna_draw_reset(SPDynaDrawContext *dc, Geom::Point p)
294     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
295     dc->vel = Geom::Point(0,0);
296     dc->vel_max = 0;
297     dc->acc = Geom::Point(0,0);
298     dc->ang = Geom::Point(0,0);
299     dc->del = Geom::Point(0,0);
302 static void
303 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
305     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
306         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
307     else
308         dc->pressure = DDC_DEFAULT_PRESSURE;
310     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
311         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
312     else
313         dc->xtilt = DDC_DEFAULT_TILT;
315     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
316         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
317     else
318         dc->ytilt = DDC_DEFAULT_TILT;
322 static gboolean
323 sp_dyna_draw_apply(SPDynaDrawContext *dc, Geom::Point p)
325     Geom::Point n = sp_dyna_draw_get_npoint(dc, p);
327     /* Calculate mass and drag */
328     double const mass = flerp(1.0, 160.0, dc->mass);
329     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
331     /* Calculate force and acceleration */
332     Geom::Point force = n - dc->cur;
334     // If force is below the absolute threshold DYNA_EPSILON,
335     // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
336     // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
337     // discard this move. 
338     // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
339     // especially bothersome at the start of the stroke where we don't yet have the inertia to
340     // smooth them out.
341     if ( Geom::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && Geom::L2(force) < DYNA_EPSILON_START)) {
342         return FALSE;
343     }
345     dc->acc = force / mass;
347     /* Calculate new velocity */
348     dc->vel += dc->acc;
350     if (Geom::L2(dc->vel) > dc->vel_max)
351         dc->vel_max = Geom::L2(dc->vel);
353     /* Calculate angle of drawing tool */
355     double a1;
356     if (dc->usetilt) {
357         // 1a. calculate nib angle from input device tilt:
358         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
360         if (length > 0) {
361             Geom::Point ang1 = Geom::Point(dc->ytilt/length, dc->xtilt/length);
362             a1 = atan2(ang1);
363         }
364         else
365             a1 = 0.0;
366     }
367     else {
368         // 1b. fixed dc->angle (absolutely flat nib):
369         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
370         Geom::Point ang1 = Geom::Point(-sin(radians),  cos(radians));
371         a1 = atan2(ang1);
372     }
374     // 2. perpendicular to dc->vel (absolutely non-flat nib):
375     gdouble const mag_vel = Geom::L2(dc->vel);
376     if ( mag_vel < DYNA_EPSILON ) {
377         return FALSE;
378     }
379     Geom::Point ang2 = Geom::rot90(dc->vel) / mag_vel;
381     // 3. Average them using flatness parameter:
382     // calculate angles
383     double a2 = atan2(ang2);
384     // flip a2 to force it to be in the same half-circle as a1
385     bool flipped = false;
386     if (fabs (a2-a1) > 0.5*M_PI) {
387         a2 += M_PI;
388         flipped = true;
389     }
390     // normalize a2
391     if (a2 > M_PI)
392         a2 -= 2*M_PI;
393     if (a2 < -M_PI)
394         a2 += 2*M_PI;
395     // find the flatness-weighted bisector angle, unflip if a2 was flipped
396     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
397     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
399     // Try to detect a sudden flip when the new angle differs too much from the previous for the
400     // current velocity; in that case discard this move
401     double angle_delta = Geom::L2(Geom::Point (cos (new_ang), sin (new_ang)) - dc->ang);
402     if ( angle_delta / Geom::L2(dc->vel) > 4000 ) {
403         return FALSE;
404     }
406     // convert to point
407     dc->ang = Geom::Point (cos (new_ang), sin (new_ang));
409 //    g_print ("force %g  acc %g  vel_max %g  vel %g  a1 %g  a2 %g  new_ang %g\n", NR::L2(force), NR::L2(dc->acc), dc->vel_max, NR::L2(dc->vel), a1, a2, new_ang);
411     /* Apply drag */
412     dc->vel *= 1.0 - drag;
414     /* Update position */
415     dc->last = dc->cur;
416     dc->cur += dc->vel;
418     return TRUE;
421 static void
422 sp_dyna_draw_brush(SPDynaDrawContext *dc)
424     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
426     // How much velocity thins strokestyle
427     double vel_thin = flerp (0, 160, dc->vel_thin);
429     // Influence of pressure on thickness
430     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
432     // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
433     // drag)
434     Geom::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
435     Geom::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush); 
437     double trace_thick = 1;
438     if (dc->trace_bg) {
439         // pick single pixel
440         NRPixBlock pb;
441         int x = (int) floor(brush_w[Geom::X]);
442         int y = (int) floor(brush_w[Geom::Y]);
443         nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
444         sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
445         const unsigned char *s = NR_PIXBLOCK_PX(&pb);
446         double R = s[0] / 255.0;
447         double G = s[1] / 255.0;
448         double B = s[2] / 255.0;
449         double A = s[3] / 255.0;
450         double max = MAX (MAX (R, G), B);
451         double min = MIN (MIN (R, G), B);
452         double L = A * (max + min)/2 + (1 - A); // blend with white bg
453         trace_thick = 1 - L;
454         //g_print ("L %g thick %g\n", L, trace_thick);
455     }
457     double width = (pressure_thick * trace_thick - vel_thin * Geom::L2(dc->vel)) * dc->width;
459     double tremble_left = 0, tremble_right = 0;
460     if (dc->tremor > 0) {
461         // obtain two normally distributed random variables, using polar Box-Muller transform
462         double x1, x2, w, y1, y2;
463         do {
464             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
465             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
466             w = x1 * x1 + x2 * x2;
467         } while ( w >= 1.0 );
468         w = sqrt( (-2.0 * log( w ) ) / w );
469         y1 = x1 * w;
470         y2 = x2 * w;
472         // deflect both left and right edges randomly and independently, so that:
473         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
474         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
475         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
476         // comparatively smooth and slow ones excessively jittery
477         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
478         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
479     }
481     if ( width < 0.02 * dc->width ) {
482         width = 0.02 * dc->width;
483     }
485     double dezoomify_factor = 0.05 * 1000;
486     if (!dc->abs_width) {
487         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
488     }
490     Geom::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
491     Geom::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
493     dc->point1[dc->npoints] = brush + del_left;
494     dc->point2[dc->npoints] = brush - del_right;
496     dc->del = 0.5*(del_left + del_right);
498     dc->npoints++;
501 void
502 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
504     desktop->setToolboxAdjustmentValue (id, value);
507 static void
508 calligraphic_cancel(SPDynaDrawContext *dc)
510     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
511     dc->dragging = FALSE;
512     dc->is_drawing = false;
513     sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
514             /* Remove all temporary line segments */
515             while (dc->segments) {
516                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
517                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
518             }
519             /* reset accumulated curve */
520             dc->accumulated->reset();
521             clear_current(dc);
522             if (dc->repr) {
523                 dc->repr = NULL;
524             }
528 gint
529 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
530                                   GdkEvent *event)
532     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
533     SPDesktop *desktop = event_context->desktop;
535     gint ret = FALSE;
537     switch (event->type) {
538         case GDK_BUTTON_PRESS:
539             if (event->button.button == 1 && !event_context->space_panning) {
541                 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
543                 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
544                     return TRUE;
545                 }
547                 Geom::Point const button_w(event->button.x,
548                                          event->button.y);
549                 Geom::Point const button_dt(desktop->w2d(button_w));
550                 sp_dyna_draw_reset(dc, button_dt);
551                 sp_dyna_draw_extinput(dc, event);
552                 sp_dyna_draw_apply(dc, button_dt);
553                 dc->accumulated->reset();
554                 if (dc->repr) {
555                     dc->repr = NULL;
556                 }
558                 /* initialize first point */
559                 dc->npoints = 0;
561                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
562                                     ( GDK_KEY_PRESS_MASK |
563                                       GDK_BUTTON_RELEASE_MASK |
564                                       GDK_POINTER_MOTION_MASK |
565                                       GDK_BUTTON_PRESS_MASK ),
566                                     NULL,
567                                     event->button.time);
569                 ret = TRUE;
571                 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
572                 dc->is_drawing = true;
573             }
574             break;
575         case GDK_MOTION_NOTIFY:
576         {
577             Geom::Point const motion_w(event->motion.x,
578                                      event->motion.y);
579             Geom::Point motion_dt(desktop->w2d(motion_w));
580             sp_dyna_draw_extinput(dc, event);
582             dc->_message_context->clear();
584             // for hatching:
585             double hatch_dist = 0;
586             Geom::Point hatch_unit_vector(0,0);
587             Geom::Point nearest(0,0);
588             Geom::Point pointer(0,0);
589             Geom::Matrix motion_to_curve(Geom::identity());
591             if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
593                 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
594                 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
595                     // One item selected, and it's a path;
596                     // let's try to track it as a guide
598                     if (selected != dc->hatch_item) {
599                         dc->hatch_item = selected;
600                         if (dc->hatch_livarot_path)
601                             delete dc->hatch_livarot_path;
602                         dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
603                         dc->hatch_livarot_path->ConvertWithBackData(0.01);
604                     }
606                     // calculate pointer point in the guide item's coords
607                     motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
608                     pointer = motion_dt * motion_to_curve;
610                     // calculate the nearest point on the guide path
611                     boost::optional<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
612                     nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
615                     // distance from pointer to nearest
616                     hatch_dist = NR::L2(pointer - nearest);
617                     // unit-length vector
618                     hatch_unit_vector = (pointer - nearest)/hatch_dist;
620                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
621                 } else {
622                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
623                 }
624             } 
626             if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
627                 dc->dragging = TRUE;
629                 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
631 #define SPEED_ELEMENTS 12
632 #define SPEED_MIN 0.12
633 #define SPEED_NORMAL 0.65
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[NR::X], dc->last_nearest[NR::Y], nearest[NR::X], nearest[NR::Y], pointer[NR::X], pointer[NR::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                     } else {
686                         // Calculate angle cosine of this vector-to-guide and all past vectors
687                         // summed, to detect if we accidentally flipped to the other side of the
688                         // guide
689                         double dot = NR::dot (pointer - nearest, dc->hatch_vector_accumulated);
690                         dot /= Geom::L2(pointer - nearest) * Geom::L2(dc->hatch_vector_accumulated);
692                         if (dc->hatch_spacing != 0) { // spacing was already set
693                             double target;
694                             if (speed > SPEED_NORMAL) {
695                                 // all ok, strictly obey the spacing
696                                 target = dc->hatch_spacing;
697                             } else {
698                                 // looks like we're starting to lose speed,
699                                 // so _gradually_ let go attraction to prevent jerks
700                                 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;                            
701                             }
702                             if (!IS_NAN(dot) && dot < -0.5) {// flip
703                                 target = -target;
704                             }
706                             // This is the track pointer that we will use instead of the real one
707                             Geom::Point new_pointer = nearest + target * hatch_unit_vector;
709                             // some limited feedback: allow persistent pulling to slightly change
710                             // the spacing
711                             dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
713                             // return it to the desktop coords
714                             motion_dt = new_pointer * motion_to_curve.inverse();
716                         } else {
717                             // this is the first motion event, set the dist 
718                             dc->hatch_spacing = hatch_dist;
719                         }
721                         // remember last points
722                         dc->hatch_last_pointer = pointer;
723                         dc->hatch_last_nearest = nearest;
724                         dc->hatch_vector_accumulated += (pointer - nearest);
725                     }
727                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
729                 } else {
730                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
731                 }
733                 if (!sp_dyna_draw_apply(dc, motion_dt)) {
734                     ret = TRUE;
735                     break;
736                 }
738                 if ( dc->cur != dc->last ) {
739                     sp_dyna_draw_brush(dc);
740                     g_assert( dc->npoints > 0 );
741                     fit_and_split(dc, FALSE);
742                 }
743                 ret = TRUE;
744             }
746             // Draw the hatching circle if necessary
747             if (event->motion.state & GDK_CONTROL_MASK) { 
748                 if (dc->hatch_spacing == 0 && hatch_dist != 0) { 
749                     // Haven't set spacing yet: gray, center free, update radius live
750                     Geom::Point c = desktop->w2d(motion_w);
751                     NR::Matrix const sm (Geom::Scale(hatch_dist, hatch_dist) * Geom::Translate(c));
752                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
753                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
754                     sp_canvas_item_show(dc->hatch_area);
755                 } else if (dc->dragging && !dc->hatch_escaped) {
756                     // Tracking: green, center snapped, fixed radius
757                     Geom::Point c = motion_dt;
758                     NR::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
759                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
760                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
761                     sp_canvas_item_show(dc->hatch_area);
762                 } else if (dc->dragging && dc->hatch_escaped) {
763                     // Tracking escaped: red, center free, fixed radius
764                     Geom::Point c = desktop->w2d(motion_w);
765                     NR::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
767                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
768                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
769                     sp_canvas_item_show(dc->hatch_area);
770                 } else {
771                     // Not drawing but spacing set: gray, center snapped, fixed radius
772                     Geom::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
773                     if (!IS_NAN(c[Geom::X]) && !IS_NAN(c[Geom::Y])) {
774                         NR::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
775                         sp_canvas_item_affine_absolute(dc->hatch_area, sm);
776                         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
777                         sp_canvas_item_show(dc->hatch_area);
778                     }
779                 }
780             } else {
781                 sp_canvas_item_hide(dc->hatch_area);
782             }
783         }
784         break;
787     case GDK_BUTTON_RELEASE:
788     {
789         Geom::Point const motion_w(event->button.x, event->button.y);
790         Geom::Point const motion_dt(desktop->w2d(motion_w));
792         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
793         sp_canvas_end_forced_full_redraws(desktop->canvas);
794         dc->is_drawing = false;
796         if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
797             dc->dragging = FALSE;
799             sp_dyna_draw_apply(dc, motion_dt);
801             /* Remove all temporary line segments */
802             while (dc->segments) {
803                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
804                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
805             }
807             /* Create object */
808             fit_and_split(dc, TRUE);
809             if (accumulate_calligraphic(dc))
810                 set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK); // performs document_done
811             else
812                 g_warning ("Failed to create path: invalid data in dc->cal1 or dc->cal2");
814             /* reset accumulated curve */
815             dc->accumulated->reset();
817             clear_current(dc);
818             if (dc->repr) {
819                 dc->repr = NULL;
820             }
822             if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
823             if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
824             dc->hatch_last_nearest = Geom::Point(0,0);
825             dc->hatch_last_pointer = Geom::Point(0,0);
826             dc->hatch_vector_accumulated = Geom::Point(0,0);
827             dc->hatch_escaped = false;
828             dc->hatch_item = NULL;
829             dc->hatch_livarot_path = NULL;
831             if (dc->hatch_spacing != 0 && !dc->keep_selected) { 
832                 // we do not select the newly drawn path, so increase spacing by step
833                 if (dc->hatch_spacing_step == 0) {
834                     dc->hatch_spacing_step = dc->hatch_spacing;
835                 }
836                 dc->hatch_spacing += dc->hatch_spacing_step;
837             }
839             dc->_message_context->clear();
840             ret = TRUE;
841         }
842         break;
843     }
845     case GDK_KEY_PRESS:
846         switch (get_group0_keyval (&event->key)) {
847         case GDK_Up:
848         case GDK_KP_Up:
849             if (!MOD__CTRL_ONLY) {
850                 dc->angle += 5.0;
851                 if (dc->angle > 90.0)
852                     dc->angle = 90.0;
853                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
854                 ret = TRUE;
855             }
856             break;
857         case GDK_Down:
858         case GDK_KP_Down:
859             if (!MOD__CTRL_ONLY) {
860                 dc->angle -= 5.0;
861                 if (dc->angle < -90.0)
862                     dc->angle = -90.0;
863                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
864                 ret = TRUE;
865             }
866             break;
867         case GDK_Right:
868         case GDK_KP_Right:
869             if (!MOD__CTRL_ONLY) {
870                 dc->width += 0.01;
871                 if (dc->width > 1.0)
872                     dc->width = 1.0;
873                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
874                 ret = TRUE;
875             }
876             break;
877         case GDK_Left:
878         case GDK_KP_Left:
879             if (!MOD__CTRL_ONLY) {
880                 dc->width -= 0.01;
881                 if (dc->width < 0.01)
882                     dc->width = 0.01;
883                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
884                 ret = TRUE;
885             }
886             break;
887         case GDK_Home:
888         case GDK_KP_Home:
889             dc->width = 0.01;
890             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
891             ret = TRUE;
892             break;
893         case GDK_End:
894         case GDK_KP_End:
895             dc->width = 1.0;
896             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
897             ret = TRUE;
898             break;
899         case GDK_x:
900         case GDK_X:
901             if (MOD__ALT_ONLY) {
902                 desktop->setToolboxFocusTo ("altx-calligraphy");
903                 ret = TRUE;
904             }
905             break;
906         case GDK_Escape:
907             if (dc->is_drawing) {
908                 // if drawing, cancel, otherwise pass it up for deselecting
909                 calligraphic_cancel (dc);
910                 ret = TRUE;
911             }
912             break;
913         case GDK_z:
914         case GDK_Z:
915             if (MOD__CTRL_ONLY && dc->is_drawing) {
916                 // if drawing, cancel, otherwise pass it up for undo
917                 calligraphic_cancel (dc);
918                 ret = TRUE;
919             }
920             break;
921         default:
922             break;
923         }
924         break;
926     case GDK_KEY_RELEASE:
927         switch (get_group0_keyval(&event->key)) {
928             case GDK_Control_L:
929             case GDK_Control_R:
930                 dc->_message_context->clear();
931                 dc->hatch_spacing = 0;
932                 dc->hatch_spacing_step = 0;
933                 break;
934             default:
935                 break;
936         }
938     default:
939         break;
940     }
942     if (!ret) {
943         if (((SPEventContextClass *) dd_parent_class)->root_handler) {
944             ret = ((SPEventContextClass *) dd_parent_class)->root_handler(event_context, event);
945         }
946     }
948     return ret;
952 static void
953 clear_current(SPDynaDrawContext *dc)
955     /* reset bpath */
956     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
957     /* reset curve */
958     dc->currentcurve->reset();
959     dc->cal1->reset();
960     dc->cal2->reset();
961     /* reset points */
962     dc->npoints = 0;
965 static void
966 set_to_accumulated(SPDynaDrawContext *dc, bool unionize)
968     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
970     if (!dc->accumulated->is_empty()) {
971         if (!dc->repr) {
972             /* Create object */
973             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
974             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
976             /* Set style */
977             sp_desktop_apply_style_tool (desktop, repr, "/tools/calligraphic", false);
979             dc->repr = repr;
981             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
982             Inkscape::GC::release(dc->repr);
983             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
984             item->updateRepr();
985         }
986         Geom::PathVector pathv = dc->accumulated->get_pathvector() * sp_desktop_dt2root_affine(desktop);
987         gchar *str = sp_svg_write_path(pathv);
988         g_assert( str != NULL );
989         dc->repr->setAttribute("d", str);
990         g_free(str);
992         if (unionize) {
993             sp_desktop_selection(desktop)->add(dc->repr);
994             sp_selected_path_union_skip_undo(desktop);
995         } else {
996             if (dc->keep_selected) {
997                 sp_desktop_selection(desktop)->set(dc->repr);
998             } 
999         }
1001     } else {
1002         if (dc->repr) {
1003             sp_repr_unparent(dc->repr);
1004         }
1005         dc->repr = NULL;
1006     }
1008     sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC, 
1009                      _("Draw calligraphic stroke"));
1012 static void
1013 add_cap(SPCurve *curve,
1014         Geom::Point const &from,
1015         Geom::Point const &to, 
1016         double rounding)
1018     if (Geom::L2( to - from ) > DYNA_EPSILON) {
1019         Geom::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
1020         double mag = Geom::L2(vel);
1022         Geom::Point v = mag * NR::rot90( to - from ) / Geom::L2( to - from );
1023         curve->curveto(from + v, to + v, to);
1024     }
1027 static bool
1028 accumulate_calligraphic(SPDynaDrawContext *dc)
1030         if (
1031             dc->cal1->is_empty() ||
1032             dc->cal2->is_empty() ||
1033             (dc->cal1->get_segment_count() <= 0) ||
1034             dc->cal1->first_path()->closed() 
1035             ) {
1036             dc->cal1->reset();
1037             dc->cal2->reset();
1038             return false; // failure
1039         }
1041         SPCurve *rev_cal2 = dc->cal2->create_reverse();
1042         if (
1043             (rev_cal2->get_segment_count() <= 0) ||
1044             rev_cal2->first_path()->closed() 
1045             ) {
1046             rev_cal2->unref();
1047             dc->cal1->reset();
1048             dc->cal2->reset();
1049             return false; // failure
1050         }
1052         Geom::CubicBezier const * dc_cal1_firstseg  = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->first_segment() );
1053         Geom::CubicBezier const * rev_cal2_firstseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->first_segment() );
1054         Geom::CubicBezier const * dc_cal1_lastseg   = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->last_segment() );
1055         Geom::CubicBezier const * rev_cal2_lastseg  = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->last_segment() );
1057         if (
1058             !dc_cal1_firstseg ||
1059             !rev_cal2_firstseg ||
1060             !dc_cal1_lastseg ||
1061             !rev_cal2_lastseg 
1062             ) {
1063             rev_cal2->unref();
1064             dc->cal1->reset();
1065             dc->cal2->reset();
1066             return false; // failure
1067         }
1069         dc->accumulated->reset(); /*  Is this required ?? */
1071         dc->accumulated->append(dc->cal1, false);
1073         add_cap(dc->accumulated, (*dc_cal1_lastseg)[3], (*rev_cal2_firstseg)[0], dc->cap_rounding);
1075         dc->accumulated->append(rev_cal2, true);
1077         add_cap(dc->accumulated, (*rev_cal2_lastseg)[3], (*dc_cal1_firstseg)[0], dc->cap_rounding);
1079         dc->accumulated->closepath();
1081         rev_cal2->unref();
1083         dc->cal1->reset();
1084         dc->cal2->reset();
1086         return true; // success
1089 static double square(double const x)
1091     return x * x;
1094 static void
1095 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1097     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1099     double const tolerance_sq = square( desktop->w2d().descrim() * TOLERANCE_CALLIGRAPHIC );
1101 #ifdef DYNA_DRAW_VERBOSE
1102     g_print("[F&S:R=%c]", release?'T':'F');
1103 #endif
1105     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1106         return; // just clicked
1108     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1109 #define BEZIER_SIZE       4
1110 #define BEZIER_MAX_BEZIERS  8
1111 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1113 #ifdef DYNA_DRAW_VERBOSE
1114         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1115                 dc->npoints, release ? "TRUE" : "FALSE");
1116 #endif
1118         /* Current calligraphic */
1119         if ( dc->cal1->is_empty() || dc->cal2->is_empty() ) {
1120             /* dc->npoints > 0 */
1121             /* g_print("calligraphics(1|2) reset\n"); */
1122             dc->cal1->reset();
1123             dc->cal2->reset();
1125             dc->cal1->moveto(dc->point1[0]);
1126             dc->cal2->moveto(dc->point2[0]);
1127         }
1129         Geom::Point b1[BEZIER_MAX_LENGTH];
1130         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1131                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1132         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1134         Geom::Point b2[BEZIER_MAX_LENGTH];
1135         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1136                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1137         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1139         if ( nb1 != -1 && nb2 != -1 ) {
1140             /* Fit and draw and reset state */
1141 #ifdef DYNA_DRAW_VERBOSE
1142             g_print("nb1:%d nb2:%d\n", nb1, nb2);
1143 #endif
1144             /* CanvasShape */
1145             if (! release) {
1146                 dc->currentcurve->reset();
1147                 dc->currentcurve->moveto(b1[0]);
1148                 for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1149                     dc->currentcurve->curveto(bp1[1], bp1[2], bp1[3]);
1150                 }
1151                 dc->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]);
1152                 for (Geom::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1153                     dc->currentcurve->curveto(bp2[2], bp2[1], bp2[0]);
1154                 }
1155                 // FIXME: dc->segments is always NULL at this point??
1156                 if (!dc->segments) { // first segment
1157                     add_cap(dc->currentcurve, b2[0], b1[0], dc->cap_rounding);
1158                 }
1159                 dc->currentcurve->closepath();
1160                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1161             }
1163             /* Current calligraphic */
1164             for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1165                 dc->cal1->curveto(bp1[1], bp1[2], bp1[3]);
1166             }
1167             for (Geom::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1168                 dc->cal2->curveto(bp2[1], bp2[2], bp2[3]);
1169             }
1170         } else {
1171             /* fixme: ??? */
1172 #ifdef DYNA_DRAW_VERBOSE
1173             g_print("[fit_and_split] failed to fit-cubic.\n");
1174 #endif
1175             draw_temporary_box(dc);
1177             for (gint i = 1; i < dc->npoints; i++) {
1178                 dc->cal1->lineto(dc->point1[i]);
1179             }
1180             for (gint i = 1; i < dc->npoints; i++) {
1181                 dc->cal2->lineto(dc->point2[i]);
1182             }
1183         }
1185         /* Fit and draw and copy last point */
1186 #ifdef DYNA_DRAW_VERBOSE
1187         g_print("[%d]Yup\n", dc->npoints);
1188 #endif
1189         if (!release) {
1190             g_assert(!dc->currentcurve->is_empty());
1192             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(desktop),
1193                                                    SP_TYPE_CANVAS_BPATH,
1194                                                    NULL);
1195             SPCurve *curve = dc->currentcurve->copy();
1196             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1197             curve->unref();
1199             guint32 fillColor = sp_desktop_get_color_tool (desktop, "/tools/calligraphic", true);
1200             //guint32 strokeColor = sp_desktop_get_color_tool (desktop, "/tools/calligraphic", false);
1201             double opacity = sp_desktop_get_master_opacity_tool (desktop, "/tools/calligraphic");
1202             double fillOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/calligraphic", true);
1203             //double strokeOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/calligraphic", false);
1204             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1205             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1206             //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);
1207             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1208             /* fixme: Cannot we cascade it to root more clearly? */
1209             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), desktop);
1211             dc->segments = g_slist_prepend(dc->segments, cbp);
1212         }
1214         dc->point1[0] = dc->point1[dc->npoints - 1];
1215         dc->point2[0] = dc->point2[dc->npoints - 1];
1216         dc->npoints = 1;
1217     } else {
1218         draw_temporary_box(dc);
1219     }
1222 static void
1223 draw_temporary_box(SPDynaDrawContext *dc)
1225     dc->currentcurve->reset();
1227     dc->currentcurve->moveto(dc->point2[dc->npoints-1]);
1228     for (gint i = dc->npoints-2; i >= 0; i--) {
1229         dc->currentcurve->lineto(dc->point2[i]);
1230     }
1231     for (gint i = 0; i < dc->npoints; i++) {
1232         dc->currentcurve->lineto(dc->point1[i]);
1233     }
1235     if (dc->npoints >= 2) {
1236         add_cap(dc->currentcurve, dc->point1[dc->npoints-1], dc->point2[dc->npoints-1], dc->cap_rounding);
1237     }
1239     dc->currentcurve->closepath();
1240     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1243 /*
1244   Local Variables:
1245   mode:c++
1246   c-file-style:"stroustrup"
1247   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1248   indent-tabs-mode:nil
1249   fill-column:99
1250   End:
1251 */
1252 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :