Code

fix thinning that didn't work for paths inside a transformed group
[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>
32 #include <numeric>
34 #include "svg/svg.h"
35 #include "display/canvas-bpath.h"
36 #include "display/bezier-utils.h"
38 #include <glib/gmem.h>
39 #include "macros.h"
40 #include "document.h"
41 #include "selection.h"
42 #include "desktop.h"
43 #include "desktop-events.h"
44 #include "desktop-handles.h"
45 #include "desktop-affine.h"
46 #include "desktop-style.h"
47 #include "message-context.h"
48 #include "pixmaps/cursor-calligraphy.xpm"
49 #include "pixmaps/cursor-thin.xpm"
50 #include "pixmaps/cursor-thicken.xpm"
51 #include "libnr/n-art-bpath.h"
52 #include "libnr/nr-path.h"
53 #include "libnr/nr-matrix-ops.h"
54 #include "libnr/nr-scale-translate-ops.h"
55 #include "xml/repr.h"
56 #include "context-fns.h"
57 #include "sp-item.h"
58 #include "inkscape.h"
59 #include "color.h"
60 #include "splivarot.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 "isnan.h"
69 #include "dyna-draw-context.h"
71 #define DDC_RED_RGBA 0xff0000ff
73 #define TOLERANCE_CALLIGRAPHIC 0.1
75 #define DYNA_EPSILON 0.5e-6
76 #define DYNA_EPSILON_START 0.5e-2
77 #define DYNA_VEL_START 1e-5
79 #define DYNA_MIN_WIDTH 1.0e-6
81 #define DRAG_MIN 0.0
82 #define DRAG_DEFAULT 1.0
83 #define DRAG_MAX 1.0
85 // FIXME: move it to some shared file to be reused by both calligraphy and dropper
86 #define C1 0.552
87 static NArtBpath const hatch_area_circle[] = {
88     { NR_MOVETO, 0, 0, 0, 0, -1, 0 },
89     { NR_CURVETO, -1, C1, -C1, 1, 0, 1 },
90     { NR_CURVETO, C1, 1, 1, C1, 1, 0 },
91     { NR_CURVETO, 1, -C1, C1, -1, 0, -1 },
92     { NR_CURVETO, -C1, -1, -1, -C1, -1, 0 },
93     { NR_END, 0, 0, 0, 0, 0, 0 }
94 };
95 #undef C1
98 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
99 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
100 static void sp_dyna_draw_context_dispose(GObject *object);
102 static void sp_dyna_draw_context_setup(SPEventContext *ec);
103 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
104 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
106 static void clear_current(SPDynaDrawContext *dc);
107 static void set_to_accumulated(SPDynaDrawContext *dc, bool unionize);
108 static void add_cap(SPCurve *curve, NR::Point const &pre, NR::Point const &from, NR::Point const &to, NR::Point const &post, double rounding);
109 static void accumulate_calligraphic(SPDynaDrawContext *dc);
111 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
113 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
114 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
115 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
116 static void draw_temporary_box(SPDynaDrawContext *dc);
119 static SPEventContextClass *parent_class;
121 GtkType
122 sp_dyna_draw_context_get_type(void)
124     static GType type = 0;
125     if (!type) {
126         GTypeInfo info = {
127             sizeof(SPDynaDrawContextClass),
128             NULL, NULL,
129             (GClassInitFunc) sp_dyna_draw_context_class_init,
130             NULL, NULL,
131             sizeof(SPDynaDrawContext),
132             4,
133             (GInstanceInitFunc) sp_dyna_draw_context_init,
134             NULL,   /* value_table */
135         };
136         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
137     }
138     return type;
141 static void
142 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
144     GObjectClass *object_class = (GObjectClass *) klass;
145     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
147     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
149     object_class->dispose = sp_dyna_draw_context_dispose;
151     event_context_class->setup = sp_dyna_draw_context_setup;
152     event_context_class->set = sp_dyna_draw_context_set;
153     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
156 static void
157 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
159     SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
161     event_context->cursor_shape = cursor_calligraphy_xpm;
162     event_context->hot_x = 4;
163     event_context->hot_y = 4;
165     ddc->accumulated = NULL;
166     ddc->segments = NULL;
167     ddc->currentcurve = NULL;
168     ddc->currentshape = NULL;
169     ddc->npoints = 0;
170     ddc->cal1 = NULL;
171     ddc->cal2 = NULL;
172     ddc->repr = NULL;
174     /* DynaDraw values */
175     ddc->cur = NR::Point(0,0);
176     ddc->last = NR::Point(0,0);
177     ddc->vel = NR::Point(0,0);
178     ddc->vel_max = 0;
179     ddc->acc = NR::Point(0,0);
180     ddc->ang = NR::Point(0,0);
181     ddc->del = NR::Point(0,0);
183     /* attributes */
184     ddc->dragging = FALSE;
186     ddc->mass = 0.3;
187     ddc->drag = DRAG_DEFAULT;
188     ddc->angle = 30.0;
189     ddc->width = 0.2;
190     ddc->pressure = DDC_DEFAULT_PRESSURE;
192     ddc->vel_thin = 0.1;
193     ddc->flatness = 0.9;
194     ddc->cap_rounding = 0.0;
196     ddc->abs_width = false;
197     ddc->keep_selected = true;
199     ddc->hatch_spacing = 0;
200     new (&ddc->hatch_pointer_past) std::list<double>();
201     new (&ddc->hatch_nearest_past) std::list<double>();
202     ddc->hatch_last_nearest = NR::Point(0,0);
203     ddc->hatch_last_pointer = NR::Point(0,0);
204     ddc->hatch_vector_accumulated = NR::Point(0,0);
205     ddc->hatch_escaped = false;
206     ddc->hatch_area = NULL;
207     ddc->hatch_item = NULL;
208     ddc->hatch_livarot_path = NULL;
210     ddc->trace_bg = false;
212     ddc->is_dilating = false;
215 static void
216 sp_dyna_draw_context_dispose(GObject *object)
218     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
220     if (ddc->hatch_area) {
221         gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
222         ddc->hatch_area = NULL;
223     }
225     if (ddc->dilate_area) {
226         gtk_object_destroy(GTK_OBJECT(ddc->dilate_area));
227         ddc->dilate_area = NULL;
228     }
230     if (ddc->accumulated) {
231         ddc->accumulated = sp_curve_unref(ddc->accumulated);
232     }
234     while (ddc->segments) {
235         gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
236         ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
237     }
239     if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
240     if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
241     if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
243     if (ddc->currentshape) {
244         gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
245         ddc->currentshape = NULL;
246     }
248     if (ddc->_message_context) {
249         delete ddc->_message_context;
250     }
252     G_OBJECT_CLASS(parent_class)->dispose(object);
254     ddc->hatch_pointer_past.~list();
255     ddc->hatch_nearest_past.~list();
258 static void
259 sp_dyna_draw_context_setup(SPEventContext *ec)
261     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
263     if (((SPEventContextClass *) parent_class)->setup)
264         ((SPEventContextClass *) parent_class)->setup(ec);
266     ddc->accumulated = sp_curve_new_sized(32);
267     ddc->currentcurve = sp_curve_new_sized(4);
269     ddc->cal1 = sp_curve_new_sized(32);
270     ddc->cal2 = sp_curve_new_sized(32);
272     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
273     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
274     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
275     /* fixme: Cannot we cascade it to root more clearly? */
276     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
278     {
279         SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
280         ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
281         sp_curve_unref(c);
282         sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
283         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
284         sp_canvas_item_hide(ddc->hatch_area);
285     }
287     {
288         SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
289         ddc->dilate_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
290         sp_curve_unref(c);
291         sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->dilate_area), 0x00000000,(SPWindRule)0);
292         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->dilate_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
293         sp_canvas_item_hide(ddc->dilate_area);
294     }
296     sp_event_context_read(ec, "mass");
297     sp_event_context_read(ec, "wiggle");
298     sp_event_context_read(ec, "angle");
299     sp_event_context_read(ec, "width");
300     sp_event_context_read(ec, "thinning");
301     sp_event_context_read(ec, "tremor");
302     sp_event_context_read(ec, "flatness");
303     sp_event_context_read(ec, "tracebackground");
304     sp_event_context_read(ec, "usepressure");
305     sp_event_context_read(ec, "usetilt");
306     sp_event_context_read(ec, "abs_width");
307     sp_event_context_read(ec, "keep_selected");
308     sp_event_context_read(ec, "cap_rounding");
310     ddc->is_drawing = false;
312     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
315 static void
316 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
318     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
320     if (!strcmp(key, "mass")) {
321         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
322         ddc->mass = CLAMP(dval, -1000.0, 1000.0);
323     } else if (!strcmp(key, "wiggle")) {
324         double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
325         ddc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
326     } else if (!strcmp(key, "angle")) {
327         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
328         ddc->angle = CLAMP (dval, -90, 90);
329     } else if (!strcmp(key, "width")) {
330         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
331         ddc->width = CLAMP(dval, -1000.0, 1000.0);
332     } else if (!strcmp(key, "thinning")) {
333         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
334         ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
335     } else if (!strcmp(key, "tremor")) {
336         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
337         ddc->tremor = CLAMP(dval, 0.0, 1.0);
338     } else if (!strcmp(key, "flatness")) {
339         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
340         ddc->flatness = CLAMP(dval, 0, 1.0);
341     } else if (!strcmp(key, "tracebackground")) {
342         ddc->trace_bg = (val && strcmp(val, "0"));
343     } else if (!strcmp(key, "usepressure")) {
344         ddc->usepressure = (val && strcmp(val, "0"));
345     } else if (!strcmp(key, "usetilt")) {
346         ddc->usetilt = (val && strcmp(val, "0"));
347     } else if (!strcmp(key, "abs_width")) {
348         ddc->abs_width = (val && strcmp(val, "0"));
349     } else if (!strcmp(key, "keep_selected")) {
350         ddc->keep_selected = (val && strcmp(val, "0"));
351     } else if (!strcmp(key, "cap_rounding")) {
352         ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
353     }
355     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
358 static double
359 flerp(double f0, double f1, double p)
361     return f0 + ( f1 - f0 ) * p;
364 /* Get normalized point */
365 static NR::Point
366 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
368     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
369     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
370     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
373 /* Get view point */
374 static NR::Point
375 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
377     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
378     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
379     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
382 static void
383 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
385     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
386     dc->vel = NR::Point(0,0);
387     dc->vel_max = 0;
388     dc->acc = NR::Point(0,0);
389     dc->ang = NR::Point(0,0);
390     dc->del = NR::Point(0,0);
393 static void
394 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
396     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
397         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
398     else
399         dc->pressure = DDC_DEFAULT_PRESSURE;
401     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
402         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
403     else
404         dc->xtilt = DDC_DEFAULT_TILT;
406     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
407         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
408     else
409         dc->ytilt = DDC_DEFAULT_TILT;
413 static gboolean
414 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
416     NR::Point n = sp_dyna_draw_get_npoint(dc, p);
418     /* Calculate mass and drag */
419     double const mass = flerp(1.0, 160.0, dc->mass);
420     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
422     /* Calculate force and acceleration */
423     NR::Point force = n - dc->cur;
425     // If force is below the absolute threshold DYNA_EPSILON,
426     // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
427     // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
428     // discard this move. 
429     // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
430     // especially bothersome at the start of the stroke where we don't yet have the inertia to
431     // smooth them out.
432     if ( NR::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && NR::L2(force) < DYNA_EPSILON_START)) {
433         return FALSE;
434     }
436     dc->acc = force / mass;
438     /* Calculate new velocity */
439     dc->vel += dc->acc;
441     if (NR::L2(dc->vel) > dc->vel_max)
442         dc->vel_max = NR::L2(dc->vel);
444     /* Calculate angle of drawing tool */
446     double a1;
447     if (dc->usetilt) {
448         // 1a. calculate nib angle from input device tilt:
449         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
451         if (length > 0) {
452             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
453             a1 = atan2(ang1);
454         }
455         else
456             a1 = 0.0;
457     }
458     else {
459         // 1b. fixed dc->angle (absolutely flat nib):
460         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
461         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
462         a1 = atan2(ang1);
463     }
465     // 2. perpendicular to dc->vel (absolutely non-flat nib):
466     gdouble const mag_vel = NR::L2(dc->vel);
467     if ( mag_vel < DYNA_EPSILON ) {
468         return FALSE;
469     }
470     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
472     // 3. Average them using flatness parameter:
473     // calculate angles
474     double a2 = atan2(ang2);
475     // flip a2 to force it to be in the same half-circle as a1
476     bool flipped = false;
477     if (fabs (a2-a1) > 0.5*M_PI) {
478         a2 += M_PI;
479         flipped = true;
480     }
481     // normalize a2
482     if (a2 > M_PI)
483         a2 -= 2*M_PI;
484     if (a2 < -M_PI)
485         a2 += 2*M_PI;
486     // find the flatness-weighted bisector angle, unflip if a2 was flipped
487     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
488     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
490     // Try to detect a sudden flip when the new angle differs too much from the previous for the
491     // current velocity; in that case discard this move
492     double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
493     if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
494         return FALSE;
495     }
497     // convert to point
498     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
500 //    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);
502     /* Apply drag */
503     dc->vel *= 1.0 - drag;
505     /* Update position */
506     dc->last = dc->cur;
507     dc->cur += dc->vel;
509     return TRUE;
512 static void
513 sp_dyna_draw_brush(SPDynaDrawContext *dc)
515     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
517     // How much velocity thins strokestyle
518     double vel_thin = flerp (0, 160, dc->vel_thin);
520     // Influence of pressure on thickness
521     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
523     // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
524     // drag)
525     NR::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
526     NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush); 
528     double trace_thick = 1;
529     if (dc->trace_bg) {
530         // pick single pixel
531         NRPixBlock pb;
532         int x = (int) floor(brush_w[NR::X]);
533         int y = (int) floor(brush_w[NR::Y]);
534         nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
535         sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
536         const unsigned char *s = NR_PIXBLOCK_PX(&pb);
537         double R = s[0] / 255.0;
538         double G = s[1] / 255.0;
539         double B = s[2] / 255.0;
540         double A = s[3] / 255.0;
541         double max = MAX (MAX (R, G), B);
542         double min = MIN (MIN (R, G), B);
543         double L = A * (max + min)/2 + (1 - A); // blend with white bg
544         trace_thick = 1 - L;
545         //g_print ("L %g thick %g\n", L, trace_thick);
546     }
548     double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
550     double tremble_left = 0, tremble_right = 0;
551     if (dc->tremor > 0) {
552         // obtain two normally distributed random variables, using polar Box-Muller transform
553         double x1, x2, w, y1, y2;
554         do {
555             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
556             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
557             w = x1 * x1 + x2 * x2;
558         } while ( w >= 1.0 );
559         w = sqrt( (-2.0 * log( w ) ) / w );
560         y1 = x1 * w;
561         y2 = x2 * w;
563         // deflect both left and right edges randomly and independently, so that:
564         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
565         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
566         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
567         // comparatively smooth and slow ones excessively jittery
568         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
569         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
570     }
572     if ( width < 0.02 * dc->width ) {
573         width = 0.02 * dc->width;
574     }
576     double dezoomify_factor = 0.05 * 1000;
577     if (!dc->abs_width) {
578         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
579     }
581     NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
582     NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
584     dc->point1[dc->npoints] = brush + del_left;
585     dc->point2[dc->npoints] = brush - del_right;
587     dc->del = 0.5*(del_left + del_right);
589     dc->npoints++;
592 double
593 get_dilate_radius (SPDynaDrawContext *dc)
595     // 10 times the pen width:
596     return 500 * dc->width/SP_EVENT_CONTEXT(dc)->desktop->current_zoom(); 
599 double
600 get_dilate_force (SPDynaDrawContext *dc)
602     return 8 * dc->pressure/SP_EVENT_CONTEXT(dc)->desktop->current_zoom(); 
605 bool
606 sp_ddc_dilate (SPDynaDrawContext *dc, NR::Point p, bool expand)
608     Inkscape::Selection *selection = sp_desktop_selection(SP_EVENT_CONTEXT(dc)->desktop);
610     if (selection->isEmpty()) {
611         return false;
612     }
614     bool did = false;
615     double radius = get_dilate_radius(dc); 
616     double offset = get_dilate_force(dc); 
618     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
619          items != NULL;
620          items = items->next) {
622         SPItem *item = (SPItem *) items->data;
624         // only paths
625         if (!SP_IS_PATH(item))
626             continue;
628         SPCurve *curve = NULL;
629         curve = sp_shape_get_curve(SP_SHAPE(item));
630         if (curve == NULL)
631             continue;
633         // skip those paths whose bboxes are entirely out of reach with our radius
634         NR::Maybe<NR::Rect> bbox = item->getBounds(sp_item_i2doc_affine(item));
635         if (bbox) {
636             bbox->growBy(radius);
637             if (!bbox->contains(p)) {
638                 continue;
639             }
640         }
642         Path *orig = Path_for_item(item, false);
643         if (orig == NULL) {
644             sp_curve_unref(curve);
645             continue;
646         }
647         Path *res = new Path;
648         res->SetBackData(false);
650         Shape *theShape = new Shape;
651         Shape *theRes = new Shape;
653         orig->ConvertWithBackData(0.05);
654         orig->Fill(theShape, 0);
656         SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
657         gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
658         if (val && strcmp(val, "nonzero") == 0)
659         {
660             theRes->ConvertToShape(theShape, fill_nonZero);
661         }
662         else if (val && strcmp(val, "evenodd") == 0)
663         {
664             theRes->ConvertToShape(theShape, fill_oddEven);
665         }
666         else
667         {
668             theRes->ConvertToShape(theShape, fill_nonZero);
669         }
671         bool did_this = false;
672         NR::Matrix i2doc(sp_item_i2doc_affine(item));
673         if (theShape->MakeOffset(theRes, 
674                                  expand? offset : -offset,
675                                  join_straight, butt_straight,
676                                  true, p[NR::X], p[NR::Y], radius, &i2doc) == 0) // 0 means the shape was actually changed
677             did_this = true;
679         // the rest only makes sense if we actually changed the path
680         if (did_this) {
681             theRes->ConvertToShape(theShape, fill_positive);
683             res->Reset();
684             theRes->ConvertToForme(res);
686             if (offset >= 0.5)
687             {
688                 res->ConvertEvenLines(0.5);
689                 res->Simplify(0.5);
690             }
691             else
692             {
693                 res->ConvertEvenLines(0.5*offset);
694                 res->Simplify(0.5 * offset);
695             }
697             sp_curve_unref(curve);
698             if (res->descr_cmd.size() > 1) { 
699                 gchar *str = res->svg_dump_path();
700                 SP_OBJECT_REPR(item)->setAttribute("d", str);
701                 g_free(str);
702             } else {
703                 // TODO: if there's 0 or 1 node left, delete this path altogether
704             }
705         }
707         delete theShape;
708         delete theRes;
709         delete orig;
710         delete res;
712         if (did_this) 
713             did = true;
714     }
716     return did;
719 void
720 sp_ddc_update_cursors (SPDynaDrawContext *dc)
722     if (dc->is_dilating) {
723         double radius = get_dilate_radius(dc);
724         NR::Matrix const sm (NR::scale(radius, radius) * NR::translate(SP_EVENT_CONTEXT(dc)->desktop->point()));
725         sp_canvas_item_affine_absolute(dc->dilate_area, sm);
726         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
727         sp_canvas_item_show(dc->dilate_area);
728     }
731 void
732 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
734     desktop->setToolboxAdjustmentValue (id, value);
737 static void
738 calligraphic_cancel(SPDynaDrawContext *dc)
740     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
741     dc->dragging = FALSE;
742     dc->is_drawing = false;
743     sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
744             /* Remove all temporary line segments */
745             while (dc->segments) {
746                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
747                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
748             }
749             /* reset accumulated curve */
750             sp_curve_reset(dc->accumulated);
751             clear_current(dc);
752             if (dc->repr) {
753                 dc->repr = NULL;
754             }
758 gint
759 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
760                                   GdkEvent *event)
762     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
763     SPDesktop *desktop = event_context->desktop;
765     gint ret = FALSE;
767     switch (event->type) {
768         case GDK_BUTTON_PRESS:
769             if ( event->button.button == 1 ) {
771                 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
773                 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
774                     return TRUE;
775                 }
777                 NR::Point const button_w(event->button.x,
778                                          event->button.y);
779                 NR::Point const button_dt(desktop->w2d(button_w));
780                 sp_dyna_draw_reset(dc, button_dt);
781                 sp_dyna_draw_extinput(dc, event);
782                 sp_dyna_draw_apply(dc, button_dt);
783                 sp_curve_reset(dc->accumulated);
784                 if (dc->repr) {
785                     dc->repr = NULL;
786                 }
788                 /* initialize first point */
789                 dc->npoints = 0;
791                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
792                                     ( GDK_KEY_PRESS_MASK |
793                                       GDK_BUTTON_RELEASE_MASK |
794                                       GDK_POINTER_MOTION_MASK |
795                                       GDK_BUTTON_PRESS_MASK ),
796                                     NULL,
797                                     event->button.time);
799                 ret = TRUE;
801                 dc->is_drawing = true;
802             }
803             break;
804         case GDK_MOTION_NOTIFY:
805         {
806             NR::Point const motion_w(event->motion.x,
807                                      event->motion.y);
808             NR::Point motion_dt(desktop->w2d(motion_w));
810             // draw the dilating cursor
811             if (event->motion.state & GDK_MOD1_MASK) {
812                 double radius = get_dilate_radius(dc);
813                 NR::Matrix const sm (NR::scale(radius, radius) * NR::translate(desktop->w2d(motion_w)));
814                 sp_canvas_item_affine_absolute(dc->dilate_area, sm);
815                 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
816                 sp_canvas_item_show(dc->dilate_area);
818                 guint num = 0;
819                 if (!desktop->selection->isEmpty()) {
820                     num = g_slist_length((GSList *) desktop->selection->itemList());
821                 }
822                 if (num == 0) {
823                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select paths</b> to thin or thicken"));
824                 } else {
825                     dc->_message_context->setF(Inkscape::NORMAL_MESSAGE,
826                                            event->motion.state & GDK_SHIFT_MASK?
827                                            _("<b>Thickening %d</b> selected paths; without <b>Shift</b> to thin") :
828                                            _("<b>Thinning %d</b> selected paths; with <b>Shift</b> to thicken"), num);
829                 }
831             } else {
832                 dc->_message_context->clear();
833                 sp_canvas_item_hide(dc->dilate_area);
834             }
836             // dilating:
837             if (dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) && event->motion.state & GDK_MOD1_MASK) {  
838                 sp_ddc_dilate (dc, desktop->dt2doc(motion_dt), event->motion.state & GDK_SHIFT_MASK? true : false);
839                 dc->is_dilating = true;
840                 // it's slow, so prevent clogging up with events
841                 gobble_motion_events(GDK_BUTTON1_MASK);
842                 return TRUE;
843             }
846             // for hatching:
847             double hatch_dist = 0;
848             NR::Point hatch_unit_vector(0,0);
849             NR::Point nearest(0,0);
850             NR::Point pointer(0,0);
851             NR::Matrix motion_to_curve(NR::identity());
853             if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
855                 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
856                 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
857                     // One item selected, and it's a path;
858                     // let's try to track it as a guide
860                     if (selected != dc->hatch_item) {
861                         dc->hatch_item = selected;
862                         if (dc->hatch_livarot_path)
863                             delete dc->hatch_livarot_path;
864                         dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
865                         dc->hatch_livarot_path->ConvertWithBackData(0.01);
866                     }
868                     // calculate pointer point in the guide item's coords
869                     motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
870                     pointer = motion_dt * motion_to_curve;
872                     // calculate the nearest point on the guide path
873                     NR::Maybe<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
874                     nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
877                     // distance from pointer to nearest
878                     hatch_dist = NR::L2(pointer - nearest);
879                     // unit-length vector
880                     hatch_unit_vector = (pointer - nearest)/hatch_dist;
882                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
883                 } else {
884                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
885                 }
886             } 
888             if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
889                 dc->dragging = TRUE;
891                 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
893 #define SPEED_ELEMENTS 12
894 #define SPEED_MIN 0.12
895 #define SPEED_NORMAL 0.65
897                     // speed is the movement of the nearest point along the guide path, divided by
898                     // the movement of the pointer at the same period; it is averaged for the last
899                     // SPEED_ELEMENTS motion events.  Normally, as you track the guide path, speed
900                     // is about 1, i.e. the nearest point on the path is moved by about the same
901                     // distance as the pointer. If the speed starts to decrease, we are losing
902                     // contact with the guide; if it drops below SPEED_MIN, we are on our own and
903                     // not attracted to guide anymore. Most often this happens when you have
904                     // tracked to the end of a guide calligraphic stroke and keep moving
905                     // further. We try to handle this situation gracefully: not stick with the
906                     // guide forever but let go of it smoothly and without sharp jerks (non-zero
907                     // mass recommended; with zero mass, jerks are still quite noticeable).
909                     double speed = 1;
910                     if (NR::L2(dc->hatch_last_nearest) != 0) {
911                         // the distance nearest moved since the last motion event
912                         double nearest_moved = NR::L2(nearest - dc->hatch_last_nearest);
913                         // the distance pointer moved since the last motion event
914                         double pointer_moved = NR::L2(pointer - dc->hatch_last_pointer);
915                         // store them in stacks limited to SPEED_ELEMENTS
916                         dc->hatch_nearest_past.push_front(nearest_moved);
917                         if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
918                             dc->hatch_nearest_past.pop_back();
919                         dc->hatch_pointer_past.push_front(pointer_moved);
920                         if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
921                             dc->hatch_pointer_past.pop_back();
923                         // If the stacks are full,
924                         if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
925                             // calculate the sums of all stored movements
926                             double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
927                             double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
928                             // and divide to get the speed
929                             speed = nearest_sum/pointer_sum;
930                             //g_print ("nearest sum %g  pointer_sum %g  speed %g\n", nearest_sum, pointer_sum, speed);
931                         }
932                     }
934                     if (   dc->hatch_escaped  // already escaped, do not reattach
935                         || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
936                         || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
937                         ) {
938                         // We are NOT attracted to the guide!
940                         //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);
942                         // Remember hatch_escaped so we don't get
943                         // attracted again until the end of this stroke
944                         dc->hatch_escaped = true;
946                     } else {
948                         // Calculate angle cosine of this vector-to-guide and all past vectors
949                         // summed, to detect if we accidentally flipped to the other side of the
950                         // guide
951                         double dot = NR::dot (pointer - nearest, dc->hatch_vector_accumulated);
952                         dot /= NR::L2(pointer - nearest) * NR::L2(dc->hatch_vector_accumulated);
954                         if (dc->hatch_spacing != 0) { // spacing was already set
955                             double target;
956                             if (speed > SPEED_NORMAL) {
957                                 // all ok, strictly obey the spacing
958                                 target = dc->hatch_spacing;
959                             } else {
960                                 // looks like we're starting to lose speed,
961                                 // so _gradually_ let go attraction to prevent jerks
962                                 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;                            
963                             }
964                             if (!isNaN(dot) && dot < -0.5) {// flip
965                                 target = -target;
966                             }
968                             // This is the track pointer that we will use instead of the real one
969                             NR::Point new_pointer = nearest + target * hatch_unit_vector;
971                             // some limited feedback: allow persistent pulling to slightly change
972                             // the spacing
973                             dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
975                             // return it to the desktop coords
976                             motion_dt = new_pointer * motion_to_curve.inverse();
978                         } else {
979                             // this is the first motion event, set the dist 
980                             dc->hatch_spacing = hatch_dist;
981                         }
983                         // remember last points
984                         dc->hatch_last_pointer = pointer;
985                         dc->hatch_last_nearest = nearest;
986                         dc->hatch_vector_accumulated += (pointer - nearest);
987                     }
989                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
991                 } else {
992                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
993                 }
995                 sp_dyna_draw_extinput(dc, event);
996                 if (!sp_dyna_draw_apply(dc, motion_dt)) {
997                     ret = TRUE;
998                     break;
999                 }
1001                 if ( dc->cur != dc->last ) {
1002                     sp_dyna_draw_brush(dc);
1003                     g_assert( dc->npoints > 0 );
1004                     fit_and_split(dc, FALSE);
1005                 }
1006                 ret = TRUE;
1007             }
1009             // Draw the hatching circle if necessary
1010             if (event->motion.state & GDK_CONTROL_MASK) { 
1011                 if (dc->hatch_spacing == 0 && hatch_dist != 0) { 
1012                     // Haven't set spacing yet: gray, center free, update radius live
1013                     NR::Point c = desktop->w2d(motion_w);
1014                     NR::Matrix const sm (NR::scale(hatch_dist, hatch_dist) * NR::translate(c));
1015                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1016                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1017                     sp_canvas_item_show(dc->hatch_area);
1018                 } else if (dc->dragging && !dc->hatch_escaped) {
1019                     // Tracking: green, center snapped, fixed radius
1020                     NR::Point c = motion_dt;
1021                     NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1022                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1023                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1024                     sp_canvas_item_show(dc->hatch_area);
1025                 } else if (dc->dragging && dc->hatch_escaped) {
1026                     // Tracking escaped: red, center free, fixed radius
1027                     NR::Point c = desktop->w2d(motion_w);
1028                     NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1030                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1031                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1032                     sp_canvas_item_show(dc->hatch_area);
1033                 } else {
1034                     // Not drawing but spacing set: gray, center snapped, fixed radius
1035                     NR::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
1036                     if (!isNaN(c[NR::X]) && !isNaN(c[NR::Y])) {
1037                         NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1038                         sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1039                         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1040                         sp_canvas_item_show(dc->hatch_area);
1041                     }
1042                 }
1043             } else {
1044                 sp_canvas_item_hide(dc->hatch_area);
1045             }
1046         }
1047         break;
1050     case GDK_BUTTON_RELEASE:
1051         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
1052         dc->is_drawing = false;
1054         if ( dc->is_dilating && event->button.button == 1 ) {
1055             dc->is_dilating = false;
1056             sp_document_done(sp_desktop_document(SP_EVENT_CONTEXT(dc)->desktop), 
1057                          SP_VERB_CONTEXT_CALLIGRAPHIC,
1058                          (event->button.state & GDK_SHIFT_MASK ? _("Thicken paths") : _("Thin paths")));
1059             ret = TRUE;
1060         } else if ( dc->dragging && event->button.button == 1 ) {
1061             dc->dragging = FALSE;
1063             NR::Point const motion_w(event->button.x, event->button.y);
1064             NR::Point const motion_dt(desktop->w2d(motion_w));
1065             sp_dyna_draw_apply(dc, motion_dt);
1067             /* Remove all temporary line segments */
1068             while (dc->segments) {
1069                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
1070                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
1071             }
1073             /* Create object */
1074             fit_and_split(dc, TRUE);
1075             accumulate_calligraphic(dc);
1076             set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK); // performs document_done
1078             /* reset accumulated curve */
1079             sp_curve_reset(dc->accumulated);
1081             clear_current(dc);
1082             if (dc->repr) {
1083                 dc->repr = NULL;
1084             }
1086             if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
1087             if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
1088             dc->hatch_last_nearest = NR::Point(0,0);
1089             dc->hatch_last_pointer = NR::Point(0,0);
1090             dc->hatch_vector_accumulated = NR::Point(0,0);
1091             dc->hatch_escaped = false;
1092             dc->hatch_item = NULL;
1093             dc->hatch_livarot_path = NULL;
1095             dc->_message_context->clear();
1096             ret = TRUE;
1097         }
1098         break;
1100     case GDK_KEY_PRESS:
1101         switch (get_group0_keyval (&event->key)) {
1102         case GDK_Up:
1103         case GDK_KP_Up:
1104             if (!MOD__CTRL_ONLY) {
1105                 dc->angle += 5.0;
1106                 if (dc->angle > 90.0)
1107                     dc->angle = 90.0;
1108                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
1109                 ret = TRUE;
1110             }
1111             break;
1112         case GDK_Down:
1113         case GDK_KP_Down:
1114             if (!MOD__CTRL_ONLY) {
1115                 dc->angle -= 5.0;
1116                 if (dc->angle < -90.0)
1117                     dc->angle = -90.0;
1118                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
1119                 ret = TRUE;
1120             }
1121             break;
1122         case GDK_Right:
1123         case GDK_KP_Right:
1124             if (!MOD__CTRL_ONLY) {
1125                 dc->width += 0.01;
1126                 if (dc->width > 1.0)
1127                     dc->width = 1.0;
1128                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
1129                 sp_ddc_update_cursors(dc);
1130                 ret = TRUE;
1131             }
1132             break;
1133         case GDK_Left:
1134         case GDK_KP_Left:
1135             if (!MOD__CTRL_ONLY) {
1136                 dc->width -= 0.01;
1137                 if (dc->width < 0.01)
1138                     dc->width = 0.01;
1139                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1140                 sp_ddc_update_cursors(dc);
1141                 ret = TRUE;
1142             }
1143             break;
1144         case GDK_Home:
1145         case GDK_KP_Home:
1146             dc->width = 0.01;
1147             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1148             sp_ddc_update_cursors(dc);
1149             ret = TRUE;
1150             break;
1151         case GDK_End:
1152         case GDK_KP_End:
1153             dc->width = 1.0;
1154             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1155             sp_ddc_update_cursors(dc);
1156             ret = TRUE;
1157             break;
1158         case GDK_x:
1159         case GDK_X:
1160             if (MOD__ALT_ONLY) {
1161                 desktop->setToolboxFocusTo ("altx-calligraphy");
1162                 ret = TRUE;
1163             }
1164             break;
1165         case GDK_Escape:
1166             if (dc->is_drawing) {
1167                 // if drawing, cancel, otherwise pass it up for deselecting
1168                 calligraphic_cancel (dc);
1169                 ret = TRUE;
1170             }
1171             break;
1172         case GDK_z:
1173         case GDK_Z:
1174             if (MOD__CTRL_ONLY && dc->is_drawing) {
1175                 // if drawing, cancel, otherwise pass it up for undo
1176                 calligraphic_cancel (dc);
1177                 ret = TRUE;
1178             }
1179             break;
1180         case GDK_Meta_L:
1181         case GDK_Meta_R:
1182             event_context->cursor_shape = cursor_thicken_xpm;
1183             sp_event_context_update_cursor(event_context);
1184             break;
1185         case GDK_Alt_L:
1186         case GDK_Alt_R:
1187             if (MOD__SHIFT) {
1188                 event_context->cursor_shape = cursor_thicken_xpm;
1189                 sp_event_context_update_cursor(event_context);
1190             } else {
1191                 event_context->cursor_shape = cursor_thin_xpm;
1192                 sp_event_context_update_cursor(event_context);
1193             }
1194             break;
1195         case GDK_Shift_L:
1196         case GDK_Shift_R:
1197             if (MOD__ALT) {
1198                 event_context->cursor_shape = cursor_thicken_xpm;
1199                 sp_event_context_update_cursor(event_context);
1200             }
1201             break;
1202         default:
1203             break;
1204         }
1205         break;
1207     case GDK_KEY_RELEASE:
1208         switch (get_group0_keyval(&event->key)) {
1209             case GDK_Control_L:
1210             case GDK_Control_R:
1211                 dc->_message_context->clear();
1212                 dc->hatch_spacing = 0;
1213                 break;
1214             case GDK_Alt_L:
1215             case GDK_Alt_R:
1216                 event_context->cursor_shape = cursor_calligraphy_xpm;
1217                 sp_event_context_update_cursor(event_context);
1218                 break;
1219             case GDK_Shift_L:
1220             case GDK_Shift_R:
1221                 if (MOD__ALT) {
1222                     event_context->cursor_shape = cursor_thin_xpm;
1223                     sp_event_context_update_cursor(event_context);
1224                 }
1225                 break;
1226             case GDK_Meta_L:
1227             case GDK_Meta_R:
1228                 event_context->cursor_shape = cursor_calligraphy_xpm;
1229                 sp_event_context_update_cursor(event_context);
1230             break;
1231             default:
1232                 break;
1233         }
1235     default:
1236         break;
1237     }
1239     if (!ret) {
1240         if (((SPEventContextClass *) parent_class)->root_handler) {
1241             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1242         }
1243     }
1245     return ret;
1249 static void
1250 clear_current(SPDynaDrawContext *dc)
1252     /* reset bpath */
1253     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
1254     /* reset curve */
1255     sp_curve_reset(dc->currentcurve);
1256     sp_curve_reset(dc->cal1);
1257     sp_curve_reset(dc->cal2);
1258     /* reset points */
1259     dc->npoints = 0;
1262 static void
1263 set_to_accumulated(SPDynaDrawContext *dc, bool unionize)
1265     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1267     if (!sp_curve_empty(dc->accumulated)) {
1268         NArtBpath *abp;
1269         gchar *str;
1271         if (!dc->repr) {
1272             /* Create object */
1273             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1274             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1276             /* Set style */
1277             sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
1279             dc->repr = repr;
1281             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
1282             Inkscape::GC::release(dc->repr);
1283             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
1284             item->updateRepr();
1285         }
1286         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
1287         str = sp_svg_write_path(abp);
1288         g_assert( str != NULL );
1289         g_free(abp);
1290         dc->repr->setAttribute("d", str);
1291         g_free(str);
1293         if (unionize) {
1294             sp_desktop_selection(desktop)->add(dc->repr);
1295             sp_selected_path_union_skip_undo();
1296         } else {
1297             if (dc->keep_selected) {
1298                 sp_desktop_selection(desktop)->set(dc->repr);
1299             } else {
1300                 sp_desktop_selection(desktop)->clear();
1301             }
1302         }
1304     } else {
1305         if (dc->repr) {
1306             sp_repr_unparent(dc->repr);
1307         }
1308         dc->repr = NULL;
1309     }
1311     sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC, 
1312                      _("Draw calligraphic stroke"));
1315 static void
1316 add_cap(SPCurve *curve,
1317         NR::Point const &pre, NR::Point const &from,
1318         NR::Point const &to, NR::Point const &post,
1319         double rounding)
1321     NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
1322     double mag = NR::L2(vel);
1324     NR::Point v_in = from - pre;
1325     double mag_in = NR::L2(v_in);
1326     if ( mag_in > DYNA_EPSILON ) {
1327         v_in = mag * v_in / mag_in;
1328     } else {
1329         v_in = NR::Point(0, 0);
1330     }
1332     NR::Point v_out = to - post;
1333     double mag_out = NR::L2(v_out);
1334     if ( mag_out > DYNA_EPSILON ) {
1335         v_out = mag * v_out / mag_out;
1336     } else {
1337         v_out = NR::Point(0, 0);
1338     }
1340     if ( NR::L2(v_in) > DYNA_EPSILON || NR::L2(v_out) > DYNA_EPSILON ) {
1341         sp_curve_curveto(curve, from + v_in, to + v_out, to);
1342     }
1345 static void
1346 accumulate_calligraphic(SPDynaDrawContext *dc)
1348     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
1349         sp_curve_reset(dc->accumulated); /*  Is this required ?? */
1350         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
1352         g_assert(dc->cal1->end > 1);
1353         g_assert(rev_cal2->end > 1);
1354         g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
1355         g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
1356         g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
1357         g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
1358         g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
1359         g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
1361         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
1363         add_cap(dc->accumulated, SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->c(2), SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->c(3), SP_CURVE_SEGMENT(rev_cal2, 0)->c(3), SP_CURVE_SEGMENT(rev_cal2, 1)->c(1), dc->cap_rounding);
1365         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
1367         add_cap(dc->accumulated, SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->c(2), SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->c(3), SP_CURVE_SEGMENT(dc->cal1, 0)->c(3), SP_CURVE_SEGMENT(dc->cal1, 1)->c(1), dc->cap_rounding);
1369         sp_curve_closepath(dc->accumulated);
1371         sp_curve_unref(rev_cal2);
1373         sp_curve_reset(dc->cal1);
1374         sp_curve_reset(dc->cal2);
1375     }
1378 static double square(double const x)
1380     return x * x;
1383 static void
1384 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1386     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
1388 #ifdef DYNA_DRAW_VERBOSE
1389     g_print("[F&S:R=%c]", release?'T':'F');
1390 #endif
1392     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1393         return; // just clicked
1395     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1396 #define BEZIER_SIZE       4
1397 #define BEZIER_MAX_BEZIERS  8
1398 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1400 #ifdef DYNA_DRAW_VERBOSE
1401         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1402                 dc->npoints, release ? "TRUE" : "FALSE");
1403 #endif
1405         /* Current calligraphic */
1406         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
1407             /* dc->npoints > 0 */
1408             /* g_print("calligraphics(1|2) reset\n"); */
1409             sp_curve_reset(dc->cal1);
1410             sp_curve_reset(dc->cal2);
1412             sp_curve_moveto(dc->cal1, dc->point1[0]);
1413             sp_curve_moveto(dc->cal2, dc->point2[0]);
1414         }
1416         NR::Point b1[BEZIER_MAX_LENGTH];
1417         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1418                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1419         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1421         NR::Point b2[BEZIER_MAX_LENGTH];
1422         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1423                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1424         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1426         if ( nb1 != -1 && nb2 != -1 ) {
1427             /* Fit and draw and reset state */
1428 #ifdef DYNA_DRAW_VERBOSE
1429             g_print("nb1:%d nb2:%d\n", nb1, nb2);
1430 #endif
1431             /* CanvasShape */
1432             if (! release) {
1433                 sp_curve_reset(dc->currentcurve);
1434                 sp_curve_moveto(dc->currentcurve, b1[0]);
1435                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1436                     sp_curve_curveto(dc->currentcurve, bp1[1],
1437                                      bp1[2], bp1[3]);
1438                 }
1439                 sp_curve_lineto(dc->currentcurve,
1440                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
1441                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1442                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
1443                 }
1444                 // FIXME: dc->segments is always NULL at this point??
1445                 if (!dc->segments) { // first segment
1446                     add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
1447                 }
1448                 sp_curve_closepath(dc->currentcurve);
1449                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1450             }
1452             /* Current calligraphic */
1453             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1454                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
1455             }
1456             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1457                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
1458             }
1459         } else {
1460             /* fixme: ??? */
1461 #ifdef DYNA_DRAW_VERBOSE
1462             g_print("[fit_and_split] failed to fit-cubic.\n");
1463 #endif
1464             draw_temporary_box(dc);
1466             for (gint i = 1; i < dc->npoints; i++) {
1467                 sp_curve_lineto(dc->cal1, dc->point1[i]);
1468             }
1469             for (gint i = 1; i < dc->npoints; i++) {
1470                 sp_curve_lineto(dc->cal2, dc->point2[i]);
1471             }
1472         }
1474         /* Fit and draw and copy last point */
1475 #ifdef DYNA_DRAW_VERBOSE
1476         g_print("[%d]Yup\n", dc->npoints);
1477 #endif
1478         if (!release) {
1479             g_assert(!sp_curve_empty(dc->currentcurve));
1481             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1482                                                    SP_TYPE_CANVAS_BPATH,
1483                                                    NULL);
1484             SPCurve *curve = sp_curve_copy(dc->currentcurve);
1485             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1486             sp_curve_unref(curve);
1488             guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1489             //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1490             double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
1491             double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1492             //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1493             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1494             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1495             //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);
1496             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1497             /* fixme: Cannot we cascade it to root more clearly? */
1498             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1500             dc->segments = g_slist_prepend(dc->segments, cbp);
1501         }
1503         dc->point1[0] = dc->point1[dc->npoints - 1];
1504         dc->point2[0] = dc->point2[dc->npoints - 1];
1505         dc->npoints = 1;
1506     } else {
1507         draw_temporary_box(dc);
1508     }
1511 static void
1512 draw_temporary_box(SPDynaDrawContext *dc)
1514     sp_curve_reset(dc->currentcurve);
1516     sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
1517     for (gint i = dc->npoints-2; i >= 0; i--) {
1518         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
1519     }
1520     for (gint i = 0; i < dc->npoints; i++) {
1521         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
1522     }
1523     if (dc->npoints >= 2) {
1524         add_cap(dc->currentcurve, dc->point2[dc->npoints-2], dc->point2[dc->npoints-1], dc->point1[dc->npoints-1], dc->point1[dc->npoints-2], dc->cap_rounding);
1525     }
1527     sp_curve_closepath(dc->currentcurve);
1528     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1531 /*
1532   Local Variables:
1533   mode:c++
1534   c-file-style:"stroustrup"
1535   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1536   indent-tabs-mode:nil
1537   fill-column:99
1538   End:
1539 */
1540 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :