Code

ensure that final resting position is included in calligraphic stroke
[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-2006 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>
31 #include "svg/svg.h"
32 #include "display/canvas-bpath.h"
33 #include "display/bezier-utils.h"
35 #include <glib/gmem.h>
36 #include "macros.h"
37 #include "document.h"
38 #include "selection.h"
39 #include "desktop.h"
40 #include "desktop-events.h"
41 #include "desktop-handles.h"
42 #include "desktop-affine.h"
43 #include "desktop-style.h"
44 #include "message-context.h"
45 #include "pixmaps/cursor-calligraphy.xpm"
46 #include "pixmaps/cursor-calligraphy.pixbuf"
47 #include "dyna-draw-context.h"
48 #include "libnr/n-art-bpath.h"
49 #include "libnr/nr-path.h"
50 #include "xml/repr.h"
51 #include "context-fns.h"
52 #include "sp-item.h"
53 #include "inkscape.h"
54 #include "color.h"
56 #define DDC_RED_RGBA 0xff0000ff
58 #define SAMPLE_TIMEOUT 10
59 #define TOLERANCE_LINE 1.0
60 #define TOLERANCE_CALLIGRAPHIC 3.0
61 #define DYNA_EPSILON 0.5e-2
63 #define DYNA_MIN_WIDTH 1.0e-6
65 #define DRAG_MIN 0.0
66 #define DRAG_DEFAULT 1.0
67 #define DRAG_MAX 1.0
69 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
70 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
71 static void sp_dyna_draw_context_dispose(GObject *object);
73 static void sp_dyna_draw_context_setup(SPEventContext *ec);
74 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
75 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
77 static void clear_current(SPDynaDrawContext *dc);
78 static void set_to_accumulated(SPDynaDrawContext *dc);
79 static void add_cap(SPCurve *curve, NR::Point const &from, NR::Point const &to, double rounding);
80 static void accumulate_calligraphic(SPDynaDrawContext *dc);
82 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
84 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
85 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
86 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
87 static void draw_temporary_box(SPDynaDrawContext *dc);
90 static SPEventContextClass *parent_class;
92 GtkType
93 sp_dyna_draw_context_get_type(void)
94 {
95     static GType type = 0;
96     if (!type) {
97         GTypeInfo info = {
98             sizeof(SPDynaDrawContextClass),
99             NULL, NULL,
100             (GClassInitFunc) sp_dyna_draw_context_class_init,
101             NULL, NULL,
102             sizeof(SPDynaDrawContext),
103             4,
104             (GInstanceInitFunc) sp_dyna_draw_context_init,
105             NULL,   /* value_table */
106         };
107         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
108     }
109     return type;
112 static void
113 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
115     GObjectClass *object_class = (GObjectClass *) klass;
116     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
118     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
120     object_class->dispose = sp_dyna_draw_context_dispose;
122     event_context_class->setup = sp_dyna_draw_context_setup;
123     event_context_class->set = sp_dyna_draw_context_set;
124     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
127 static void
128 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
130     SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
132     event_context->cursor_shape = cursor_calligraphy_xpm;
133     event_context->cursor_pixbuf = gdk_pixbuf_new_from_inline(
134             -1,
135             cursor_calligraphy_pixbuf,
136             FALSE,
137             NULL);  
138     event_context->hot_x = 4;
139     event_context->hot_y = 4;
141     ddc->accumulated = NULL;
142     ddc->segments = NULL;
143     ddc->currentcurve = NULL;
144     ddc->currentshape = NULL;
145     ddc->npoints = 0;
146     ddc->cal1 = NULL;
147     ddc->cal2 = NULL;
148     ddc->repr = NULL;
150     /* DynaDraw values */
151     ddc->cur = NR::Point(0,0);
152     ddc->last = NR::Point(0,0);
153     ddc->vel = NR::Point(0,0);
154     ddc->acc = NR::Point(0,0);
155     ddc->ang = NR::Point(0,0);
156     ddc->del = NR::Point(0,0);
158     /* attributes */
159     ddc->dragging = FALSE;
161     ddc->mass = 0.3;
162     ddc->drag = DRAG_DEFAULT;
163     ddc->angle = 30.0;
164     ddc->width = 0.2;
166     ddc->vel_thin = 0.1;
167     ddc->flatness = 0.9;
168     ddc->cap_rounding = 0.0;
170     ddc->abs_width = false;
171     ddc->keep_selected = true;
174 static void
175 sp_dyna_draw_context_dispose(GObject *object)
177     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
179     if (ddc->accumulated) {
180         ddc->accumulated = sp_curve_unref(ddc->accumulated);
181     }
183     while (ddc->segments) {
184         gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
185         ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
186     }
188     if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
189     if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
190     if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
192     if (ddc->currentshape) {
193         gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
194         ddc->currentshape = NULL;
195     }
197     if (ddc->_message_context) {
198         delete ddc->_message_context;
199     }
201     G_OBJECT_CLASS(parent_class)->dispose(object);
204 static void
205 sp_dyna_draw_context_setup(SPEventContext *ec)
207     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
209     if (((SPEventContextClass *) parent_class)->setup)
210         ((SPEventContextClass *) parent_class)->setup(ec);
212     ddc->accumulated = sp_curve_new_sized(32);
213     ddc->currentcurve = sp_curve_new_sized(4);
215     ddc->cal1 = sp_curve_new_sized(32);
216     ddc->cal2 = sp_curve_new_sized(32);
218     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
219     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
220     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
221     /* fixme: Cannot we cascade it to root more clearly? */
222     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
224     sp_event_context_read(ec, "mass");
225     sp_event_context_read(ec, "drag");
226     sp_event_context_read(ec, "angle");
227     sp_event_context_read(ec, "width");
228     sp_event_context_read(ec, "thinning");
229     sp_event_context_read(ec, "tremor");
230     sp_event_context_read(ec, "flatness");
231     sp_event_context_read(ec, "usepressure");
232     sp_event_context_read(ec, "usetilt");
233     sp_event_context_read(ec, "abs_width");
234     sp_event_context_read(ec, "keep_selected");
235     sp_event_context_read(ec, "cap_rounding");
237     ddc->is_drawing = false;
239     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
242 static void
243 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
245     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
247     if (!strcmp(key, "mass")) {
248         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
249         ddc->mass = CLAMP(dval, -1000.0, 1000.0);
250     } else if (!strcmp(key, "drag")) {
251         double const dval = ( val ? g_ascii_strtod (val, NULL) : DRAG_DEFAULT );
252         ddc->drag = CLAMP(dval, DRAG_MIN, DRAG_MAX);
253     } else if (!strcmp(key, "angle")) {
254         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
255         ddc->angle = CLAMP (dval, -90, 90);
256     } else if (!strcmp(key, "width")) {
257         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
258         ddc->width = CLAMP(dval, -1000.0, 1000.0);
259     } else if (!strcmp(key, "thinning")) {
260         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
261         ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
262     } else if (!strcmp(key, "tremor")) {
263         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
264         ddc->tremor = CLAMP(dval, 0.0, 1.0);
265     } else if (!strcmp(key, "flatness")) {
266         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
267         ddc->flatness = CLAMP(dval, 0, 1.0);
268     } else if (!strcmp(key, "usepressure")) {
269         ddc->usepressure = (val && strcmp(val, "0"));
270     } else if (!strcmp(key, "usetilt")) {
271         ddc->usetilt = (val && strcmp(val, "0"));
272     } else if (!strcmp(key, "abs_width")) {
273         ddc->abs_width = (val && strcmp(val, "0"));
274     } else if (!strcmp(key, "keep_selected")) {
275         ddc->keep_selected = (val && strcmp(val, "0"));
276     } else if (!strcmp(key, "cap_rounding")) {
277         ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
278     }
280     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
283 static double
284 flerp(double f0, double f1, double p)
286     return f0 + ( f1 - f0 ) * p;
289 /* Get normalized point */
290 static NR::Point
291 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
293     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
294     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
295     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
298 /* Get view point */
299 static NR::Point
300 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
302     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
303     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
304     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
307 static void
308 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
310     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
311     dc->vel = NR::Point(0,0);
312     dc->acc = NR::Point(0,0);
313     dc->ang = NR::Point(0,0);
314     dc->del = NR::Point(0,0);
317 static void
318 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
320     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
321         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
322     else
323         dc->pressure = DDC_DEFAULT_PRESSURE;
325     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
326         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
327     else
328         dc->xtilt = DDC_DEFAULT_TILT;
330     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
331         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
332     else
333         dc->ytilt = DDC_DEFAULT_TILT;
337 static gboolean
338 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
340     NR::Point n = sp_dyna_draw_get_npoint(dc, p);
342     /* Calculate mass and drag */
343     double const mass = flerp(1.0, 160.0, dc->mass);
344     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
346     /* Calculate force and acceleration */
347     NR::Point force = n - dc->cur;
348     if ( NR::L2(force) < DYNA_EPSILON ) {
349         return FALSE;
350     }
352     dc->acc = force / mass;
354     /* Calculate new velocity */
355     dc->vel += dc->acc;
357     /* Calculate angle of drawing tool */
359     double a1;
360     if (dc->usetilt) {
361         // 1a. calculate nib angle from input device tilt:
362         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
364         if (length > 0) {
365             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
366             a1 = atan2(ang1);
367         }
368         else
369             a1 = 0.0;
370     }
371     else {
372         // 1b. fixed dc->angle (absolutely flat nib):
373         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
374         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
375         a1 = atan2(ang1);
376     }
378     // 2. perpendicular to dc->vel (absolutely non-flat nib):
379     gdouble const mag_vel = NR::L2(dc->vel);
380     if ( mag_vel < DYNA_EPSILON ) {
381         return FALSE;
382     }
383     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
385     // 3. Average them using flatness parameter:
386     // calculate angles
387     double a2 = atan2(ang2);
388     // flip a2 to force it to be in the same half-circle as a1
389     bool flipped = false;
390     if (fabs (a2-a1) > 0.5*M_PI) {
391         a2 += M_PI;
392         flipped = true;
393     }
394     // normalize a2
395     if (a2 > M_PI)
396         a2 -= 2*M_PI;
397     if (a2 < -M_PI)
398         a2 += 2*M_PI;
399     // find the flatness-weighted bisector angle, unflip if a2 was flipped
400     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
401     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
402     // convert to point
403     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
405     /* Apply drag */
406     dc->vel *= 1.0 - drag;
408     /* Update position */
409     dc->last = dc->cur;
410     dc->cur += dc->vel;
412     return TRUE;
415 static void
416 sp_dyna_draw_brush(SPDynaDrawContext *dc)
418     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
420     // How much velocity thins strokestyle
421     double vel_thin = flerp (0, 160, dc->vel_thin);
423     // Influence of pressure on thickness
424     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
426     double width = ( pressure_thick - vel_thin * NR::L2(dc->vel) ) * dc->width;
428     double tremble_left = 0, tremble_right = 0;
429     if (dc->tremor > 0) {
430         // obtain two normally distributed random variables, using polar Box-Muller transform
431         double x1, x2, w, y1, y2;
432         do {
433             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
434             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
435             w = x1 * x1 + x2 * x2;
436         } while ( w >= 1.0 );
437         w = sqrt( (-2.0 * log( w ) ) / w );
438         y1 = x1 * w;
439         y2 = x2 * w;
441         // deflect both left and right edges randomly and independently, so that:
442         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
443         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
444         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
445         // comparatively smooth and slow ones excessively jittery
446         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
447         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
448     }
450     if ( width < 0.02 * dc->width ) {
451         width = 0.02 * dc->width;
452     }
454     double dezoomify_factor = 0.05 * 1000;
455     if (!dc->abs_width) {
456         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
457     }
459     NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
460     NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
462     NR::Point abs_middle = sp_dyna_draw_get_vpoint(dc, dc->cur);
464     dc->point1[dc->npoints] = abs_middle + del_left;
465     dc->point2[dc->npoints] = abs_middle - del_right;
467     dc->del = 0.5*(del_left + del_right);
469     dc->npoints++;
472 void
473 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
475     desktop->setToolboxAdjustmentValue (id, value);
478 gint
479 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
480                                   GdkEvent *event)
482     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
483     SPDesktop *desktop = event_context->desktop;
485     gint ret = FALSE;
487     switch (event->type) {
488     case GDK_BUTTON_PRESS:
489         if ( event->button.button == 1 ) {
491             SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
493             if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
494                 return TRUE;
495             }
497             NR::Point const button_w(event->button.x,
498                                      event->button.y);
499             NR::Point const button_dt(desktop->w2d(button_w));
500             sp_dyna_draw_reset(dc, button_dt);
501             sp_dyna_draw_extinput(dc, event);
502             sp_dyna_draw_apply(dc, button_dt);
503             sp_curve_reset(dc->accumulated);
504             if (dc->repr) {
505                 dc->repr = NULL;
506             }
508             /* initialize first point */
509             dc->npoints = 0;
511             sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
512                                 ( GDK_KEY_PRESS_MASK |
513                                   GDK_BUTTON_RELEASE_MASK |
514                                   GDK_POINTER_MOTION_MASK |
515                                   GDK_BUTTON_PRESS_MASK ),
516                                 NULL,
517                                 event->button.time);
519             ret = TRUE;
521             dc->is_drawing = true;
522         }
523         break;
524     case GDK_MOTION_NOTIFY:
525         if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
526             dc->dragging = TRUE;
528             NR::Point const motion_w(event->motion.x,
529                                      event->motion.y);
530             NR::Point const motion_dt(desktop->w2d(motion_w));
532             sp_dyna_draw_extinput(dc, event);
533             if (!sp_dyna_draw_apply(dc, motion_dt)) {
534                 ret = TRUE;
535                 break;
536             }
538             if ( dc->cur != dc->last ) {
539                 sp_dyna_draw_brush(dc);
540                 g_assert( dc->npoints > 0 );
541                 fit_and_split(dc, FALSE);
542             }
543             ret = TRUE;
544         }
545         break;
547     case GDK_BUTTON_RELEASE:
548         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
549         dc->is_drawing = false;
551         if ( dc->dragging && event->button.button == 1 ) {
552             dc->dragging = FALSE;
554             NR::Point const motion_w(event->button.x, event->button.y);
555             NR::Point const motion_dt(desktop->w2d(motion_w));
556             sp_dyna_draw_apply(dc, motion_dt);
558             /* Remove all temporary line segments */
559             while (dc->segments) {
560                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
561                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
562             }
563             /* Create object */
564             fit_and_split(dc, TRUE);
565             accumulate_calligraphic(dc);
566             set_to_accumulated(dc); /* temporal implementation */
567             /* reset accumulated curve */
568             sp_curve_reset(dc->accumulated);
569             clear_current(dc);
570             if (dc->repr) {
571                 dc->repr = NULL;
572             }
573             ret = TRUE;
574         }
575         break;
576     case GDK_KEY_PRESS:
577         switch (get_group0_keyval (&event->key)) {
578         case GDK_Up:
579         case GDK_KP_Up:
580             if (!MOD__CTRL_ONLY) {
581                 dc->angle += 5.0;
582                 if (dc->angle > 90.0)
583                     dc->angle = 90.0;
584                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
585                 ret = TRUE;
586             }
587             break;
588         case GDK_Down:
589         case GDK_KP_Down:
590             if (!MOD__CTRL_ONLY) {
591                 dc->angle -= 5.0;
592                 if (dc->angle < -90.0)
593                     dc->angle = -90.0;
594                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
595                 ret = TRUE;
596             }
597             break;
598         case GDK_Right:
599         case GDK_KP_Right:
600             if (!MOD__CTRL_ONLY) {
601                 dc->width += 0.01;
602                 if (dc->width > 1.0)
603                     dc->width = 1.0;
604                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
605                 ret = TRUE;
606             }
607             break;
608         case GDK_Left:
609         case GDK_KP_Left:
610             if (!MOD__CTRL_ONLY) {
611                 dc->width -= 0.01;
612                 if (dc->width < 0.01)
613                     dc->width = 0.01;
614                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
615                 ret = TRUE;
616             }
617             break;
618         case GDK_x:
619         case GDK_X:
620             if (MOD__ALT_ONLY) {
621                 desktop->setToolboxFocusTo ("altx-calligraphy");
622                 ret = TRUE;
623             }
624             break;
625         case GDK_Escape:
626             sp_desktop_selection(desktop)->clear();
627             break;
629         default:
630             break;
631         }
632     default:
633         break;
634     }
636     if (!ret) {
637         if (((SPEventContextClass *) parent_class)->root_handler) {
638             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
639         }
640     }
642     return ret;
646 static void
647 clear_current(SPDynaDrawContext *dc)
649     /* reset bpath */
650     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
651     /* reset curve */
652     sp_curve_reset(dc->currentcurve);
653     sp_curve_reset(dc->cal1);
654     sp_curve_reset(dc->cal2);
655     /* reset points */
656     dc->npoints = 0;
659 static void
660 set_to_accumulated(SPDynaDrawContext *dc)
662     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
664     if (!sp_curve_empty(dc->accumulated)) {
665         NArtBpath *abp;
666         gchar *str;
668         if (!dc->repr) {
669             /* Create object */
670             Inkscape::XML::Node *repr = sp_repr_new("svg:path");
672             /* Set style */
673             sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
675             dc->repr = repr;
677             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
678             Inkscape::GC::release(dc->repr);
679             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
680             item->updateRepr();
681             if (dc->keep_selected) {
682                 sp_desktop_selection(desktop)->set(dc->repr);
683             } else {
684                 sp_desktop_selection(desktop)->clear();
685             }
686         }
687         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
688         str = sp_svg_write_path(abp);
689         g_assert( str != NULL );
690         g_free(abp);
691         dc->repr->setAttribute("d", str);
692         g_free(str);
693     } else {
694         if (dc->repr) {
695             sp_repr_unparent(dc->repr);
696         }
697         dc->repr = NULL;
698     }
700     sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC, 
701                      /* TODO: annotate */ "dyna-draw-context.cpp:689");
704 static void
705 add_cap(SPCurve *curve, NR::Point const &from, NR::Point const &to,
706         double rounding)
708     NR::Point vec = rounding * NR::rot90( ( to - from ) / sqrt(2.0) );
710     if ( NR::L2(vec) > DYNA_EPSILON ) {
711         sp_curve_curveto(curve, from + vec, to + vec, to);
712     }
715 static void
716 accumulate_calligraphic(SPDynaDrawContext *dc)
718     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
719         sp_curve_reset(dc->accumulated); /*  Is this required ?? */
720         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
721         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
722         add_cap(dc->accumulated, sp_curve_last_point(dc->cal1), sp_curve_first_point(rev_cal2), dc->cap_rounding);
723         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
724         add_cap(dc->accumulated, sp_curve_last_point(rev_cal2), sp_curve_first_point(dc->cal1), dc->cap_rounding);
725         sp_curve_closepath(dc->accumulated);
727         sp_curve_unref(rev_cal2);
729         sp_curve_reset(dc->cal1);
730         sp_curve_reset(dc->cal2);
731     }
734 static double square(double const x)
736     return x * x;
739 static void
740 fit_and_split(SPDynaDrawContext *dc, gboolean release)
742     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
744 #ifdef DYNA_DRAW_VERBOSE
745     g_print("[F&S:R=%c]", release?'T':'F');
746 #endif
748     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
749         return; // just clicked
751     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
752 #define BEZIER_SIZE       4
753 #define BEZIER_MAX_BEZIERS  8
754 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
756 #ifdef DYNA_DRAW_VERBOSE
757         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
758                 dc->npoints, release ? "TRUE" : "FALSE");
759 #endif
761         /* Current calligraphic */
762         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
763             /* dc->npoints > 0 */
764             /* g_print("calligraphics(1|2) reset\n"); */
765             sp_curve_reset(dc->cal1);
766             sp_curve_reset(dc->cal2);
768             sp_curve_moveto(dc->cal1, dc->point1[0]);
769             sp_curve_moveto(dc->cal2, dc->point2[0]);
770         }
772         NR::Point b1[BEZIER_MAX_LENGTH];
773         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
774                                                tolerance_sq, BEZIER_MAX_BEZIERS);
775         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
777         NR::Point b2[BEZIER_MAX_LENGTH];
778         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
779                                                tolerance_sq, BEZIER_MAX_BEZIERS);
780         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
782         if ( nb1 != -1 && nb2 != -1 ) {
783             /* Fit and draw and reset state */
784 #ifdef DYNA_DRAW_VERBOSE
785             g_print("nb1:%d nb2:%d\n", nb1, nb2);
786 #endif
787             /* CanvasShape */
788             if (! release) {
789                 sp_curve_reset(dc->currentcurve);
790                 sp_curve_moveto(dc->currentcurve, b1[0]);
791                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
792                     sp_curve_curveto(dc->currentcurve, bp1[1],
793                                      bp1[2], bp1[3]);
794                 }
795                 sp_curve_lineto(dc->currentcurve,
796                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
797                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
798                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
799                 }
800                 if (!dc->segments) {
801                     add_cap(dc->currentcurve, b2[0], b1[0], dc->cap_rounding);
802                 }
803                 sp_curve_closepath(dc->currentcurve);
804                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
805             }
807             /* Current calligraphic */
808             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
809                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
810             }
811             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
812                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
813             }
814         } else {
815             /* fixme: ??? */
816 #ifdef DYNA_DRAW_VERBOSE
817             g_print("[fit_and_split] failed to fit-cubic.\n");
818 #endif
819             draw_temporary_box(dc);
821             for (gint i = 1; i < dc->npoints; i++) {
822                 sp_curve_lineto(dc->cal1, dc->point1[i]);
823             }
824             for (gint i = 1; i < dc->npoints; i++) {
825                 sp_curve_lineto(dc->cal2, dc->point2[i]);
826             }
827         }
829         /* Fit and draw and copy last point */
830 #ifdef DYNA_DRAW_VERBOSE
831         g_print("[%d]Yup\n", dc->npoints);
832 #endif
833         if (!release) {
834             g_assert(!sp_curve_empty(dc->currentcurve));
836             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
837                                                    SP_TYPE_CANVAS_BPATH,
838                                                    NULL);
839             SPCurve *curve = sp_curve_copy(dc->currentcurve);
840             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
841             sp_curve_unref(curve);
843             guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
844             //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
845             double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
846             double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
847             //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
848             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
849             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
850             //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);
851             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
852             /* fixme: Cannot we cascade it to root more clearly? */
853             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
855             dc->segments = g_slist_prepend(dc->segments, cbp);
856         }
858         dc->point1[0] = dc->point1[dc->npoints - 1];
859         dc->point2[0] = dc->point2[dc->npoints - 1];
860         dc->npoints = 1;
861     } else {
862         draw_temporary_box(dc);
863     }
866 static void
867 draw_temporary_box(SPDynaDrawContext *dc)
869     sp_curve_reset(dc->currentcurve);
870     sp_curve_moveto(dc->currentcurve, dc->point1[0]);
871     for (gint i = 1; i < dc->npoints; i++) {
872         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
873     }
874     for (gint i = dc->npoints-1; i >= 0; i--) {
875         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
876     }
877     add_cap(dc->currentcurve, dc->point2[0], dc->point1[0], dc->cap_rounding);
878     sp_curve_closepath(dc->currentcurve);
879     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
882 /*
883   Local Variables:
884   mode:c++
885   c-file-style:"stroustrup"
886   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
887   indent-tabs-mode:nil
888   fill-column:99
889   End:
890 */
891 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :