Code

work a bit on snapindicator: added switch statement for different types
[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     ddc->hatch_last_nearest = Geom::Point(0,0);
157     ddc->hatch_last_pointer = Geom::Point(0,0);
158     ddc->hatch_vector_accumulated = Geom::Point(0,0);
159     ddc->hatch_escaped = false;
160     ddc->hatch_area = NULL;
161     ddc->hatch_item = NULL;
162     ddc->hatch_livarot_path = NULL;
164     ddc->trace_bg = false;
167 static void
168 sp_dyna_draw_context_dispose(GObject *object)
170     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
172     if (ddc->hatch_area) {
173         gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
174         ddc->hatch_area = NULL;
175     }
178     G_OBJECT_CLASS(dd_parent_class)->dispose(object);
180     ddc->hatch_pointer_past.~list();
181     ddc->hatch_nearest_past.~list();
184 static void
185 sp_dyna_draw_context_setup(SPEventContext *ec)
187     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
189     if (((SPEventContextClass *) dd_parent_class)->setup)
190         ((SPEventContextClass *) dd_parent_class)->setup(ec);
192     ddc->accumulated = new SPCurve();
193     ddc->currentcurve = new SPCurve();
195     ddc->cal1 = new SPCurve();
196     ddc->cal2 = new SPCurve();
198     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
199     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
200     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
201     /* fixme: Cannot we cascade it to root more clearly? */
202     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
204     {
205         /* 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) */
206         SPCurve *c = new SPCurve();
207         const double C1 = 0.552;
208         c->moveto(-1,0);
209         c->curveto(-1, C1, -C1, 1, 0, 1 );
210         c->curveto(C1, 1, 1, C1, 1, 0 );
211         c->curveto(1, -C1, C1, -1, 0, -1 );
212         c->curveto(-C1, -1, -1, -C1, -1, 0 );
213         c->closepath();
214         ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
215         c->unref();
216         sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
217         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
218         sp_canvas_item_hide(ddc->hatch_area);
219     }
221     sp_event_context_read(ec, "mass");
222     sp_event_context_read(ec, "wiggle");
223     sp_event_context_read(ec, "angle");
224     sp_event_context_read(ec, "width");
225     sp_event_context_read(ec, "thinning");
226     sp_event_context_read(ec, "tremor");
227     sp_event_context_read(ec, "flatness");
228     sp_event_context_read(ec, "tracebackground");
229     sp_event_context_read(ec, "usepressure");
230     sp_event_context_read(ec, "usetilt");
231     sp_event_context_read(ec, "abs_width");
232     sp_event_context_read(ec, "keep_selected");
233     sp_event_context_read(ec, "cap_rounding");
235     ddc->is_drawing = false;
236     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
238     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
239     if (prefs->getBool("/tools/calligraphic/selcue")) {
240         ec->enableSelectionCue();
241     }
244 static void
245 sp_dyna_draw_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val)
247     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
248     Glib::ustring path = val->getEntryName();
250     if (path == "tracebackground") {
251         ddc->trace_bg = val->getBool();
252     } else if (path == "keep_selected") {
253         ddc->keep_selected = val->getBool();
254     } else {
255         //pass on up to parent class to handle common attributes.
256         if ( dd_parent_class->set ) {
257             dd_parent_class->set(ec, val);
258         }
259     }
261     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
264 static double
265 flerp(double f0, double f1, double p)
267     return f0 + ( f1 - f0 ) * p;
270 /* Get normalized point */
271 static Geom::Point
272 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, Geom::Point v)
274     Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
275     double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
276     return Geom::Point(( v[Geom::X] - drect.min()[Geom::X] ) / max,  ( v[Geom::Y] - drect.min()[Geom::Y] ) / max);
279 /* Get view point */
280 static Geom::Point
281 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, Geom::Point n)
283     Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
284     double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
285     return Geom::Point(n[Geom::X] * max + drect.min()[Geom::X], n[Geom::Y] * max + drect.min()[Geom::Y]);
288 static void
289 sp_dyna_draw_reset(SPDynaDrawContext *dc, Geom::Point p)
291     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
292     dc->vel = Geom::Point(0,0);
293     dc->vel_max = 0;
294     dc->acc = Geom::Point(0,0);
295     dc->ang = Geom::Point(0,0);
296     dc->del = Geom::Point(0,0);
299 static void
300 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
302     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
303         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
304     else
305         dc->pressure = DDC_DEFAULT_PRESSURE;
307     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
308         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
309     else
310         dc->xtilt = DDC_DEFAULT_TILT;
312     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
313         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
314     else
315         dc->ytilt = DDC_DEFAULT_TILT;
319 static gboolean
320 sp_dyna_draw_apply(SPDynaDrawContext *dc, Geom::Point p)
322     Geom::Point n = sp_dyna_draw_get_npoint(dc, p);
324     /* Calculate mass and drag */
325     double const mass = flerp(1.0, 160.0, dc->mass);
326     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
328     /* Calculate force and acceleration */
329     Geom::Point force = n - dc->cur;
331     // If force is below the absolute threshold DYNA_EPSILON,
332     // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
333     // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
334     // discard this move. 
335     // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
336     // especially bothersome at the start of the stroke where we don't yet have the inertia to
337     // smooth them out.
338     if ( Geom::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && Geom::L2(force) < DYNA_EPSILON_START)) {
339         return FALSE;
340     }
342     dc->acc = force / mass;
344     /* Calculate new velocity */
345     dc->vel += dc->acc;
347     if (Geom::L2(dc->vel) > dc->vel_max)
348         dc->vel_max = Geom::L2(dc->vel);
350     /* Calculate angle of drawing tool */
352     double a1;
353     if (dc->usetilt) {
354         // 1a. calculate nib angle from input device tilt:
355         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
357         if (length > 0) {
358             Geom::Point ang1 = Geom::Point(dc->ytilt/length, dc->xtilt/length);
359             a1 = atan2(ang1);
360         }
361         else
362             a1 = 0.0;
363     }
364     else {
365         // 1b. fixed dc->angle (absolutely flat nib):
366         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
367         Geom::Point ang1 = Geom::Point(-sin(radians),  cos(radians));
368         a1 = atan2(ang1);
369     }
371     // 2. perpendicular to dc->vel (absolutely non-flat nib):
372     gdouble const mag_vel = Geom::L2(dc->vel);
373     if ( mag_vel < DYNA_EPSILON ) {
374         return FALSE;
375     }
376     Geom::Point ang2 = Geom::rot90(dc->vel) / mag_vel;
378     // 3. Average them using flatness parameter:
379     // calculate angles
380     double a2 = atan2(ang2);
381     // flip a2 to force it to be in the same half-circle as a1
382     bool flipped = false;
383     if (fabs (a2-a1) > 0.5*M_PI) {
384         a2 += M_PI;
385         flipped = true;
386     }
387     // normalize a2
388     if (a2 > M_PI)
389         a2 -= 2*M_PI;
390     if (a2 < -M_PI)
391         a2 += 2*M_PI;
392     // find the flatness-weighted bisector angle, unflip if a2 was flipped
393     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
394     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
396     // Try to detect a sudden flip when the new angle differs too much from the previous for the
397     // current velocity; in that case discard this move
398     double angle_delta = Geom::L2(Geom::Point (cos (new_ang), sin (new_ang)) - dc->ang);
399     if ( angle_delta / Geom::L2(dc->vel) > 4000 ) {
400         return FALSE;
401     }
403     // convert to point
404     dc->ang = Geom::Point (cos (new_ang), sin (new_ang));
406 //    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);
408     /* Apply drag */
409     dc->vel *= 1.0 - drag;
411     /* Update position */
412     dc->last = dc->cur;
413     dc->cur += dc->vel;
415     return TRUE;
418 static void
419 sp_dyna_draw_brush(SPDynaDrawContext *dc)
421     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
423     // How much velocity thins strokestyle
424     double vel_thin = flerp (0, 160, dc->vel_thin);
426     // Influence of pressure on thickness
427     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
429     // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
430     // drag)
431     Geom::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
432     Geom::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush); 
434     double trace_thick = 1;
435     if (dc->trace_bg) {
436         // pick single pixel
437         NRPixBlock pb;
438         int x = (int) floor(brush_w[Geom::X]);
439         int y = (int) floor(brush_w[Geom::Y]);
440         nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
441         sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
442         const unsigned char *s = NR_PIXBLOCK_PX(&pb);
443         double R = s[0] / 255.0;
444         double G = s[1] / 255.0;
445         double B = s[2] / 255.0;
446         double A = s[3] / 255.0;
447         double max = MAX (MAX (R, G), B);
448         double min = MIN (MIN (R, G), B);
449         double L = A * (max + min)/2 + (1 - A); // blend with white bg
450         trace_thick = 1 - L;
451         //g_print ("L %g thick %g\n", L, trace_thick);
452     }
454     double width = (pressure_thick * trace_thick - vel_thin * Geom::L2(dc->vel)) * dc->width;
456     double tremble_left = 0, tremble_right = 0;
457     if (dc->tremor > 0) {
458         // obtain two normally distributed random variables, using polar Box-Muller transform
459         double x1, x2, w, y1, y2;
460         do {
461             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
462             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
463             w = x1 * x1 + x2 * x2;
464         } while ( w >= 1.0 );
465         w = sqrt( (-2.0 * log( w ) ) / w );
466         y1 = x1 * w;
467         y2 = x2 * w;
469         // deflect both left and right edges randomly and independently, so that:
470         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
471         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
472         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
473         // comparatively smooth and slow ones excessively jittery
474         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
475         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
476     }
478     if ( width < 0.02 * dc->width ) {
479         width = 0.02 * dc->width;
480     }
482     double dezoomify_factor = 0.05 * 1000;
483     if (!dc->abs_width) {
484         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
485     }
487     Geom::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
488     Geom::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
490     dc->point1[dc->npoints] = brush + del_left;
491     dc->point2[dc->npoints] = brush - del_right;
493     dc->del = 0.5*(del_left + del_right);
495     dc->npoints++;
498 void
499 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
501     desktop->setToolboxAdjustmentValue (id, value);
504 static void
505 calligraphic_cancel(SPDynaDrawContext *dc)
507     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
508     dc->dragging = FALSE;
509     dc->is_drawing = false;
510     sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
511             /* Remove all temporary line segments */
512             while (dc->segments) {
513                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
514                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
515             }
516             /* reset accumulated curve */
517             dc->accumulated->reset();
518             clear_current(dc);
519             if (dc->repr) {
520                 dc->repr = NULL;
521             }
525 gint
526 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
527                                   GdkEvent *event)
529     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
530     SPDesktop *desktop = event_context->desktop;
532     gint ret = FALSE;
534     switch (event->type) {
535         case GDK_BUTTON_PRESS:
536             if (event->button.button == 1 && !event_context->space_panning) {
538                 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
540                 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
541                     return TRUE;
542                 }
544                 Geom::Point const button_w(event->button.x,
545                                          event->button.y);
546                 Geom::Point const button_dt(desktop->w2d(button_w));
547                 sp_dyna_draw_reset(dc, button_dt);
548                 sp_dyna_draw_extinput(dc, event);
549                 sp_dyna_draw_apply(dc, button_dt);
550                 dc->accumulated->reset();
551                 if (dc->repr) {
552                     dc->repr = NULL;
553                 }
555                 /* initialize first point */
556                 dc->npoints = 0;
558                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
559                                     ( GDK_KEY_PRESS_MASK |
560                                       GDK_BUTTON_RELEASE_MASK |
561                                       GDK_POINTER_MOTION_MASK |
562                                       GDK_BUTTON_PRESS_MASK ),
563                                     NULL,
564                                     event->button.time);
566                 ret = TRUE;
568                 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
569                 dc->is_drawing = true;
570             }
571             break;
572         case GDK_MOTION_NOTIFY:
573         {
574             Geom::Point const motion_w(event->motion.x,
575                                      event->motion.y);
576             Geom::Point motion_dt(desktop->w2d(motion_w));
577             sp_dyna_draw_extinput(dc, event);
579             dc->_message_context->clear();
581             // for hatching:
582             double hatch_dist = 0;
583             Geom::Point hatch_unit_vector(0,0);
584             Geom::Point nearest(0,0);
585             Geom::Point pointer(0,0);
586             Geom::Matrix motion_to_curve(Geom::identity());
588             if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
590                 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
591                 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
592                     // One item selected, and it's a path;
593                     // let's try to track it as a guide
595                     if (selected != dc->hatch_item) {
596                         dc->hatch_item = selected;
597                         if (dc->hatch_livarot_path)
598                             delete dc->hatch_livarot_path;
599                         dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
600                         dc->hatch_livarot_path->ConvertWithBackData(0.01);
601                     }
603                     // calculate pointer point in the guide item's coords
604                     motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
605                     pointer = motion_dt * motion_to_curve;
607                     // calculate the nearest point on the guide path
608                     boost::optional<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
609                     nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
612                     // distance from pointer to nearest
613                     hatch_dist = Geom::L2(pointer - nearest);
614                     // unit-length vector
615                     hatch_unit_vector = (pointer - nearest)/hatch_dist;
617                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
618                 } else {
619                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
620                 }
621             } 
623             if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
624                 dc->dragging = TRUE;
626                 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
628 #define SPEED_ELEMENTS 12
629 #define SPEED_MIN 0.12
630 #define SPEED_NORMAL 0.65
632                     // speed is the movement of the nearest point along the guide path, divided by
633                     // the movement of the pointer at the same period; it is averaged for the last
634                     // SPEED_ELEMENTS motion events.  Normally, as you track the guide path, speed
635                     // is about 1, i.e. the nearest point on the path is moved by about the same
636                     // distance as the pointer. If the speed starts to decrease, we are losing
637                     // contact with the guide; if it drops below SPEED_MIN, we are on our own and
638                     // not attracted to guide anymore. Most often this happens when you have
639                     // tracked to the end of a guide calligraphic stroke and keep moving
640                     // further. We try to handle this situation gracefully: not stick with the
641                     // guide forever but let go of it smoothly and without sharp jerks (non-zero
642                     // mass recommended; with zero mass, jerks are still quite noticeable).
644                     double speed = 1;
645                     if (Geom::L2(dc->hatch_last_nearest) != 0) {
646                         // the distance nearest moved since the last motion event
647                         double nearest_moved = Geom::L2(nearest - dc->hatch_last_nearest);
648                         // the distance pointer moved since the last motion event
649                         double pointer_moved = Geom::L2(pointer - dc->hatch_last_pointer);
650                         // store them in stacks limited to SPEED_ELEMENTS
651                         dc->hatch_nearest_past.push_front(nearest_moved);
652                         if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
653                             dc->hatch_nearest_past.pop_back();
654                         dc->hatch_pointer_past.push_front(pointer_moved);
655                         if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
656                             dc->hatch_pointer_past.pop_back();
658                         // If the stacks are full,
659                         if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
660                             // calculate the sums of all stored movements
661                             double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
662                             double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
663                             // and divide to get the speed
664                             speed = nearest_sum/pointer_sum;
665                             //g_print ("nearest sum %g  pointer_sum %g  speed %g\n", nearest_sum, pointer_sum, speed);
666                         }
667                     }
669                     if (   dc->hatch_escaped  // already escaped, do not reattach
670                         || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
671                         || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
672                         ) {
673                         // We are NOT attracted to the guide!
675                         //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);
677                         // Remember hatch_escaped so we don't get
678                         // attracted again until the end of this stroke
679                         dc->hatch_escaped = true;
681                     } else {
683                         // Calculate angle cosine of this vector-to-guide and all past vectors
684                         // summed, to detect if we accidentally flipped to the other side of the
685                         // guide
686                         double dot = Geom::dot (pointer - nearest, dc->hatch_vector_accumulated);
687                         dot /= Geom::L2(pointer - nearest) * Geom::L2(dc->hatch_vector_accumulated);
689                         if (dc->hatch_spacing != 0) { // spacing was already set
690                             double target;
691                             if (speed > SPEED_NORMAL) {
692                                 // all ok, strictly obey the spacing
693                                 target = dc->hatch_spacing;
694                             } else {
695                                 // looks like we're starting to lose speed,
696                                 // so _gradually_ let go attraction to prevent jerks
697                                 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;                            
698                             }
699                             if (!IS_NAN(dot) && dot < -0.5) {// flip
700                                 target = -target;
701                             }
703                             // This is the track pointer that we will use instead of the real one
704                             Geom::Point new_pointer = nearest + target * hatch_unit_vector;
706                             // some limited feedback: allow persistent pulling to slightly change
707                             // the spacing
708                             dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
710                             // return it to the desktop coords
711                             motion_dt = new_pointer * motion_to_curve.inverse();
713                         } else {
714                             // this is the first motion event, set the dist 
715                             dc->hatch_spacing = hatch_dist;
716                         }
718                         // remember last points
719                         dc->hatch_last_pointer = pointer;
720                         dc->hatch_last_nearest = nearest;
721                         dc->hatch_vector_accumulated += (pointer - nearest);
722                     }
724                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
726                 } else {
727                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
728                 }
730                 if (!sp_dyna_draw_apply(dc, motion_dt)) {
731                     ret = TRUE;
732                     break;
733                 }
735                 if ( dc->cur != dc->last ) {
736                     sp_dyna_draw_brush(dc);
737                     g_assert( dc->npoints > 0 );
738                     fit_and_split(dc, FALSE);
739                 }
740                 ret = TRUE;
741             }
743             // Draw the hatching circle if necessary
744             if (event->motion.state & GDK_CONTROL_MASK) { 
745                 if (dc->hatch_spacing == 0 && hatch_dist != 0) { 
746                     // Haven't set spacing yet: gray, center free, update radius live
747                     Geom::Point c = desktop->w2d(motion_w);
748                     Geom::Matrix const sm (Geom::Scale(hatch_dist, hatch_dist) * Geom::Translate(c));
749                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
750                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
751                     sp_canvas_item_show(dc->hatch_area);
752                 } else if (dc->dragging && !dc->hatch_escaped) {
753                     // Tracking: green, center snapped, fixed radius
754                     Geom::Point c = motion_dt;
755                     Geom::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
756                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
757                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
758                     sp_canvas_item_show(dc->hatch_area);
759                 } else if (dc->dragging && dc->hatch_escaped) {
760                     // Tracking escaped: red, center free, fixed radius
761                     Geom::Point c = desktop->w2d(motion_w);
762                     Geom::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
764                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
765                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
766                     sp_canvas_item_show(dc->hatch_area);
767                 } else {
768                     // Not drawing but spacing set: gray, center snapped, fixed radius
769                     Geom::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
770                     if (!IS_NAN(c[Geom::X]) && !IS_NAN(c[Geom::Y])) {
771                         Geom::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
772                         sp_canvas_item_affine_absolute(dc->hatch_area, sm);
773                         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
774                         sp_canvas_item_show(dc->hatch_area);
775                     }
776                 }
777             } else {
778                 sp_canvas_item_hide(dc->hatch_area);
779             }
780         }
781         break;
784     case GDK_BUTTON_RELEASE:
785     {
786         Geom::Point const motion_w(event->button.x, event->button.y);
787         Geom::Point const motion_dt(desktop->w2d(motion_w));
789         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
790         sp_canvas_end_forced_full_redraws(desktop->canvas);
791         dc->is_drawing = false;
793         if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
794             dc->dragging = FALSE;
796             sp_dyna_draw_apply(dc, motion_dt);
798             /* Remove all temporary line segments */
799             while (dc->segments) {
800                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
801                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
802             }
804             /* Create object */
805             fit_and_split(dc, TRUE);
806             if (accumulate_calligraphic(dc))
807                 set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK); // performs document_done
808             else
809                 g_warning ("Failed to create path: invalid data in dc->cal1 or dc->cal2");
811             /* reset accumulated curve */
812             dc->accumulated->reset();
814             clear_current(dc);
815             if (dc->repr) {
816                 dc->repr = NULL;
817             }
819             if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
820             if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
821             dc->hatch_last_nearest = Geom::Point(0,0);
822             dc->hatch_last_pointer = Geom::Point(0,0);
823             dc->hatch_vector_accumulated = Geom::Point(0,0);
824             dc->hatch_escaped = false;
825             dc->hatch_item = NULL;
826             dc->hatch_livarot_path = NULL;
828             if (dc->hatch_spacing != 0 && !dc->keep_selected) { 
829                 // we do not select the newly drawn path, so increase spacing by step
830                 if (dc->hatch_spacing_step == 0) {
831                     dc->hatch_spacing_step = dc->hatch_spacing;
832                 }
833                 dc->hatch_spacing += dc->hatch_spacing_step;
834             }
836             dc->_message_context->clear();
837             ret = TRUE;
838         }
839         break;
840     }
842     case GDK_KEY_PRESS:
843         switch (get_group0_keyval (&event->key)) {
844         case GDK_Up:
845         case GDK_KP_Up:
846             if (!MOD__CTRL_ONLY) {
847                 dc->angle += 5.0;
848                 if (dc->angle > 90.0)
849                     dc->angle = 90.0;
850                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
851                 ret = TRUE;
852             }
853             break;
854         case GDK_Down:
855         case GDK_KP_Down:
856             if (!MOD__CTRL_ONLY) {
857                 dc->angle -= 5.0;
858                 if (dc->angle < -90.0)
859                     dc->angle = -90.0;
860                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
861                 ret = TRUE;
862             }
863             break;
864         case GDK_Right:
865         case GDK_KP_Right:
866             if (!MOD__CTRL_ONLY) {
867                 dc->width += 0.01;
868                 if (dc->width > 1.0)
869                     dc->width = 1.0;
870                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
871                 ret = TRUE;
872             }
873             break;
874         case GDK_Left:
875         case GDK_KP_Left:
876             if (!MOD__CTRL_ONLY) {
877                 dc->width -= 0.01;
878                 if (dc->width < 0.01)
879                     dc->width = 0.01;
880                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
881                 ret = TRUE;
882             }
883             break;
884         case GDK_Home:
885         case GDK_KP_Home:
886             dc->width = 0.01;
887             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
888             ret = TRUE;
889             break;
890         case GDK_End:
891         case GDK_KP_End:
892             dc->width = 1.0;
893             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
894             ret = TRUE;
895             break;
896         case GDK_x:
897         case GDK_X:
898             if (MOD__ALT_ONLY) {
899                 desktop->setToolboxFocusTo ("altx-calligraphy");
900                 ret = TRUE;
901             }
902             break;
903         case GDK_Escape:
904             if (dc->is_drawing) {
905                 // if drawing, cancel, otherwise pass it up for deselecting
906                 calligraphic_cancel (dc);
907                 ret = TRUE;
908             }
909             break;
910         case GDK_z:
911         case GDK_Z:
912             if (MOD__CTRL_ONLY && dc->is_drawing) {
913                 // if drawing, cancel, otherwise pass it up for undo
914                 calligraphic_cancel (dc);
915                 ret = TRUE;
916             }
917             break;
918         default:
919             break;
920         }
921         break;
923     case GDK_KEY_RELEASE:
924         switch (get_group0_keyval(&event->key)) {
925             case GDK_Control_L:
926             case GDK_Control_R:
927                 dc->_message_context->clear();
928                 dc->hatch_spacing = 0;
929                 dc->hatch_spacing_step = 0;
930                 break;
931             default:
932                 break;
933         }
935     default:
936         break;
937     }
939     if (!ret) {
940         if (((SPEventContextClass *) dd_parent_class)->root_handler) {
941             ret = ((SPEventContextClass *) dd_parent_class)->root_handler(event_context, event);
942         }
943     }
945     return ret;
949 static void
950 clear_current(SPDynaDrawContext *dc)
952     /* reset bpath */
953     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
954     /* reset curve */
955     dc->currentcurve->reset();
956     dc->cal1->reset();
957     dc->cal2->reset();
958     /* reset points */
959     dc->npoints = 0;
962 static void
963 set_to_accumulated(SPDynaDrawContext *dc, bool unionize)
965     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
967     if (!dc->accumulated->is_empty()) {
968         if (!dc->repr) {
969             /* Create object */
970             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
971             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
973             /* Set style */
974             sp_desktop_apply_style_tool (desktop, repr, "/tools/calligraphic", false);
976             dc->repr = repr;
978             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
979             Inkscape::GC::release(dc->repr);
980             item->transform = sp_item_i2doc_affine(SP_ITEM(desktop->currentLayer())).inverse();
981             item->updateRepr();
982         }
983         Geom::PathVector pathv = dc->accumulated->get_pathvector() * sp_desktop_dt2doc_affine(desktop);
984         gchar *str = sp_svg_write_path(pathv);
985         g_assert( str != NULL );
986         dc->repr->setAttribute("d", str);
987         g_free(str);
989         if (unionize) {
990             sp_desktop_selection(desktop)->add(dc->repr);
991             sp_selected_path_union_skip_undo(desktop);
992         } else {
993             if (dc->keep_selected) {
994                 sp_desktop_selection(desktop)->set(dc->repr);
995             } 
996         }
998     } else {
999         if (dc->repr) {
1000             sp_repr_unparent(dc->repr);
1001         }
1002         dc->repr = NULL;
1003     }
1005     sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC, 
1006                      _("Draw calligraphic stroke"));
1009 static void
1010 add_cap(SPCurve *curve,
1011         Geom::Point const &from,
1012         Geom::Point const &to, 
1013         double rounding)
1015     if (Geom::L2( to - from ) > DYNA_EPSILON) {
1016         Geom::Point vel = rounding * Geom::rot90( to - from ) / sqrt(2.0);
1017         double mag = Geom::L2(vel);
1019         Geom::Point v = mag * Geom::rot90( to - from ) / Geom::L2( to - from );
1020         curve->curveto(from + v, to + v, to);
1021     }
1024 static bool
1025 accumulate_calligraphic(SPDynaDrawContext *dc)
1027         if (
1028             dc->cal1->is_empty() ||
1029             dc->cal2->is_empty() ||
1030             (dc->cal1->get_segment_count() <= 0) ||
1031             dc->cal1->first_path()->closed() 
1032             ) {
1033             dc->cal1->reset();
1034             dc->cal2->reset();
1035             return false; // failure
1036         }
1038         SPCurve *rev_cal2 = dc->cal2->create_reverse();
1039         if (
1040             (rev_cal2->get_segment_count() <= 0) ||
1041             rev_cal2->first_path()->closed() 
1042             ) {
1043             rev_cal2->unref();
1044             dc->cal1->reset();
1045             dc->cal2->reset();
1046             return false; // failure
1047         }
1049         Geom::CubicBezier const * dc_cal1_firstseg  = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->first_segment() );
1050         Geom::CubicBezier const * rev_cal2_firstseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->first_segment() );
1051         Geom::CubicBezier const * dc_cal1_lastseg   = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->last_segment() );
1052         Geom::CubicBezier const * rev_cal2_lastseg  = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->last_segment() );
1054         if (
1055             !dc_cal1_firstseg ||
1056             !rev_cal2_firstseg ||
1057             !dc_cal1_lastseg ||
1058             !rev_cal2_lastseg 
1059             ) {
1060             rev_cal2->unref();
1061             dc->cal1->reset();
1062             dc->cal2->reset();
1063             return false; // failure
1064         }
1066         dc->accumulated->reset(); /*  Is this required ?? */
1068         dc->accumulated->append(dc->cal1, false);
1070         add_cap(dc->accumulated, (*dc_cal1_lastseg)[3], (*rev_cal2_firstseg)[0], dc->cap_rounding);
1072         dc->accumulated->append(rev_cal2, true);
1074         add_cap(dc->accumulated, (*rev_cal2_lastseg)[3], (*dc_cal1_firstseg)[0], dc->cap_rounding);
1076         dc->accumulated->closepath();
1078         rev_cal2->unref();
1080         dc->cal1->reset();
1081         dc->cal2->reset();
1083         return true; // success
1086 static double square(double const x)
1088     return x * x;
1091 static void
1092 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1094     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1096     double const tolerance_sq = square( desktop->w2d().descrim() * TOLERANCE_CALLIGRAPHIC );
1098 #ifdef DYNA_DRAW_VERBOSE
1099     g_print("[F&S:R=%c]", release?'T':'F');
1100 #endif
1102     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1103         return; // just clicked
1105     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1106 #define BEZIER_SIZE       4
1107 #define BEZIER_MAX_BEZIERS  8
1108 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1110 #ifdef DYNA_DRAW_VERBOSE
1111         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1112                 dc->npoints, release ? "TRUE" : "FALSE");
1113 #endif
1115         /* Current calligraphic */
1116         if ( dc->cal1->is_empty() || dc->cal2->is_empty() ) {
1117             /* dc->npoints > 0 */
1118             /* g_print("calligraphics(1|2) reset\n"); */
1119             dc->cal1->reset();
1120             dc->cal2->reset();
1122             dc->cal1->moveto(dc->point1[0]);
1123             dc->cal2->moveto(dc->point2[0]);
1124         }
1126         Geom::Point b1[BEZIER_MAX_LENGTH];
1127         gint const nb1 = Geom::bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1128                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1129         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1131         Geom::Point b2[BEZIER_MAX_LENGTH];
1132         gint const nb2 = Geom::bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1133                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1134         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1136         if ( nb1 != -1 && nb2 != -1 ) {
1137             /* Fit and draw and reset state */
1138 #ifdef DYNA_DRAW_VERBOSE
1139             g_print("nb1:%d nb2:%d\n", nb1, nb2);
1140 #endif
1141             /* CanvasShape */
1142             if (! release) {
1143                 dc->currentcurve->reset();
1144                 dc->currentcurve->moveto(b1[0]);
1145                 for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1146                     dc->currentcurve->curveto(bp1[1], bp1[2], bp1[3]);
1147                 }
1148                 dc->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]);
1149                 for (Geom::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1150                     dc->currentcurve->curveto(bp2[2], bp2[1], bp2[0]);
1151                 }
1152                 // FIXME: dc->segments is always NULL at this point??
1153                 if (!dc->segments) { // first segment
1154                     add_cap(dc->currentcurve, b2[0], b1[0], dc->cap_rounding);
1155                 }
1156                 dc->currentcurve->closepath();
1157                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1158             }
1160             /* Current calligraphic */
1161             for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1162                 dc->cal1->curveto(bp1[1], bp1[2], bp1[3]);
1163             }
1164             for (Geom::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1165                 dc->cal2->curveto(bp2[1], bp2[2], bp2[3]);
1166             }
1167         } else {
1168             /* fixme: ??? */
1169 #ifdef DYNA_DRAW_VERBOSE
1170             g_print("[fit_and_split] failed to fit-cubic.\n");
1171 #endif
1172             draw_temporary_box(dc);
1174             for (gint i = 1; i < dc->npoints; i++) {
1175                 dc->cal1->lineto(dc->point1[i]);
1176             }
1177             for (gint i = 1; i < dc->npoints; i++) {
1178                 dc->cal2->lineto(dc->point2[i]);
1179             }
1180         }
1182         /* Fit and draw and copy last point */
1183 #ifdef DYNA_DRAW_VERBOSE
1184         g_print("[%d]Yup\n", dc->npoints);
1185 #endif
1186         if (!release) {
1187             g_assert(!dc->currentcurve->is_empty());
1189             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(desktop),
1190                                                    SP_TYPE_CANVAS_BPATH,
1191                                                    NULL);
1192             SPCurve *curve = dc->currentcurve->copy();
1193             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1194             curve->unref();
1196             guint32 fillColor = sp_desktop_get_color_tool (desktop, "/tools/calligraphic", true);
1197             //guint32 strokeColor = sp_desktop_get_color_tool (desktop, "/tools/calligraphic", false);
1198             double opacity = sp_desktop_get_master_opacity_tool (desktop, "/tools/calligraphic");
1199             double fillOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/calligraphic", true);
1200             //double strokeOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/calligraphic", false);
1201             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1202             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1203             //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);
1204             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1205             /* fixme: Cannot we cascade it to root more clearly? */
1206             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), desktop);
1208             dc->segments = g_slist_prepend(dc->segments, cbp);
1209         }
1211         dc->point1[0] = dc->point1[dc->npoints - 1];
1212         dc->point2[0] = dc->point2[dc->npoints - 1];
1213         dc->npoints = 1;
1214     } else {
1215         draw_temporary_box(dc);
1216     }
1219 static void
1220 draw_temporary_box(SPDynaDrawContext *dc)
1222     dc->currentcurve->reset();
1224     dc->currentcurve->moveto(dc->point2[dc->npoints-1]);
1225     for (gint i = dc->npoints-2; i >= 0; i--) {
1226         dc->currentcurve->lineto(dc->point2[i]);
1227     }
1228     for (gint i = 0; i < dc->npoints; i++) {
1229         dc->currentcurve->lineto(dc->point1[i]);
1230     }
1232     if (dc->npoints >= 2) {
1233         add_cap(dc->currentcurve, dc->point1[dc->npoints-1], dc->point2[dc->npoints-1], dc->cap_rounding);
1234     }
1236     dc->currentcurve->closepath();
1237     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1240 /*
1241   Local Variables:
1242   mode:c++
1243   c-file-style:"stroustrup"
1244   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1245   indent-tabs-mode:nil
1246   fill-column:99
1247   End:
1248 */
1249 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :