Code

recurse into groups for thinning/thickening
[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-item-group.h"
62 #include "sp-shape.h"
63 #include "sp-path.h"
64 #include "sp-text.h"
65 #include "display/canvas-bpath.h"
66 #include "display/canvas-arena.h"
67 #include "livarot/Shape.h"
68 #include "isnan.h"
70 #include "dyna-draw-context.h"
72 #define DDC_RED_RGBA 0xff0000ff
74 #define TOLERANCE_CALLIGRAPHIC 0.1
76 #define DYNA_EPSILON 0.5e-6
77 #define DYNA_EPSILON_START 0.5e-2
78 #define DYNA_VEL_START 1e-5
80 #define DYNA_MIN_WIDTH 1.0e-6
82 #define DRAG_MIN 0.0
83 #define DRAG_DEFAULT 1.0
84 #define DRAG_MAX 1.0
86 // FIXME: move it to some shared file to be reused by both calligraphy and dropper
87 #define C1 0.552
88 static NArtBpath const hatch_area_circle[] = {
89     { NR_MOVETO, 0, 0, 0, 0, -1, 0 },
90     { NR_CURVETO, -1, C1, -C1, 1, 0, 1 },
91     { NR_CURVETO, C1, 1, 1, C1, 1, 0 },
92     { NR_CURVETO, 1, -C1, C1, -1, 0, -1 },
93     { NR_CURVETO, -C1, -1, -1, -C1, -1, 0 },
94     { NR_END, 0, 0, 0, 0, 0, 0 }
95 };
96 #undef C1
99 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
100 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
101 static void sp_dyna_draw_context_dispose(GObject *object);
103 static void sp_dyna_draw_context_setup(SPEventContext *ec);
104 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
105 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
107 static void clear_current(SPDynaDrawContext *dc);
108 static void set_to_accumulated(SPDynaDrawContext *dc, bool unionize);
109 static void add_cap(SPCurve *curve, NR::Point const &pre, NR::Point const &from, NR::Point const &to, NR::Point const &post, double rounding);
110 static void accumulate_calligraphic(SPDynaDrawContext *dc);
112 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
114 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
115 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
116 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
117 static void draw_temporary_box(SPDynaDrawContext *dc);
120 static SPEventContextClass *parent_class;
122 GtkType
123 sp_dyna_draw_context_get_type(void)
125     static GType type = 0;
126     if (!type) {
127         GTypeInfo info = {
128             sizeof(SPDynaDrawContextClass),
129             NULL, NULL,
130             (GClassInitFunc) sp_dyna_draw_context_class_init,
131             NULL, NULL,
132             sizeof(SPDynaDrawContext),
133             4,
134             (GInstanceInitFunc) sp_dyna_draw_context_init,
135             NULL,   /* value_table */
136         };
137         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
138     }
139     return type;
142 static void
143 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
145     GObjectClass *object_class = (GObjectClass *) klass;
146     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
148     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
150     object_class->dispose = sp_dyna_draw_context_dispose;
152     event_context_class->setup = sp_dyna_draw_context_setup;
153     event_context_class->set = sp_dyna_draw_context_set;
154     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
157 static void
158 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
160     SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
162     event_context->cursor_shape = cursor_calligraphy_xpm;
163     event_context->hot_x = 4;
164     event_context->hot_y = 4;
166     ddc->accumulated = NULL;
167     ddc->segments = NULL;
168     ddc->currentcurve = NULL;
169     ddc->currentshape = NULL;
170     ddc->npoints = 0;
171     ddc->cal1 = NULL;
172     ddc->cal2 = NULL;
173     ddc->repr = NULL;
175     /* DynaDraw values */
176     ddc->cur = NR::Point(0,0);
177     ddc->last = NR::Point(0,0);
178     ddc->vel = NR::Point(0,0);
179     ddc->vel_max = 0;
180     ddc->acc = NR::Point(0,0);
181     ddc->ang = NR::Point(0,0);
182     ddc->del = NR::Point(0,0);
184     /* attributes */
185     ddc->dragging = FALSE;
187     ddc->mass = 0.3;
188     ddc->drag = DRAG_DEFAULT;
189     ddc->angle = 30.0;
190     ddc->width = 0.2;
191     ddc->pressure = DDC_DEFAULT_PRESSURE;
193     ddc->vel_thin = 0.1;
194     ddc->flatness = 0.9;
195     ddc->cap_rounding = 0.0;
197     ddc->abs_width = false;
198     ddc->keep_selected = true;
200     ddc->hatch_spacing = 0;
201     new (&ddc->hatch_pointer_past) std::list<double>();
202     new (&ddc->hatch_nearest_past) std::list<double>();
203     ddc->hatch_last_nearest = NR::Point(0,0);
204     ddc->hatch_last_pointer = NR::Point(0,0);
205     ddc->hatch_vector_accumulated = NR::Point(0,0);
206     ddc->hatch_escaped = false;
207     ddc->hatch_area = NULL;
208     ddc->hatch_item = NULL;
209     ddc->hatch_livarot_path = NULL;
211     ddc->trace_bg = false;
213     ddc->is_dilating = false;
216 static void
217 sp_dyna_draw_context_dispose(GObject *object)
219     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
221     if (ddc->hatch_area) {
222         gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
223         ddc->hatch_area = NULL;
224     }
226     if (ddc->dilate_area) {
227         gtk_object_destroy(GTK_OBJECT(ddc->dilate_area));
228         ddc->dilate_area = NULL;
229     }
231     if (ddc->accumulated) {
232         ddc->accumulated = sp_curve_unref(ddc->accumulated);
233     }
235     while (ddc->segments) {
236         gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
237         ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
238     }
240     if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
241     if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
242     if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
244     if (ddc->currentshape) {
245         gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
246         ddc->currentshape = NULL;
247     }
249     if (ddc->_message_context) {
250         delete ddc->_message_context;
251     }
253     G_OBJECT_CLASS(parent_class)->dispose(object);
255     ddc->hatch_pointer_past.~list();
256     ddc->hatch_nearest_past.~list();
259 static void
260 sp_dyna_draw_context_setup(SPEventContext *ec)
262     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
264     if (((SPEventContextClass *) parent_class)->setup)
265         ((SPEventContextClass *) parent_class)->setup(ec);
267     ddc->accumulated = sp_curve_new_sized(32);
268     ddc->currentcurve = sp_curve_new_sized(4);
270     ddc->cal1 = sp_curve_new_sized(32);
271     ddc->cal2 = sp_curve_new_sized(32);
273     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
274     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
275     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
276     /* fixme: Cannot we cascade it to root more clearly? */
277     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
279     {
280         SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
281         ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
282         sp_curve_unref(c);
283         sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
284         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
285         sp_canvas_item_hide(ddc->hatch_area);
286     }
288     {
289         SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
290         ddc->dilate_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
291         sp_curve_unref(c);
292         sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->dilate_area), 0x00000000,(SPWindRule)0);
293         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->dilate_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
294         sp_canvas_item_hide(ddc->dilate_area);
295     }
297     sp_event_context_read(ec, "mass");
298     sp_event_context_read(ec, "wiggle");
299     sp_event_context_read(ec, "angle");
300     sp_event_context_read(ec, "width");
301     sp_event_context_read(ec, "thinning");
302     sp_event_context_read(ec, "tremor");
303     sp_event_context_read(ec, "flatness");
304     sp_event_context_read(ec, "tracebackground");
305     sp_event_context_read(ec, "usepressure");
306     sp_event_context_read(ec, "usetilt");
307     sp_event_context_read(ec, "abs_width");
308     sp_event_context_read(ec, "keep_selected");
309     sp_event_context_read(ec, "cap_rounding");
311     ddc->is_drawing = false;
313     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
316 static void
317 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
319     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
321     if (!strcmp(key, "mass")) {
322         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
323         ddc->mass = CLAMP(dval, -1000.0, 1000.0);
324     } else if (!strcmp(key, "wiggle")) {
325         double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
326         ddc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
327     } else if (!strcmp(key, "angle")) {
328         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
329         ddc->angle = CLAMP (dval, -90, 90);
330     } else if (!strcmp(key, "width")) {
331         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
332         ddc->width = CLAMP(dval, -1000.0, 1000.0);
333     } else if (!strcmp(key, "thinning")) {
334         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
335         ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
336     } else if (!strcmp(key, "tremor")) {
337         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
338         ddc->tremor = CLAMP(dval, 0.0, 1.0);
339     } else if (!strcmp(key, "flatness")) {
340         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
341         ddc->flatness = CLAMP(dval, 0, 1.0);
342     } else if (!strcmp(key, "tracebackground")) {
343         ddc->trace_bg = (val && strcmp(val, "0"));
344     } else if (!strcmp(key, "usepressure")) {
345         ddc->usepressure = (val && strcmp(val, "0"));
346     } else if (!strcmp(key, "usetilt")) {
347         ddc->usetilt = (val && strcmp(val, "0"));
348     } else if (!strcmp(key, "abs_width")) {
349         ddc->abs_width = (val && strcmp(val, "0"));
350     } else if (!strcmp(key, "keep_selected")) {
351         ddc->keep_selected = (val && strcmp(val, "0"));
352     } else if (!strcmp(key, "cap_rounding")) {
353         ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
354     }
356     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
359 static double
360 flerp(double f0, double f1, double p)
362     return f0 + ( f1 - f0 ) * p;
365 /* Get normalized point */
366 static NR::Point
367 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
369     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
370     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
371     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
374 /* Get view point */
375 static NR::Point
376 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
378     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
379     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
380     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
383 static void
384 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
386     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
387     dc->vel = NR::Point(0,0);
388     dc->vel_max = 0;
389     dc->acc = NR::Point(0,0);
390     dc->ang = NR::Point(0,0);
391     dc->del = NR::Point(0,0);
394 static void
395 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
397     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
398         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
399     else
400         dc->pressure = DDC_DEFAULT_PRESSURE;
402     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
403         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
404     else
405         dc->xtilt = DDC_DEFAULT_TILT;
407     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
408         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
409     else
410         dc->ytilt = DDC_DEFAULT_TILT;
414 static gboolean
415 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
417     NR::Point n = sp_dyna_draw_get_npoint(dc, p);
419     /* Calculate mass and drag */
420     double const mass = flerp(1.0, 160.0, dc->mass);
421     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
423     /* Calculate force and acceleration */
424     NR::Point force = n - dc->cur;
426     // If force is below the absolute threshold DYNA_EPSILON,
427     // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
428     // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
429     // discard this move. 
430     // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
431     // especially bothersome at the start of the stroke where we don't yet have the inertia to
432     // smooth them out.
433     if ( NR::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && NR::L2(force) < DYNA_EPSILON_START)) {
434         return FALSE;
435     }
437     dc->acc = force / mass;
439     /* Calculate new velocity */
440     dc->vel += dc->acc;
442     if (NR::L2(dc->vel) > dc->vel_max)
443         dc->vel_max = NR::L2(dc->vel);
445     /* Calculate angle of drawing tool */
447     double a1;
448     if (dc->usetilt) {
449         // 1a. calculate nib angle from input device tilt:
450         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
452         if (length > 0) {
453             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
454             a1 = atan2(ang1);
455         }
456         else
457             a1 = 0.0;
458     }
459     else {
460         // 1b. fixed dc->angle (absolutely flat nib):
461         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
462         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
463         a1 = atan2(ang1);
464     }
466     // 2. perpendicular to dc->vel (absolutely non-flat nib):
467     gdouble const mag_vel = NR::L2(dc->vel);
468     if ( mag_vel < DYNA_EPSILON ) {
469         return FALSE;
470     }
471     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
473     // 3. Average them using flatness parameter:
474     // calculate angles
475     double a2 = atan2(ang2);
476     // flip a2 to force it to be in the same half-circle as a1
477     bool flipped = false;
478     if (fabs (a2-a1) > 0.5*M_PI) {
479         a2 += M_PI;
480         flipped = true;
481     }
482     // normalize a2
483     if (a2 > M_PI)
484         a2 -= 2*M_PI;
485     if (a2 < -M_PI)
486         a2 += 2*M_PI;
487     // find the flatness-weighted bisector angle, unflip if a2 was flipped
488     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
489     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
491     // Try to detect a sudden flip when the new angle differs too much from the previous for the
492     // current velocity; in that case discard this move
493     double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
494     if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
495         return FALSE;
496     }
498     // convert to point
499     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
501 //    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);
503     /* Apply drag */
504     dc->vel *= 1.0 - drag;
506     /* Update position */
507     dc->last = dc->cur;
508     dc->cur += dc->vel;
510     return TRUE;
513 static void
514 sp_dyna_draw_brush(SPDynaDrawContext *dc)
516     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
518     // How much velocity thins strokestyle
519     double vel_thin = flerp (0, 160, dc->vel_thin);
521     // Influence of pressure on thickness
522     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
524     // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
525     // drag)
526     NR::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
527     NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush); 
529     double trace_thick = 1;
530     if (dc->trace_bg) {
531         // pick single pixel
532         NRPixBlock pb;
533         int x = (int) floor(brush_w[NR::X]);
534         int y = (int) floor(brush_w[NR::Y]);
535         nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
536         sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
537         const unsigned char *s = NR_PIXBLOCK_PX(&pb);
538         double R = s[0] / 255.0;
539         double G = s[1] / 255.0;
540         double B = s[2] / 255.0;
541         double A = s[3] / 255.0;
542         double max = MAX (MAX (R, G), B);
543         double min = MIN (MIN (R, G), B);
544         double L = A * (max + min)/2 + (1 - A); // blend with white bg
545         trace_thick = 1 - L;
546         //g_print ("L %g thick %g\n", L, trace_thick);
547     }
549     double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
551     double tremble_left = 0, tremble_right = 0;
552     if (dc->tremor > 0) {
553         // obtain two normally distributed random variables, using polar Box-Muller transform
554         double x1, x2, w, y1, y2;
555         do {
556             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
557             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
558             w = x1 * x1 + x2 * x2;
559         } while ( w >= 1.0 );
560         w = sqrt( (-2.0 * log( w ) ) / w );
561         y1 = x1 * w;
562         y2 = x2 * w;
564         // deflect both left and right edges randomly and independently, so that:
565         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
566         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
567         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
568         // comparatively smooth and slow ones excessively jittery
569         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
570         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
571     }
573     if ( width < 0.02 * dc->width ) {
574         width = 0.02 * dc->width;
575     }
577     double dezoomify_factor = 0.05 * 1000;
578     if (!dc->abs_width) {
579         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
580     }
582     NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
583     NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
585     dc->point1[dc->npoints] = brush + del_left;
586     dc->point2[dc->npoints] = brush - del_right;
588     dc->del = 0.5*(del_left + del_right);
590     dc->npoints++;
593 double
594 get_dilate_radius (SPDynaDrawContext *dc)
596     // 10 times the pen width:
597     return 500 * dc->width/SP_EVENT_CONTEXT(dc)->desktop->current_zoom(); 
600 double
601 get_dilate_force (SPDynaDrawContext *dc)
603     double force = 4 * dc->pressure/SP_EVENT_CONTEXT(dc)->desktop->current_zoom(); 
604     if (force > 3) {
605         force += 8 * (force - 3);
606     }
607     return force;
610 bool
611 sp_ddc_dilate_recursive (SPItem *item, NR::Point p, bool expand, double radius, double offset)
613     bool did = false;
615     if (SP_IS_GROUP(item)) {
616         for (SPObject *child = sp_object_first_child(SP_OBJECT(item)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
617             if (SP_IS_ITEM(child)) {
618                 did = did || sp_ddc_dilate_recursive (SP_ITEM(child), p, expand, radius, offset);
619             }
620         }
622     } else if (SP_IS_PATH(item)) {
624         SPCurve *curve = NULL;
625         curve = sp_shape_get_curve(SP_SHAPE(item));
626         if (curve == NULL)
627             return false;
629         // skip those paths whose bboxes are entirely out of reach with our radius
630         NR::Maybe<NR::Rect> bbox = item->getBounds(sp_item_i2doc_affine(item));
631         if (bbox) {
632             bbox->growBy(radius);
633             if (!bbox->contains(p)) {
634                 return false;
635             }
636         }
638         Path *orig = Path_for_item(item, false);
639         if (orig == NULL) {
640             sp_curve_unref(curve);
641             return false;
642         }
643         Path *res = new Path;
644         res->SetBackData(false);
646         Shape *theShape = new Shape;
647         Shape *theRes = new Shape;
649         orig->ConvertWithBackData(0.05);
650         orig->Fill(theShape, 0);
652         SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
653         gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
654         if (val && strcmp(val, "nonzero") == 0)
655         {
656             theRes->ConvertToShape(theShape, fill_nonZero);
657         }
658         else if (val && strcmp(val, "evenodd") == 0)
659         {
660             theRes->ConvertToShape(theShape, fill_oddEven);
661         }
662         else
663         {
664             theRes->ConvertToShape(theShape, fill_nonZero);
665         }
667         bool did_this = false;
668         NR::Matrix i2doc(sp_item_i2doc_affine(item));
669         if (theShape->MakeOffset(theRes, 
670                                  expand? offset : -offset,
671                                  join_straight, butt_straight,
672                                  true, p[NR::X], p[NR::Y], radius, &i2doc) == 0) // 0 means the shape was actually changed
673             did_this = true;
675         // the rest only makes sense if we actually changed the path
676         if (did_this) {
677             theRes->ConvertToShape(theShape, fill_positive);
679             res->Reset();
680             theRes->ConvertToForme(res);
682             if (offset >= 0.5)
683             {
684                 res->ConvertEvenLines(0.5);
685                 res->Simplify(0.5);
686             }
687             else
688             {
689                 res->ConvertEvenLines(0.5*offset);
690                 res->Simplify(0.5 * offset);
691             }
693             sp_curve_unref(curve);
694             if (res->descr_cmd.size() > 1) { 
695                 gchar *str = res->svg_dump_path();
696                 SP_OBJECT_REPR(item)->setAttribute("d", str);
697                 g_free(str);
698             } else {
699                 // TODO: if there's 0 or 1 node left, delete this path altogether
700             }
701         }
703         delete theShape;
704         delete theRes;
705         delete orig;
706         delete res;
708         if (did_this) 
709             did = true;
710     }
712     return did;
716 bool
717 sp_ddc_dilate (SPDynaDrawContext *dc, NR::Point p, bool expand)
719     Inkscape::Selection *selection = sp_desktop_selection(SP_EVENT_CONTEXT(dc)->desktop);
721     if (selection->isEmpty()) {
722         return false;
723     }
725     bool did = false;
726     double radius = get_dilate_radius(dc); 
727     double offset = get_dilate_force(dc); 
728     if (radius == 0 || offset == 0) {
729         return false;
730     }
732     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
733          items != NULL;
734          items = items->next) {
736         SPItem *item = (SPItem *) items->data;
738         did = did || sp_ddc_dilate_recursive (item, p, expand, radius, offset);
740     }
742     return did;
745 void
746 sp_ddc_update_cursors (SPDynaDrawContext *dc)
748     if (dc->is_dilating) {
749         double radius = get_dilate_radius(dc);
750         NR::Matrix const sm (NR::scale(radius, radius) * NR::translate(SP_EVENT_CONTEXT(dc)->desktop->point()));
751         sp_canvas_item_affine_absolute(dc->dilate_area, sm);
752         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
753         sp_canvas_item_show(dc->dilate_area);
754     }
757 void
758 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
760     desktop->setToolboxAdjustmentValue (id, value);
763 static void
764 calligraphic_cancel(SPDynaDrawContext *dc)
766     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
767     dc->dragging = FALSE;
768     dc->is_drawing = false;
769     sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
770             /* Remove all temporary line segments */
771             while (dc->segments) {
772                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
773                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
774             }
775             /* reset accumulated curve */
776             sp_curve_reset(dc->accumulated);
777             clear_current(dc);
778             if (dc->repr) {
779                 dc->repr = NULL;
780             }
784 gint
785 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
786                                   GdkEvent *event)
788     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
789     SPDesktop *desktop = event_context->desktop;
791     gint ret = FALSE;
793     switch (event->type) {
794         case GDK_BUTTON_PRESS:
795             if ( event->button.button == 1 ) {
797                 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
799                 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
800                     return TRUE;
801                 }
803                 NR::Point const button_w(event->button.x,
804                                          event->button.y);
805                 NR::Point const button_dt(desktop->w2d(button_w));
806                 sp_dyna_draw_reset(dc, button_dt);
807                 sp_dyna_draw_extinput(dc, event);
808                 sp_dyna_draw_apply(dc, button_dt);
809                 sp_curve_reset(dc->accumulated);
810                 if (dc->repr) {
811                     dc->repr = NULL;
812                 }
814                 /* initialize first point */
815                 dc->npoints = 0;
817                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
818                                     ( GDK_KEY_PRESS_MASK |
819                                       GDK_BUTTON_RELEASE_MASK |
820                                       GDK_POINTER_MOTION_MASK |
821                                       GDK_BUTTON_PRESS_MASK ),
822                                     NULL,
823                                     event->button.time);
825                 if (event->motion.state & GDK_MOD1_MASK) {
826                     sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
827                 }
829                 ret = TRUE;
831                 dc->is_drawing = true;
832             }
833             break;
834         case GDK_MOTION_NOTIFY:
835         {
836             NR::Point const motion_w(event->motion.x,
837                                      event->motion.y);
838             NR::Point motion_dt(desktop->w2d(motion_w));
839             sp_dyna_draw_extinput(dc, event);
841             // draw the dilating cursor
842             if (event->motion.state & GDK_MOD1_MASK) {
843                 double radius = get_dilate_radius(dc);
844                 NR::Matrix const sm (NR::scale(radius, radius) * NR::translate(desktop->w2d(motion_w)));
845                 sp_canvas_item_affine_absolute(dc->dilate_area, sm);
846                 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
847                 sp_canvas_item_show(dc->dilate_area);
849                 guint num = 0;
850                 if (!desktop->selection->isEmpty()) {
851                     num = g_slist_length((GSList *) desktop->selection->itemList());
852                 }
853                 if (num == 0) {
854                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select paths</b> to thin or thicken"));
855                 } else {
856                     dc->_message_context->setF(Inkscape::NORMAL_MESSAGE,
857                                            event->motion.state & GDK_SHIFT_MASK?
858                                            _("<b>Thickening %d</b> selected objects; without <b>Shift</b> to thin") :
859                                            _("<b>Thinning %d</b> selected objects; with <b>Shift</b> to thicken"), num);
860                 }
862             } else {
863                 dc->_message_context->clear();
864                 sp_canvas_item_hide(dc->dilate_area);
865             }
867             // dilating:
868             if (dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) && event->motion.state & GDK_MOD1_MASK) {  
869                 sp_ddc_dilate (dc, desktop->dt2doc(motion_dt), event->motion.state & GDK_SHIFT_MASK? true : false);
870                 dc->is_dilating = true;
871                 // it's slow, so prevent clogging up with events
872                 gobble_motion_events(GDK_BUTTON1_MASK);
873                 return TRUE;
874             }
877             // for hatching:
878             double hatch_dist = 0;
879             NR::Point hatch_unit_vector(0,0);
880             NR::Point nearest(0,0);
881             NR::Point pointer(0,0);
882             NR::Matrix motion_to_curve(NR::identity());
884             if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
886                 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
887                 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
888                     // One item selected, and it's a path;
889                     // let's try to track it as a guide
891                     if (selected != dc->hatch_item) {
892                         dc->hatch_item = selected;
893                         if (dc->hatch_livarot_path)
894                             delete dc->hatch_livarot_path;
895                         dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
896                         dc->hatch_livarot_path->ConvertWithBackData(0.01);
897                     }
899                     // calculate pointer point in the guide item's coords
900                     motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
901                     pointer = motion_dt * motion_to_curve;
903                     // calculate the nearest point on the guide path
904                     NR::Maybe<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
905                     nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
908                     // distance from pointer to nearest
909                     hatch_dist = NR::L2(pointer - nearest);
910                     // unit-length vector
911                     hatch_unit_vector = (pointer - nearest)/hatch_dist;
913                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
914                 } else {
915                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
916                 }
917             } 
919             if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
920                 dc->dragging = TRUE;
922                 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
924 #define SPEED_ELEMENTS 12
925 #define SPEED_MIN 0.12
926 #define SPEED_NORMAL 0.65
928                     // speed is the movement of the nearest point along the guide path, divided by
929                     // the movement of the pointer at the same period; it is averaged for the last
930                     // SPEED_ELEMENTS motion events.  Normally, as you track the guide path, speed
931                     // is about 1, i.e. the nearest point on the path is moved by about the same
932                     // distance as the pointer. If the speed starts to decrease, we are losing
933                     // contact with the guide; if it drops below SPEED_MIN, we are on our own and
934                     // not attracted to guide anymore. Most often this happens when you have
935                     // tracked to the end of a guide calligraphic stroke and keep moving
936                     // further. We try to handle this situation gracefully: not stick with the
937                     // guide forever but let go of it smoothly and without sharp jerks (non-zero
938                     // mass recommended; with zero mass, jerks are still quite noticeable).
940                     double speed = 1;
941                     if (NR::L2(dc->hatch_last_nearest) != 0) {
942                         // the distance nearest moved since the last motion event
943                         double nearest_moved = NR::L2(nearest - dc->hatch_last_nearest);
944                         // the distance pointer moved since the last motion event
945                         double pointer_moved = NR::L2(pointer - dc->hatch_last_pointer);
946                         // store them in stacks limited to SPEED_ELEMENTS
947                         dc->hatch_nearest_past.push_front(nearest_moved);
948                         if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
949                             dc->hatch_nearest_past.pop_back();
950                         dc->hatch_pointer_past.push_front(pointer_moved);
951                         if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
952                             dc->hatch_pointer_past.pop_back();
954                         // If the stacks are full,
955                         if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
956                             // calculate the sums of all stored movements
957                             double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
958                             double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
959                             // and divide to get the speed
960                             speed = nearest_sum/pointer_sum;
961                             //g_print ("nearest sum %g  pointer_sum %g  speed %g\n", nearest_sum, pointer_sum, speed);
962                         }
963                     }
965                     if (   dc->hatch_escaped  // already escaped, do not reattach
966                         || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
967                         || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
968                         ) {
969                         // We are NOT attracted to the guide!
971                         //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);
973                         // Remember hatch_escaped so we don't get
974                         // attracted again until the end of this stroke
975                         dc->hatch_escaped = true;
977                     } else {
979                         // Calculate angle cosine of this vector-to-guide and all past vectors
980                         // summed, to detect if we accidentally flipped to the other side of the
981                         // guide
982                         double dot = NR::dot (pointer - nearest, dc->hatch_vector_accumulated);
983                         dot /= NR::L2(pointer - nearest) * NR::L2(dc->hatch_vector_accumulated);
985                         if (dc->hatch_spacing != 0) { // spacing was already set
986                             double target;
987                             if (speed > SPEED_NORMAL) {
988                                 // all ok, strictly obey the spacing
989                                 target = dc->hatch_spacing;
990                             } else {
991                                 // looks like we're starting to lose speed,
992                                 // so _gradually_ let go attraction to prevent jerks
993                                 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;                            
994                             }
995                             if (!isNaN(dot) && dot < -0.5) {// flip
996                                 target = -target;
997                             }
999                             // This is the track pointer that we will use instead of the real one
1000                             NR::Point new_pointer = nearest + target * hatch_unit_vector;
1002                             // some limited feedback: allow persistent pulling to slightly change
1003                             // the spacing
1004                             dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
1006                             // return it to the desktop coords
1007                             motion_dt = new_pointer * motion_to_curve.inverse();
1009                         } else {
1010                             // this is the first motion event, set the dist 
1011                             dc->hatch_spacing = hatch_dist;
1012                         }
1014                         // remember last points
1015                         dc->hatch_last_pointer = pointer;
1016                         dc->hatch_last_nearest = nearest;
1017                         dc->hatch_vector_accumulated += (pointer - nearest);
1018                     }
1020                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
1022                 } else {
1023                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
1024                 }
1026                 if (!sp_dyna_draw_apply(dc, motion_dt)) {
1027                     ret = TRUE;
1028                     break;
1029                 }
1031                 if ( dc->cur != dc->last ) {
1032                     sp_dyna_draw_brush(dc);
1033                     g_assert( dc->npoints > 0 );
1034                     fit_and_split(dc, FALSE);
1035                 }
1036                 ret = TRUE;
1037             }
1039             // Draw the hatching circle if necessary
1040             if (event->motion.state & GDK_CONTROL_MASK) { 
1041                 if (dc->hatch_spacing == 0 && hatch_dist != 0) { 
1042                     // Haven't set spacing yet: gray, center free, update radius live
1043                     NR::Point c = desktop->w2d(motion_w);
1044                     NR::Matrix const sm (NR::scale(hatch_dist, hatch_dist) * NR::translate(c));
1045                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1046                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1047                     sp_canvas_item_show(dc->hatch_area);
1048                 } else if (dc->dragging && !dc->hatch_escaped) {
1049                     // Tracking: green, center snapped, fixed radius
1050                     NR::Point c = motion_dt;
1051                     NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1052                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1053                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1054                     sp_canvas_item_show(dc->hatch_area);
1055                 } else if (dc->dragging && dc->hatch_escaped) {
1056                     // Tracking escaped: red, center free, fixed radius
1057                     NR::Point c = desktop->w2d(motion_w);
1058                     NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1060                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1061                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1062                     sp_canvas_item_show(dc->hatch_area);
1063                 } else {
1064                     // Not drawing but spacing set: gray, center snapped, fixed radius
1065                     NR::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
1066                     if (!isNaN(c[NR::X]) && !isNaN(c[NR::Y])) {
1067                         NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1068                         sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1069                         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1070                         sp_canvas_item_show(dc->hatch_area);
1071                     }
1072                 }
1073             } else {
1074                 sp_canvas_item_hide(dc->hatch_area);
1075             }
1076         }
1077         break;
1080     case GDK_BUTTON_RELEASE:
1081         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
1082         dc->is_drawing = false;
1084         if ( dc->is_dilating && event->button.button == 1 ) {
1085             dc->is_dilating = false;
1086             sp_canvas_end_forced_full_redraws(desktop->canvas);
1087             sp_document_done(sp_desktop_document(SP_EVENT_CONTEXT(dc)->desktop), 
1088                          SP_VERB_CONTEXT_CALLIGRAPHIC,
1089                          (event->button.state & GDK_SHIFT_MASK ? _("Thicken paths") : _("Thin paths")));
1090             ret = TRUE;
1091         } else if ( dc->dragging && event->button.button == 1 ) {
1092             dc->dragging = FALSE;
1094             NR::Point const motion_w(event->button.x, event->button.y);
1095             NR::Point const motion_dt(desktop->w2d(motion_w));
1096             sp_dyna_draw_apply(dc, motion_dt);
1098             /* Remove all temporary line segments */
1099             while (dc->segments) {
1100                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
1101                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
1102             }
1104             /* Create object */
1105             fit_and_split(dc, TRUE);
1106             accumulate_calligraphic(dc);
1107             set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK); // performs document_done
1109             /* reset accumulated curve */
1110             sp_curve_reset(dc->accumulated);
1112             clear_current(dc);
1113             if (dc->repr) {
1114                 dc->repr = NULL;
1115             }
1117             if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
1118             if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
1119             dc->hatch_last_nearest = NR::Point(0,0);
1120             dc->hatch_last_pointer = NR::Point(0,0);
1121             dc->hatch_vector_accumulated = NR::Point(0,0);
1122             dc->hatch_escaped = false;
1123             dc->hatch_item = NULL;
1124             dc->hatch_livarot_path = NULL;
1126             dc->_message_context->clear();
1127             ret = TRUE;
1128         }
1129         break;
1131     case GDK_KEY_PRESS:
1132         switch (get_group0_keyval (&event->key)) {
1133         case GDK_Up:
1134         case GDK_KP_Up:
1135             if (!MOD__CTRL_ONLY) {
1136                 dc->angle += 5.0;
1137                 if (dc->angle > 90.0)
1138                     dc->angle = 90.0;
1139                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
1140                 ret = TRUE;
1141             }
1142             break;
1143         case GDK_Down:
1144         case GDK_KP_Down:
1145             if (!MOD__CTRL_ONLY) {
1146                 dc->angle -= 5.0;
1147                 if (dc->angle < -90.0)
1148                     dc->angle = -90.0;
1149                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
1150                 ret = TRUE;
1151             }
1152             break;
1153         case GDK_Right:
1154         case GDK_KP_Right:
1155             if (!MOD__CTRL_ONLY) {
1156                 dc->width += 0.01;
1157                 if (dc->width > 1.0)
1158                     dc->width = 1.0;
1159                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
1160                 sp_ddc_update_cursors(dc);
1161                 ret = TRUE;
1162             }
1163             break;
1164         case GDK_Left:
1165         case GDK_KP_Left:
1166             if (!MOD__CTRL_ONLY) {
1167                 dc->width -= 0.01;
1168                 if (dc->width < 0.01)
1169                     dc->width = 0.01;
1170                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1171                 sp_ddc_update_cursors(dc);
1172                 ret = TRUE;
1173             }
1174             break;
1175         case GDK_Home:
1176         case GDK_KP_Home:
1177             dc->width = 0.01;
1178             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1179             sp_ddc_update_cursors(dc);
1180             ret = TRUE;
1181             break;
1182         case GDK_End:
1183         case GDK_KP_End:
1184             dc->width = 1.0;
1185             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1186             sp_ddc_update_cursors(dc);
1187             ret = TRUE;
1188             break;
1189         case GDK_x:
1190         case GDK_X:
1191             if (MOD__ALT_ONLY) {
1192                 desktop->setToolboxFocusTo ("altx-calligraphy");
1193                 ret = TRUE;
1194             }
1195             break;
1196         case GDK_Escape:
1197             if (dc->is_drawing) {
1198                 // if drawing, cancel, otherwise pass it up for deselecting
1199                 calligraphic_cancel (dc);
1200                 ret = TRUE;
1201             }
1202             break;
1203         case GDK_z:
1204         case GDK_Z:
1205             if (MOD__CTRL_ONLY && dc->is_drawing) {
1206                 // if drawing, cancel, otherwise pass it up for undo
1207                 calligraphic_cancel (dc);
1208                 ret = TRUE;
1209             }
1210             break;
1211         case GDK_Meta_L:
1212         case GDK_Meta_R:
1213             event_context->cursor_shape = cursor_thicken_xpm;
1214             sp_event_context_update_cursor(event_context);
1215             break;
1216         case GDK_Alt_L:
1217         case GDK_Alt_R:
1218             if (MOD__SHIFT) {
1219                 event_context->cursor_shape = cursor_thicken_xpm;
1220                 sp_event_context_update_cursor(event_context);
1221             } else {
1222                 event_context->cursor_shape = cursor_thin_xpm;
1223                 sp_event_context_update_cursor(event_context);
1224             }
1225             break;
1226         case GDK_Shift_L:
1227         case GDK_Shift_R:
1228             if (MOD__ALT) {
1229                 event_context->cursor_shape = cursor_thicken_xpm;
1230                 sp_event_context_update_cursor(event_context);
1231             }
1232             break;
1233         default:
1234             break;
1235         }
1236         break;
1238     case GDK_KEY_RELEASE:
1239         switch (get_group0_keyval(&event->key)) {
1240             case GDK_Control_L:
1241             case GDK_Control_R:
1242                 dc->_message_context->clear();
1243                 dc->hatch_spacing = 0;
1244                 break;
1245             case GDK_Alt_L:
1246             case GDK_Alt_R:
1247                 event_context->cursor_shape = cursor_calligraphy_xpm;
1248                 sp_event_context_update_cursor(event_context);
1249                 break;
1250             case GDK_Shift_L:
1251             case GDK_Shift_R:
1252                 if (MOD__ALT) {
1253                     event_context->cursor_shape = cursor_thin_xpm;
1254                     sp_event_context_update_cursor(event_context);
1255                 }
1256                 break;
1257             case GDK_Meta_L:
1258             case GDK_Meta_R:
1259                 event_context->cursor_shape = cursor_calligraphy_xpm;
1260                 sp_event_context_update_cursor(event_context);
1261             break;
1262             default:
1263                 break;
1264         }
1266     default:
1267         break;
1268     }
1270     if (!ret) {
1271         if (((SPEventContextClass *) parent_class)->root_handler) {
1272             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1273         }
1274     }
1276     return ret;
1280 static void
1281 clear_current(SPDynaDrawContext *dc)
1283     /* reset bpath */
1284     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
1285     /* reset curve */
1286     sp_curve_reset(dc->currentcurve);
1287     sp_curve_reset(dc->cal1);
1288     sp_curve_reset(dc->cal2);
1289     /* reset points */
1290     dc->npoints = 0;
1293 static void
1294 set_to_accumulated(SPDynaDrawContext *dc, bool unionize)
1296     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1298     if (!sp_curve_empty(dc->accumulated)) {
1299         NArtBpath *abp;
1300         gchar *str;
1302         if (!dc->repr) {
1303             /* Create object */
1304             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1305             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1307             /* Set style */
1308             sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
1310             dc->repr = repr;
1312             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
1313             Inkscape::GC::release(dc->repr);
1314             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
1315             item->updateRepr();
1316         }
1317         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
1318         str = sp_svg_write_path(abp);
1319         g_assert( str != NULL );
1320         g_free(abp);
1321         dc->repr->setAttribute("d", str);
1322         g_free(str);
1324         if (unionize) {
1325             sp_desktop_selection(desktop)->add(dc->repr);
1326             sp_selected_path_union_skip_undo();
1327         } else {
1328             if (dc->keep_selected) {
1329                 sp_desktop_selection(desktop)->set(dc->repr);
1330             } else {
1331                 sp_desktop_selection(desktop)->clear();
1332             }
1333         }
1335     } else {
1336         if (dc->repr) {
1337             sp_repr_unparent(dc->repr);
1338         }
1339         dc->repr = NULL;
1340     }
1342     sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC, 
1343                      _("Draw calligraphic stroke"));
1346 static void
1347 add_cap(SPCurve *curve,
1348         NR::Point const &pre, NR::Point const &from,
1349         NR::Point const &to, NR::Point const &post,
1350         double rounding)
1352     NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
1353     double mag = NR::L2(vel);
1355     NR::Point v_in = from - pre;
1356     double mag_in = NR::L2(v_in);
1357     if ( mag_in > DYNA_EPSILON ) {
1358         v_in = mag * v_in / mag_in;
1359     } else {
1360         v_in = NR::Point(0, 0);
1361     }
1363     NR::Point v_out = to - post;
1364     double mag_out = NR::L2(v_out);
1365     if ( mag_out > DYNA_EPSILON ) {
1366         v_out = mag * v_out / mag_out;
1367     } else {
1368         v_out = NR::Point(0, 0);
1369     }
1371     if ( NR::L2(v_in) > DYNA_EPSILON || NR::L2(v_out) > DYNA_EPSILON ) {
1372         sp_curve_curveto(curve, from + v_in, to + v_out, to);
1373     }
1376 static void
1377 accumulate_calligraphic(SPDynaDrawContext *dc)
1379     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
1380         sp_curve_reset(dc->accumulated); /*  Is this required ?? */
1381         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
1383         g_assert(dc->cal1->end > 1);
1384         g_assert(rev_cal2->end > 1);
1385         g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
1386         g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
1387         g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
1388         g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
1389         g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
1390         g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
1392         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
1394         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);
1396         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
1398         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);
1400         sp_curve_closepath(dc->accumulated);
1402         sp_curve_unref(rev_cal2);
1404         sp_curve_reset(dc->cal1);
1405         sp_curve_reset(dc->cal2);
1406     }
1409 static double square(double const x)
1411     return x * x;
1414 static void
1415 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1417     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
1419 #ifdef DYNA_DRAW_VERBOSE
1420     g_print("[F&S:R=%c]", release?'T':'F');
1421 #endif
1423     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1424         return; // just clicked
1426     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1427 #define BEZIER_SIZE       4
1428 #define BEZIER_MAX_BEZIERS  8
1429 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1431 #ifdef DYNA_DRAW_VERBOSE
1432         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1433                 dc->npoints, release ? "TRUE" : "FALSE");
1434 #endif
1436         /* Current calligraphic */
1437         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
1438             /* dc->npoints > 0 */
1439             /* g_print("calligraphics(1|2) reset\n"); */
1440             sp_curve_reset(dc->cal1);
1441             sp_curve_reset(dc->cal2);
1443             sp_curve_moveto(dc->cal1, dc->point1[0]);
1444             sp_curve_moveto(dc->cal2, dc->point2[0]);
1445         }
1447         NR::Point b1[BEZIER_MAX_LENGTH];
1448         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1449                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1450         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1452         NR::Point b2[BEZIER_MAX_LENGTH];
1453         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1454                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1455         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1457         if ( nb1 != -1 && nb2 != -1 ) {
1458             /* Fit and draw and reset state */
1459 #ifdef DYNA_DRAW_VERBOSE
1460             g_print("nb1:%d nb2:%d\n", nb1, nb2);
1461 #endif
1462             /* CanvasShape */
1463             if (! release) {
1464                 sp_curve_reset(dc->currentcurve);
1465                 sp_curve_moveto(dc->currentcurve, b1[0]);
1466                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1467                     sp_curve_curveto(dc->currentcurve, bp1[1],
1468                                      bp1[2], bp1[3]);
1469                 }
1470                 sp_curve_lineto(dc->currentcurve,
1471                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
1472                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1473                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
1474                 }
1475                 // FIXME: dc->segments is always NULL at this point??
1476                 if (!dc->segments) { // first segment
1477                     add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
1478                 }
1479                 sp_curve_closepath(dc->currentcurve);
1480                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1481             }
1483             /* Current calligraphic */
1484             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1485                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
1486             }
1487             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1488                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
1489             }
1490         } else {
1491             /* fixme: ??? */
1492 #ifdef DYNA_DRAW_VERBOSE
1493             g_print("[fit_and_split] failed to fit-cubic.\n");
1494 #endif
1495             draw_temporary_box(dc);
1497             for (gint i = 1; i < dc->npoints; i++) {
1498                 sp_curve_lineto(dc->cal1, dc->point1[i]);
1499             }
1500             for (gint i = 1; i < dc->npoints; i++) {
1501                 sp_curve_lineto(dc->cal2, dc->point2[i]);
1502             }
1503         }
1505         /* Fit and draw and copy last point */
1506 #ifdef DYNA_DRAW_VERBOSE
1507         g_print("[%d]Yup\n", dc->npoints);
1508 #endif
1509         if (!release) {
1510             g_assert(!sp_curve_empty(dc->currentcurve));
1512             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1513                                                    SP_TYPE_CANVAS_BPATH,
1514                                                    NULL);
1515             SPCurve *curve = sp_curve_copy(dc->currentcurve);
1516             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1517             sp_curve_unref(curve);
1519             guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1520             //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1521             double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
1522             double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1523             //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1524             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1525             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1526             //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);
1527             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1528             /* fixme: Cannot we cascade it to root more clearly? */
1529             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1531             dc->segments = g_slist_prepend(dc->segments, cbp);
1532         }
1534         dc->point1[0] = dc->point1[dc->npoints - 1];
1535         dc->point2[0] = dc->point2[dc->npoints - 1];
1536         dc->npoints = 1;
1537     } else {
1538         draw_temporary_box(dc);
1539     }
1542 static void
1543 draw_temporary_box(SPDynaDrawContext *dc)
1545     sp_curve_reset(dc->currentcurve);
1547     sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
1548     for (gint i = dc->npoints-2; i >= 0; i--) {
1549         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
1550     }
1551     for (gint i = 0; i < dc->npoints; i++) {
1552         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
1553     }
1554     if (dc->npoints >= 2) {
1555         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);
1556     }
1558     sp_curve_closepath(dc->currentcurve);
1559     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1562 /*
1563   Local Variables:
1564   mode:c++
1565   c-file-style:"stroustrup"
1566   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1567   indent-tabs-mode:nil
1568   fill-column:99
1569   End:
1570 */
1571 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :