Code

silly error - lazy boolean evaluation bit me
[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     ddc->hatch_spacing_step = 0;
202     new (&ddc->hatch_pointer_past) std::list<double>();
203     new (&ddc->hatch_nearest_past) std::list<double>();
204     ddc->hatch_last_nearest = NR::Point(0,0);
205     ddc->hatch_last_pointer = NR::Point(0,0);
206     ddc->hatch_vector_accumulated = NR::Point(0,0);
207     ddc->hatch_escaped = false;
208     ddc->hatch_area = NULL;
209     ddc->hatch_item = NULL;
210     ddc->hatch_livarot_path = NULL;
212     ddc->trace_bg = false;
214     ddc->is_dilating = false;
217 static void
218 sp_dyna_draw_context_dispose(GObject *object)
220     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
222     if (ddc->hatch_area) {
223         gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
224         ddc->hatch_area = NULL;
225     }
227     if (ddc->dilate_area) {
228         gtk_object_destroy(GTK_OBJECT(ddc->dilate_area));
229         ddc->dilate_area = NULL;
230     }
232     if (ddc->accumulated) {
233         ddc->accumulated = sp_curve_unref(ddc->accumulated);
234     }
236     while (ddc->segments) {
237         gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
238         ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
239     }
241     if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
242     if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
243     if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
245     if (ddc->currentshape) {
246         gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
247         ddc->currentshape = NULL;
248     }
250     if (ddc->_message_context) {
251         delete ddc->_message_context;
252     }
254     G_OBJECT_CLASS(parent_class)->dispose(object);
256     ddc->hatch_pointer_past.~list();
257     ddc->hatch_nearest_past.~list();
260 static void
261 sp_dyna_draw_context_setup(SPEventContext *ec)
263     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
265     if (((SPEventContextClass *) parent_class)->setup)
266         ((SPEventContextClass *) parent_class)->setup(ec);
268     ddc->accumulated = sp_curve_new_sized(32);
269     ddc->currentcurve = sp_curve_new_sized(4);
271     ddc->cal1 = sp_curve_new_sized(32);
272     ddc->cal2 = sp_curve_new_sized(32);
274     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
275     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
276     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
277     /* fixme: Cannot we cascade it to root more clearly? */
278     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
280     {
281         SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
282         ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
283         sp_curve_unref(c);
284         sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
285         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
286         sp_canvas_item_hide(ddc->hatch_area);
287     }
289     {
290         SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
291         ddc->dilate_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
292         sp_curve_unref(c);
293         sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->dilate_area), 0x00000000,(SPWindRule)0);
294         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->dilate_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
295         sp_canvas_item_hide(ddc->dilate_area);
296     }
298     sp_event_context_read(ec, "mass");
299     sp_event_context_read(ec, "wiggle");
300     sp_event_context_read(ec, "angle");
301     sp_event_context_read(ec, "width");
302     sp_event_context_read(ec, "thinning");
303     sp_event_context_read(ec, "tremor");
304     sp_event_context_read(ec, "flatness");
305     sp_event_context_read(ec, "tracebackground");
306     sp_event_context_read(ec, "usepressure");
307     sp_event_context_read(ec, "usetilt");
308     sp_event_context_read(ec, "abs_width");
309     sp_event_context_read(ec, "keep_selected");
310     sp_event_context_read(ec, "cap_rounding");
312     ddc->is_drawing = false;
314     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
317 static void
318 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
320     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
322     if (!strcmp(key, "mass")) {
323         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
324         ddc->mass = CLAMP(dval, -1000.0, 1000.0);
325     } else if (!strcmp(key, "wiggle")) {
326         double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
327         ddc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
328     } else if (!strcmp(key, "angle")) {
329         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
330         ddc->angle = CLAMP (dval, -90, 90);
331     } else if (!strcmp(key, "width")) {
332         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
333         ddc->width = CLAMP(dval, -1000.0, 1000.0);
334     } else if (!strcmp(key, "thinning")) {
335         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
336         ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
337     } else if (!strcmp(key, "tremor")) {
338         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
339         ddc->tremor = CLAMP(dval, 0.0, 1.0);
340     } else if (!strcmp(key, "flatness")) {
341         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
342         ddc->flatness = CLAMP(dval, 0, 1.0);
343     } else if (!strcmp(key, "tracebackground")) {
344         ddc->trace_bg = (val && strcmp(val, "0"));
345     } else if (!strcmp(key, "usepressure")) {
346         ddc->usepressure = (val && strcmp(val, "0"));
347     } else if (!strcmp(key, "usetilt")) {
348         ddc->usetilt = (val && strcmp(val, "0"));
349     } else if (!strcmp(key, "abs_width")) {
350         ddc->abs_width = (val && strcmp(val, "0"));
351     } else if (!strcmp(key, "keep_selected")) {
352         ddc->keep_selected = (val && strcmp(val, "0"));
353     } else if (!strcmp(key, "cap_rounding")) {
354         ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
355     }
357     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
360 static double
361 flerp(double f0, double f1, double p)
363     return f0 + ( f1 - f0 ) * p;
366 /* Get normalized point */
367 static NR::Point
368 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
370     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
371     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
372     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
375 /* Get view point */
376 static NR::Point
377 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
379     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
380     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
381     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
384 static void
385 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
387     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
388     dc->vel = NR::Point(0,0);
389     dc->vel_max = 0;
390     dc->acc = NR::Point(0,0);
391     dc->ang = NR::Point(0,0);
392     dc->del = NR::Point(0,0);
395 static void
396 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
398     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
399         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
400     else
401         dc->pressure = DDC_DEFAULT_PRESSURE;
403     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
404         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
405     else
406         dc->xtilt = DDC_DEFAULT_TILT;
408     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
409         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
410     else
411         dc->ytilt = DDC_DEFAULT_TILT;
415 static gboolean
416 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
418     NR::Point n = sp_dyna_draw_get_npoint(dc, p);
420     /* Calculate mass and drag */
421     double const mass = flerp(1.0, 160.0, dc->mass);
422     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
424     /* Calculate force and acceleration */
425     NR::Point force = n - dc->cur;
427     // If force is below the absolute threshold DYNA_EPSILON,
428     // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
429     // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
430     // discard this move. 
431     // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
432     // especially bothersome at the start of the stroke where we don't yet have the inertia to
433     // smooth them out.
434     if ( NR::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && NR::L2(force) < DYNA_EPSILON_START)) {
435         return FALSE;
436     }
438     dc->acc = force / mass;
440     /* Calculate new velocity */
441     dc->vel += dc->acc;
443     if (NR::L2(dc->vel) > dc->vel_max)
444         dc->vel_max = NR::L2(dc->vel);
446     /* Calculate angle of drawing tool */
448     double a1;
449     if (dc->usetilt) {
450         // 1a. calculate nib angle from input device tilt:
451         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
453         if (length > 0) {
454             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
455             a1 = atan2(ang1);
456         }
457         else
458             a1 = 0.0;
459     }
460     else {
461         // 1b. fixed dc->angle (absolutely flat nib):
462         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
463         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
464         a1 = atan2(ang1);
465     }
467     // 2. perpendicular to dc->vel (absolutely non-flat nib):
468     gdouble const mag_vel = NR::L2(dc->vel);
469     if ( mag_vel < DYNA_EPSILON ) {
470         return FALSE;
471     }
472     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
474     // 3. Average them using flatness parameter:
475     // calculate angles
476     double a2 = atan2(ang2);
477     // flip a2 to force it to be in the same half-circle as a1
478     bool flipped = false;
479     if (fabs (a2-a1) > 0.5*M_PI) {
480         a2 += M_PI;
481         flipped = true;
482     }
483     // normalize a2
484     if (a2 > M_PI)
485         a2 -= 2*M_PI;
486     if (a2 < -M_PI)
487         a2 += 2*M_PI;
488     // find the flatness-weighted bisector angle, unflip if a2 was flipped
489     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
490     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
492     // Try to detect a sudden flip when the new angle differs too much from the previous for the
493     // current velocity; in that case discard this move
494     double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
495     if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
496         return FALSE;
497     }
499     // convert to point
500     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
502 //    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);
504     /* Apply drag */
505     dc->vel *= 1.0 - drag;
507     /* Update position */
508     dc->last = dc->cur;
509     dc->cur += dc->vel;
511     return TRUE;
514 static void
515 sp_dyna_draw_brush(SPDynaDrawContext *dc)
517     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
519     // How much velocity thins strokestyle
520     double vel_thin = flerp (0, 160, dc->vel_thin);
522     // Influence of pressure on thickness
523     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
525     // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
526     // drag)
527     NR::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
528     NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush); 
530     double trace_thick = 1;
531     if (dc->trace_bg) {
532         // pick single pixel
533         NRPixBlock pb;
534         int x = (int) floor(brush_w[NR::X]);
535         int y = (int) floor(brush_w[NR::Y]);
536         nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
537         sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
538         const unsigned char *s = NR_PIXBLOCK_PX(&pb);
539         double R = s[0] / 255.0;
540         double G = s[1] / 255.0;
541         double B = s[2] / 255.0;
542         double A = s[3] / 255.0;
543         double max = MAX (MAX (R, G), B);
544         double min = MIN (MIN (R, G), B);
545         double L = A * (max + min)/2 + (1 - A); // blend with white bg
546         trace_thick = 1 - L;
547         //g_print ("L %g thick %g\n", L, trace_thick);
548     }
550     double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
552     double tremble_left = 0, tremble_right = 0;
553     if (dc->tremor > 0) {
554         // obtain two normally distributed random variables, using polar Box-Muller transform
555         double x1, x2, w, y1, y2;
556         do {
557             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
558             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
559             w = x1 * x1 + x2 * x2;
560         } while ( w >= 1.0 );
561         w = sqrt( (-2.0 * log( w ) ) / w );
562         y1 = x1 * w;
563         y2 = x2 * w;
565         // deflect both left and right edges randomly and independently, so that:
566         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
567         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
568         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
569         // comparatively smooth and slow ones excessively jittery
570         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
571         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
572     }
574     if ( width < 0.02 * dc->width ) {
575         width = 0.02 * dc->width;
576     }
578     double dezoomify_factor = 0.05 * 1000;
579     if (!dc->abs_width) {
580         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
581     }
583     NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
584     NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
586     dc->point1[dc->npoints] = brush + del_left;
587     dc->point2[dc->npoints] = brush - del_right;
589     dc->del = 0.5*(del_left + del_right);
591     dc->npoints++;
594 double
595 get_dilate_radius (SPDynaDrawContext *dc)
597     // 10 times the pen width:
598     return 500 * dc->width/SP_EVENT_CONTEXT(dc)->desktop->current_zoom(); 
601 double
602 get_dilate_force (SPDynaDrawContext *dc)
604     double force = 4 * dc->pressure/SP_EVENT_CONTEXT(dc)->desktop->current_zoom(); 
605     if (force > 3) {
606         force += 8 * (force - 3);
607     }
608     return force;
611 bool
612 sp_ddc_dilate_recursive (SPItem *item, NR::Point p, bool expand, double radius, double offset)
614     bool did = false;
616     if (SP_IS_GROUP(item)) {
617         for (SPObject *child = sp_object_first_child(SP_OBJECT(item)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
618             if (SP_IS_ITEM(child)) {
619                 did = did || sp_ddc_dilate_recursive (SP_ITEM(child), p, expand, radius, offset);
620             }
621         }
623     } else if (SP_IS_PATH(item)) {
625         SPCurve *curve = NULL;
626         curve = sp_shape_get_curve(SP_SHAPE(item));
627         if (curve == NULL)
628             return false;
630         // skip those paths whose bboxes are entirely out of reach with our radius
631         NR::Maybe<NR::Rect> bbox = item->getBounds(sp_item_i2doc_affine(item));
632         if (bbox) {
633             bbox->growBy(radius);
634             if (!bbox->contains(p)) {
635                 return false;
636             }
637         }
639         Path *orig = Path_for_item(item, false);
640         if (orig == NULL) {
641             sp_curve_unref(curve);
642             return false;
643         }
644         Path *res = new Path;
645         res->SetBackData(false);
647         Shape *theShape = new Shape;
648         Shape *theRes = new Shape;
650         orig->ConvertWithBackData(0.05);
651         orig->Fill(theShape, 0);
653         SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
654         gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
655         if (val && strcmp(val, "nonzero") == 0)
656         {
657             theRes->ConvertToShape(theShape, fill_nonZero);
658         }
659         else if (val && strcmp(val, "evenodd") == 0)
660         {
661             theRes->ConvertToShape(theShape, fill_oddEven);
662         }
663         else
664         {
665             theRes->ConvertToShape(theShape, fill_nonZero);
666         }
668         bool did_this = false;
669         NR::Matrix i2doc(sp_item_i2doc_affine(item));
670         if (theShape->MakeOffset(theRes, 
671                                  expand? offset : -offset,
672                                  join_straight, butt_straight,
673                                  true, p[NR::X], p[NR::Y], radius, &i2doc) == 0) // 0 means the shape was actually changed
674             did_this = true;
676         // the rest only makes sense if we actually changed the path
677         if (did_this) {
678             theRes->ConvertToShape(theShape, fill_positive);
680             res->Reset();
681             theRes->ConvertToForme(res);
683             if (offset >= 0.5)
684             {
685                 res->ConvertEvenLines(0.5);
686                 res->Simplify(0.5);
687             }
688             else
689             {
690                 res->ConvertEvenLines(0.5*offset);
691                 res->Simplify(0.5 * offset);
692             }
694             sp_curve_unref(curve);
695             if (res->descr_cmd.size() > 1) { 
696                 gchar *str = res->svg_dump_path();
697                 SP_OBJECT_REPR(item)->setAttribute("d", str);
698                 g_free(str);
699             } else {
700                 // TODO: if there's 0 or 1 node left, delete this path altogether
701             }
702         }
704         delete theShape;
705         delete theRes;
706         delete orig;
707         delete res;
709         if (did_this) 
710             did = true;
711     }
713     return did;
717 bool
718 sp_ddc_dilate (SPDynaDrawContext *dc, NR::Point p, bool expand)
720     Inkscape::Selection *selection = sp_desktop_selection(SP_EVENT_CONTEXT(dc)->desktop);
722     if (selection->isEmpty()) {
723         return false;
724     }
726     bool did = false;
727     double radius = get_dilate_radius(dc); 
728     double offset = get_dilate_force(dc); 
729     if (radius == 0 || offset == 0) {
730         return false;
731     }
733     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
734          items != NULL;
735          items = items->next) {
737         SPItem *item = (SPItem *) items->data;
739         if (sp_ddc_dilate_recursive (item, p, expand, radius, offset))
740             did = true;
742     }
744     return did;
747 void
748 sp_ddc_update_cursors (SPDynaDrawContext *dc)
750     if (dc->is_dilating) {
751         double radius = get_dilate_radius(dc);
752         NR::Matrix const sm (NR::scale(radius, radius) * NR::translate(SP_EVENT_CONTEXT(dc)->desktop->point()));
753         sp_canvas_item_affine_absolute(dc->dilate_area, sm);
754         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
755         sp_canvas_item_show(dc->dilate_area);
756     }
759 void
760 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
762     desktop->setToolboxAdjustmentValue (id, value);
765 static void
766 calligraphic_cancel(SPDynaDrawContext *dc)
768     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
769     dc->dragging = FALSE;
770     dc->is_drawing = false;
771     sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
772             /* Remove all temporary line segments */
773             while (dc->segments) {
774                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
775                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
776             }
777             /* reset accumulated curve */
778             sp_curve_reset(dc->accumulated);
779             clear_current(dc);
780             if (dc->repr) {
781                 dc->repr = NULL;
782             }
786 gint
787 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
788                                   GdkEvent *event)
790     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
791     SPDesktop *desktop = event_context->desktop;
793     gint ret = FALSE;
795     switch (event->type) {
796         case GDK_BUTTON_PRESS:
797             if ( event->button.button == 1 ) {
799                 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
801                 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
802                     return TRUE;
803                 }
805                 NR::Point const button_w(event->button.x,
806                                          event->button.y);
807                 NR::Point const button_dt(desktop->w2d(button_w));
808                 sp_dyna_draw_reset(dc, button_dt);
809                 sp_dyna_draw_extinput(dc, event);
810                 sp_dyna_draw_apply(dc, button_dt);
811                 sp_curve_reset(dc->accumulated);
812                 if (dc->repr) {
813                     dc->repr = NULL;
814                 }
816                 /* initialize first point */
817                 dc->npoints = 0;
819                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
820                                     ( GDK_KEY_PRESS_MASK |
821                                       GDK_BUTTON_RELEASE_MASK |
822                                       GDK_POINTER_MOTION_MASK |
823                                       GDK_BUTTON_PRESS_MASK ),
824                                     NULL,
825                                     event->button.time);
827                 ret = TRUE;
829                 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
830                 dc->is_drawing = true;
831             }
832             break;
833         case GDK_MOTION_NOTIFY:
834         {
835             NR::Point const motion_w(event->motion.x,
836                                      event->motion.y);
837             NR::Point motion_dt(desktop->w2d(motion_w));
838             sp_dyna_draw_extinput(dc, event);
840             // draw the dilating cursor
841             if (event->motion.state & GDK_MOD1_MASK) {
842                 double radius = get_dilate_radius(dc);
843                 NR::Matrix const sm (NR::scale(radius, radius) * NR::translate(desktop->w2d(motion_w)));
844                 sp_canvas_item_affine_absolute(dc->dilate_area, sm);
845                 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
846                 sp_canvas_item_show(dc->dilate_area);
848                 guint num = 0;
849                 if (!desktop->selection->isEmpty()) {
850                     num = g_slist_length((GSList *) desktop->selection->itemList());
851                 }
852                 if (num == 0) {
853                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select paths</b> to thin or thicken"));
854                 } else {
855                     dc->_message_context->setF(Inkscape::NORMAL_MESSAGE,
856                                            event->motion.state & GDK_SHIFT_MASK?
857                                            _("<b>Thickening %d</b> selected objects; without <b>Shift</b> to thin") :
858                                            _("<b>Thinning %d</b> selected objects; with <b>Shift</b> to thicken"), num);
859                 }
861             } else {
862                 dc->_message_context->clear();
863                 sp_canvas_item_hide(dc->dilate_area);
864             }
866             // dilating:
867             if (dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) && event->motion.state & GDK_MOD1_MASK) {  
868                 sp_ddc_dilate (dc, desktop->dt2doc(motion_dt), event->motion.state & GDK_SHIFT_MASK? true : false);
869                 dc->is_dilating = true;
870                 // it's slow, so prevent clogging up with events
871                 gobble_motion_events(GDK_BUTTON1_MASK);
872                 return TRUE;
873             }
876             // for hatching:
877             double hatch_dist = 0;
878             NR::Point hatch_unit_vector(0,0);
879             NR::Point nearest(0,0);
880             NR::Point pointer(0,0);
881             NR::Matrix motion_to_curve(NR::identity());
883             if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
885                 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
886                 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
887                     // One item selected, and it's a path;
888                     // let's try to track it as a guide
890                     if (selected != dc->hatch_item) {
891                         dc->hatch_item = selected;
892                         if (dc->hatch_livarot_path)
893                             delete dc->hatch_livarot_path;
894                         dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
895                         dc->hatch_livarot_path->ConvertWithBackData(0.01);
896                     }
898                     // calculate pointer point in the guide item's coords
899                     motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
900                     pointer = motion_dt * motion_to_curve;
902                     // calculate the nearest point on the guide path
903                     NR::Maybe<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
904                     nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
907                     // distance from pointer to nearest
908                     hatch_dist = NR::L2(pointer - nearest);
909                     // unit-length vector
910                     hatch_unit_vector = (pointer - nearest)/hatch_dist;
912                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
913                 } else {
914                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
915                 }
916             } 
918             if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
919                 dc->dragging = TRUE;
921                 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
923 #define SPEED_ELEMENTS 12
924 #define SPEED_MIN 0.12
925 #define SPEED_NORMAL 0.65
927                     // speed is the movement of the nearest point along the guide path, divided by
928                     // the movement of the pointer at the same period; it is averaged for the last
929                     // SPEED_ELEMENTS motion events.  Normally, as you track the guide path, speed
930                     // is about 1, i.e. the nearest point on the path is moved by about the same
931                     // distance as the pointer. If the speed starts to decrease, we are losing
932                     // contact with the guide; if it drops below SPEED_MIN, we are on our own and
933                     // not attracted to guide anymore. Most often this happens when you have
934                     // tracked to the end of a guide calligraphic stroke and keep moving
935                     // further. We try to handle this situation gracefully: not stick with the
936                     // guide forever but let go of it smoothly and without sharp jerks (non-zero
937                     // mass recommended; with zero mass, jerks are still quite noticeable).
939                     double speed = 1;
940                     if (NR::L2(dc->hatch_last_nearest) != 0) {
941                         // the distance nearest moved since the last motion event
942                         double nearest_moved = NR::L2(nearest - dc->hatch_last_nearest);
943                         // the distance pointer moved since the last motion event
944                         double pointer_moved = NR::L2(pointer - dc->hatch_last_pointer);
945                         // store them in stacks limited to SPEED_ELEMENTS
946                         dc->hatch_nearest_past.push_front(nearest_moved);
947                         if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
948                             dc->hatch_nearest_past.pop_back();
949                         dc->hatch_pointer_past.push_front(pointer_moved);
950                         if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
951                             dc->hatch_pointer_past.pop_back();
953                         // If the stacks are full,
954                         if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
955                             // calculate the sums of all stored movements
956                             double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
957                             double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
958                             // and divide to get the speed
959                             speed = nearest_sum/pointer_sum;
960                             //g_print ("nearest sum %g  pointer_sum %g  speed %g\n", nearest_sum, pointer_sum, speed);
961                         }
962                     }
964                     if (   dc->hatch_escaped  // already escaped, do not reattach
965                         || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
966                         || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
967                         ) {
968                         // We are NOT attracted to the guide!
970                         //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);
972                         // Remember hatch_escaped so we don't get
973                         // attracted again until the end of this stroke
974                         dc->hatch_escaped = true;
976                     } else {
978                         // Calculate angle cosine of this vector-to-guide and all past vectors
979                         // summed, to detect if we accidentally flipped to the other side of the
980                         // guide
981                         double dot = NR::dot (pointer - nearest, dc->hatch_vector_accumulated);
982                         dot /= NR::L2(pointer - nearest) * NR::L2(dc->hatch_vector_accumulated);
984                         if (dc->hatch_spacing != 0) { // spacing was already set
985                             double target;
986                             if (speed > SPEED_NORMAL) {
987                                 // all ok, strictly obey the spacing
988                                 target = dc->hatch_spacing;
989                             } else {
990                                 // looks like we're starting to lose speed,
991                                 // so _gradually_ let go attraction to prevent jerks
992                                 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;                            
993                             }
994                             if (!isNaN(dot) && dot < -0.5) {// flip
995                                 target = -target;
996                             }
998                             // This is the track pointer that we will use instead of the real one
999                             NR::Point new_pointer = nearest + target * hatch_unit_vector;
1001                             // some limited feedback: allow persistent pulling to slightly change
1002                             // the spacing
1003                             dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
1005                             // return it to the desktop coords
1006                             motion_dt = new_pointer * motion_to_curve.inverse();
1008                         } else {
1009                             // this is the first motion event, set the dist 
1010                             dc->hatch_spacing = hatch_dist;
1011                         }
1013                         // remember last points
1014                         dc->hatch_last_pointer = pointer;
1015                         dc->hatch_last_nearest = nearest;
1016                         dc->hatch_vector_accumulated += (pointer - nearest);
1017                     }
1019                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
1021                 } else {
1022                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
1023                 }
1025                 if (!sp_dyna_draw_apply(dc, motion_dt)) {
1026                     ret = TRUE;
1027                     break;
1028                 }
1030                 if ( dc->cur != dc->last ) {
1031                     sp_dyna_draw_brush(dc);
1032                     g_assert( dc->npoints > 0 );
1033                     fit_and_split(dc, FALSE);
1034                 }
1035                 ret = TRUE;
1036             }
1038             // Draw the hatching circle if necessary
1039             if (event->motion.state & GDK_CONTROL_MASK) { 
1040                 if (dc->hatch_spacing == 0 && hatch_dist != 0) { 
1041                     // Haven't set spacing yet: gray, center free, update radius live
1042                     NR::Point c = desktop->w2d(motion_w);
1043                     NR::Matrix const sm (NR::scale(hatch_dist, hatch_dist) * NR::translate(c));
1044                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1045                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1046                     sp_canvas_item_show(dc->hatch_area);
1047                 } else if (dc->dragging && !dc->hatch_escaped) {
1048                     // Tracking: green, center snapped, fixed radius
1049                     NR::Point c = motion_dt;
1050                     NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1051                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1052                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1053                     sp_canvas_item_show(dc->hatch_area);
1054                 } else if (dc->dragging && dc->hatch_escaped) {
1055                     // Tracking escaped: red, center free, fixed radius
1056                     NR::Point c = desktop->w2d(motion_w);
1057                     NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1059                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1060                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1061                     sp_canvas_item_show(dc->hatch_area);
1062                 } else {
1063                     // Not drawing but spacing set: gray, center snapped, fixed radius
1064                     NR::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
1065                     if (!isNaN(c[NR::X]) && !isNaN(c[NR::Y])) {
1066                         NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1067                         sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1068                         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1069                         sp_canvas_item_show(dc->hatch_area);
1070                     }
1071                 }
1072             } else {
1073                 sp_canvas_item_hide(dc->hatch_area);
1074             }
1075         }
1076         break;
1079     case GDK_BUTTON_RELEASE:
1080         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
1081         sp_canvas_end_forced_full_redraws(desktop->canvas);
1082         dc->is_drawing = false;
1084         if ( dc->is_dilating && event->button.button == 1 ) {
1085             dc->is_dilating = false;
1086             sp_document_done(sp_desktop_document(SP_EVENT_CONTEXT(dc)->desktop), 
1087                          SP_VERB_CONTEXT_CALLIGRAPHIC,
1088                          (event->button.state & GDK_SHIFT_MASK ? _("Thicken paths") : _("Thin paths")));
1089             ret = TRUE;
1090         } else if ( dc->dragging && event->button.button == 1 ) {
1091             dc->dragging = FALSE;
1093             NR::Point const motion_w(event->button.x, event->button.y);
1094             NR::Point const motion_dt(desktop->w2d(motion_w));
1095             sp_dyna_draw_apply(dc, motion_dt);
1097             /* Remove all temporary line segments */
1098             while (dc->segments) {
1099                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
1100                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
1101             }
1103             /* Create object */
1104             fit_and_split(dc, TRUE);
1105             accumulate_calligraphic(dc);
1106             set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK); // performs document_done
1108             /* reset accumulated curve */
1109             sp_curve_reset(dc->accumulated);
1111             clear_current(dc);
1112             if (dc->repr) {
1113                 dc->repr = NULL;
1114             }
1116             if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
1117             if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
1118             dc->hatch_last_nearest = NR::Point(0,0);
1119             dc->hatch_last_pointer = NR::Point(0,0);
1120             dc->hatch_vector_accumulated = NR::Point(0,0);
1121             dc->hatch_escaped = false;
1122             dc->hatch_item = NULL;
1123             dc->hatch_livarot_path = NULL;
1125             if (dc->hatch_spacing != 0 && !dc->keep_selected) { 
1126                 // we do not select the newly drawn path, so increase spacing by step
1127                 if (dc->hatch_spacing_step == 0) {
1128                     dc->hatch_spacing_step = dc->hatch_spacing;
1129                 }
1130                 dc->hatch_spacing += dc->hatch_spacing_step;
1131             }
1133             dc->_message_context->clear();
1134             ret = TRUE;
1135         }
1136         break;
1138     case GDK_KEY_PRESS:
1139         switch (get_group0_keyval (&event->key)) {
1140         case GDK_Up:
1141         case GDK_KP_Up:
1142             if (!MOD__CTRL_ONLY) {
1143                 dc->angle += 5.0;
1144                 if (dc->angle > 90.0)
1145                     dc->angle = 90.0;
1146                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
1147                 ret = TRUE;
1148             }
1149             break;
1150         case GDK_Down:
1151         case GDK_KP_Down:
1152             if (!MOD__CTRL_ONLY) {
1153                 dc->angle -= 5.0;
1154                 if (dc->angle < -90.0)
1155                     dc->angle = -90.0;
1156                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
1157                 ret = TRUE;
1158             }
1159             break;
1160         case GDK_Right:
1161         case GDK_KP_Right:
1162             if (!MOD__CTRL_ONLY) {
1163                 dc->width += 0.01;
1164                 if (dc->width > 1.0)
1165                     dc->width = 1.0;
1166                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
1167                 sp_ddc_update_cursors(dc);
1168                 ret = TRUE;
1169             }
1170             break;
1171         case GDK_Left:
1172         case GDK_KP_Left:
1173             if (!MOD__CTRL_ONLY) {
1174                 dc->width -= 0.01;
1175                 if (dc->width < 0.01)
1176                     dc->width = 0.01;
1177                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1178                 sp_ddc_update_cursors(dc);
1179                 ret = TRUE;
1180             }
1181             break;
1182         case GDK_Home:
1183         case GDK_KP_Home:
1184             dc->width = 0.01;
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_End:
1190         case GDK_KP_End:
1191             dc->width = 1.0;
1192             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1193             sp_ddc_update_cursors(dc);
1194             ret = TRUE;
1195             break;
1196         case GDK_x:
1197         case GDK_X:
1198             if (MOD__ALT_ONLY) {
1199                 desktop->setToolboxFocusTo ("altx-calligraphy");
1200                 ret = TRUE;
1201             }
1202             break;
1203         case GDK_Escape:
1204             if (dc->is_drawing) {
1205                 // if drawing, cancel, otherwise pass it up for deselecting
1206                 calligraphic_cancel (dc);
1207                 ret = TRUE;
1208             }
1209             break;
1210         case GDK_z:
1211         case GDK_Z:
1212             if (MOD__CTRL_ONLY && dc->is_drawing) {
1213                 // if drawing, cancel, otherwise pass it up for undo
1214                 calligraphic_cancel (dc);
1215                 ret = TRUE;
1216             }
1217             break;
1218         case GDK_Meta_L:
1219         case GDK_Meta_R:
1220             event_context->cursor_shape = cursor_thicken_xpm;
1221             sp_event_context_update_cursor(event_context);
1222             break;
1223         case GDK_Alt_L:
1224         case GDK_Alt_R:
1225             if (MOD__SHIFT) {
1226                 event_context->cursor_shape = cursor_thicken_xpm;
1227                 sp_event_context_update_cursor(event_context);
1228             } else {
1229                 event_context->cursor_shape = cursor_thin_xpm;
1230                 sp_event_context_update_cursor(event_context);
1231             }
1232             break;
1233         case GDK_Shift_L:
1234         case GDK_Shift_R:
1235             if (MOD__ALT) {
1236                 event_context->cursor_shape = cursor_thicken_xpm;
1237                 sp_event_context_update_cursor(event_context);
1238             }
1239             break;
1240         default:
1241             break;
1242         }
1243         break;
1245     case GDK_KEY_RELEASE:
1246         switch (get_group0_keyval(&event->key)) {
1247             case GDK_Control_L:
1248             case GDK_Control_R:
1249                 dc->_message_context->clear();
1250                 dc->hatch_spacing = 0;
1251                 dc->hatch_spacing_step = 0;
1252                 break;
1253             case GDK_Alt_L:
1254             case GDK_Alt_R:
1255                 event_context->cursor_shape = cursor_calligraphy_xpm;
1256                 sp_event_context_update_cursor(event_context);
1257                 break;
1258             case GDK_Shift_L:
1259             case GDK_Shift_R:
1260                 if (MOD__ALT) {
1261                     event_context->cursor_shape = cursor_thin_xpm;
1262                     sp_event_context_update_cursor(event_context);
1263                 }
1264                 break;
1265             case GDK_Meta_L:
1266             case GDK_Meta_R:
1267                 event_context->cursor_shape = cursor_calligraphy_xpm;
1268                 sp_event_context_update_cursor(event_context);
1269             break;
1270             default:
1271                 break;
1272         }
1274     default:
1275         break;
1276     }
1278     if (!ret) {
1279         if (((SPEventContextClass *) parent_class)->root_handler) {
1280             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1281         }
1282     }
1284     return ret;
1288 static void
1289 clear_current(SPDynaDrawContext *dc)
1291     /* reset bpath */
1292     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
1293     /* reset curve */
1294     sp_curve_reset(dc->currentcurve);
1295     sp_curve_reset(dc->cal1);
1296     sp_curve_reset(dc->cal2);
1297     /* reset points */
1298     dc->npoints = 0;
1301 static void
1302 set_to_accumulated(SPDynaDrawContext *dc, bool unionize)
1304     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1306     if (!sp_curve_empty(dc->accumulated)) {
1307         NArtBpath *abp;
1308         gchar *str;
1310         if (!dc->repr) {
1311             /* Create object */
1312             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1313             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1315             /* Set style */
1316             sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
1318             dc->repr = repr;
1320             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
1321             Inkscape::GC::release(dc->repr);
1322             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
1323             item->updateRepr();
1324         }
1325         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
1326         str = sp_svg_write_path(abp);
1327         g_assert( str != NULL );
1328         g_free(abp);
1329         dc->repr->setAttribute("d", str);
1330         g_free(str);
1332         if (unionize) {
1333             sp_desktop_selection(desktop)->add(dc->repr);
1334             sp_selected_path_union_skip_undo();
1335         } else {
1336             if (dc->keep_selected) {
1337                 sp_desktop_selection(desktop)->set(dc->repr);
1338             } 
1339         }
1341     } else {
1342         if (dc->repr) {
1343             sp_repr_unparent(dc->repr);
1344         }
1345         dc->repr = NULL;
1346     }
1348     sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC, 
1349                      _("Draw calligraphic stroke"));
1352 static void
1353 add_cap(SPCurve *curve,
1354         NR::Point const &pre, NR::Point const &from,
1355         NR::Point const &to, NR::Point const &post,
1356         double rounding)
1358     NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
1359     double mag = NR::L2(vel);
1361     NR::Point v_in = from - pre;
1362     double mag_in = NR::L2(v_in);
1363     if ( mag_in > DYNA_EPSILON ) {
1364         v_in = mag * v_in / mag_in;
1365     } else {
1366         v_in = NR::Point(0, 0);
1367     }
1369     NR::Point v_out = to - post;
1370     double mag_out = NR::L2(v_out);
1371     if ( mag_out > DYNA_EPSILON ) {
1372         v_out = mag * v_out / mag_out;
1373     } else {
1374         v_out = NR::Point(0, 0);
1375     }
1377     if ( NR::L2(v_in) > DYNA_EPSILON || NR::L2(v_out) > DYNA_EPSILON ) {
1378         sp_curve_curveto(curve, from + v_in, to + v_out, to);
1379     }
1382 static void
1383 accumulate_calligraphic(SPDynaDrawContext *dc)
1385     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
1386         sp_curve_reset(dc->accumulated); /*  Is this required ?? */
1387         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
1389         g_assert(dc->cal1->end > 1);
1390         g_assert(rev_cal2->end > 1);
1391         g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
1392         g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
1393         g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
1394         g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
1395         g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
1396         g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
1398         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
1400         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);
1402         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
1404         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);
1406         sp_curve_closepath(dc->accumulated);
1408         sp_curve_unref(rev_cal2);
1410         sp_curve_reset(dc->cal1);
1411         sp_curve_reset(dc->cal2);
1412     }
1415 static double square(double const x)
1417     return x * x;
1420 static void
1421 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1423     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
1425 #ifdef DYNA_DRAW_VERBOSE
1426     g_print("[F&S:R=%c]", release?'T':'F');
1427 #endif
1429     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1430         return; // just clicked
1432     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1433 #define BEZIER_SIZE       4
1434 #define BEZIER_MAX_BEZIERS  8
1435 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1437 #ifdef DYNA_DRAW_VERBOSE
1438         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1439                 dc->npoints, release ? "TRUE" : "FALSE");
1440 #endif
1442         /* Current calligraphic */
1443         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
1444             /* dc->npoints > 0 */
1445             /* g_print("calligraphics(1|2) reset\n"); */
1446             sp_curve_reset(dc->cal1);
1447             sp_curve_reset(dc->cal2);
1449             sp_curve_moveto(dc->cal1, dc->point1[0]);
1450             sp_curve_moveto(dc->cal2, dc->point2[0]);
1451         }
1453         NR::Point b1[BEZIER_MAX_LENGTH];
1454         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1455                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1456         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1458         NR::Point b2[BEZIER_MAX_LENGTH];
1459         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1460                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1461         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1463         if ( nb1 != -1 && nb2 != -1 ) {
1464             /* Fit and draw and reset state */
1465 #ifdef DYNA_DRAW_VERBOSE
1466             g_print("nb1:%d nb2:%d\n", nb1, nb2);
1467 #endif
1468             /* CanvasShape */
1469             if (! release) {
1470                 sp_curve_reset(dc->currentcurve);
1471                 sp_curve_moveto(dc->currentcurve, b1[0]);
1472                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1473                     sp_curve_curveto(dc->currentcurve, bp1[1],
1474                                      bp1[2], bp1[3]);
1475                 }
1476                 sp_curve_lineto(dc->currentcurve,
1477                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
1478                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1479                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
1480                 }
1481                 // FIXME: dc->segments is always NULL at this point??
1482                 if (!dc->segments) { // first segment
1483                     add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
1484                 }
1485                 sp_curve_closepath(dc->currentcurve);
1486                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1487             }
1489             /* Current calligraphic */
1490             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1491                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
1492             }
1493             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1494                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
1495             }
1496         } else {
1497             /* fixme: ??? */
1498 #ifdef DYNA_DRAW_VERBOSE
1499             g_print("[fit_and_split] failed to fit-cubic.\n");
1500 #endif
1501             draw_temporary_box(dc);
1503             for (gint i = 1; i < dc->npoints; i++) {
1504                 sp_curve_lineto(dc->cal1, dc->point1[i]);
1505             }
1506             for (gint i = 1; i < dc->npoints; i++) {
1507                 sp_curve_lineto(dc->cal2, dc->point2[i]);
1508             }
1509         }
1511         /* Fit and draw and copy last point */
1512 #ifdef DYNA_DRAW_VERBOSE
1513         g_print("[%d]Yup\n", dc->npoints);
1514 #endif
1515         if (!release) {
1516             g_assert(!sp_curve_empty(dc->currentcurve));
1518             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1519                                                    SP_TYPE_CANVAS_BPATH,
1520                                                    NULL);
1521             SPCurve *curve = sp_curve_copy(dc->currentcurve);
1522             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1523             sp_curve_unref(curve);
1525             guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1526             //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1527             double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
1528             double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1529             //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1530             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1531             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1532             //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);
1533             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1534             /* fixme: Cannot we cascade it to root more clearly? */
1535             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1537             dc->segments = g_slist_prepend(dc->segments, cbp);
1538         }
1540         dc->point1[0] = dc->point1[dc->npoints - 1];
1541         dc->point2[0] = dc->point2[dc->npoints - 1];
1542         dc->npoints = 1;
1543     } else {
1544         draw_temporary_box(dc);
1545     }
1548 static void
1549 draw_temporary_box(SPDynaDrawContext *dc)
1551     sp_curve_reset(dc->currentcurve);
1553     sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
1554     for (gint i = dc->npoints-2; i >= 0; i--) {
1555         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
1556     }
1557     for (gint i = 0; i < dc->npoints; i++) {
1558         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
1559     }
1560     if (dc->npoints >= 2) {
1561         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);
1562     }
1564     sp_curve_closepath(dc->currentcurve);
1565     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1568 /*
1569   Local Variables:
1570   mode:c++
1571   c-file-style:"stroustrup"
1572   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1573   indent-tabs-mode:nil
1574   fill-column:99
1575   End:
1576 */
1577 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :