Code

Get rid of the SP_DT_* macros which do nothing more than provide additional, confusin...
[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  *
11  * The original dynadraw code:
12  *   Paul Haeberli <paul@sgi.com>
13  *
14  * Copyright (C) 1998 The Free Software Foundation
15  * Copyright (C) 1999-2005 authors
16  * Copyright (C) 2001-2002 Ximian, Inc.
17  *
18  * Released under GNU GPL, read the file 'COPYING' for more information
19  */
21 #define noDYNA_DRAW_VERBOSE
23 #include "config.h"
25 #include <gtk/gtk.h>
26 #include <gdk/gdkkeysyms.h>
28 #include "svg/svg.h"
29 #include "display/canvas-bpath.h"
30 #include "display/bezier-utils.h"
32 #include "macros.h"
33 #include "document.h"
34 #include "selection.h"
35 #include "desktop.h"
36 #include "desktop-events.h"
37 #include "desktop-handles.h"
38 #include "desktop-affine.h"
39 #include "desktop-style.h"
40 #include "message-context.h"
41 #include "pixmaps/cursor-calligraphy.xpm"
42 #include "dyna-draw-context.h"
43 #include "libnr/n-art-bpath.h"
44 #include "libnr/nr-path.h"
45 #include "xml/repr.h"
46 #include "context-fns.h"
47 #include "sp-item.h"
49 #define DDC_RED_RGBA 0xff0000ff
51 #define SAMPLE_TIMEOUT 10
52 #define TOLERANCE_LINE 1.0
53 #define TOLERANCE_CALLIGRAPHIC 3.0
54 #define DYNA_EPSILON 1.0e-6
56 #define DYNA_MIN_WIDTH 1.0e-6
58 #define DRAG_MIN 0.0
59 #define DRAG_DEFAULT 1.0
60 #define DRAG_MAX 1.0
62 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
63 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
64 static void sp_dyna_draw_context_dispose(GObject *object);
66 static void sp_dyna_draw_context_setup(SPEventContext *ec);
67 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
68 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
70 static void clear_current(SPDynaDrawContext *dc);
71 static void set_to_accumulated(SPDynaDrawContext *dc);
72 static void accumulate_calligraphic(SPDynaDrawContext *dc);
74 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
75 static void fit_and_split_calligraphics(SPDynaDrawContext *ddc, gboolean release);
77 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
78 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
79 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
80 static void draw_temporary_box(SPDynaDrawContext *dc);
83 static SPEventContextClass *parent_class;
85 GtkType
86 sp_dyna_draw_context_get_type(void)
87 {
88     static GType type = 0;
89     if (!type) {
90         GTypeInfo info = {
91             sizeof(SPDynaDrawContextClass),
92             NULL, NULL,
93             (GClassInitFunc) sp_dyna_draw_context_class_init,
94             NULL, NULL,
95             sizeof(SPDynaDrawContext),
96             4,
97             (GInstanceInitFunc) sp_dyna_draw_context_init,
98             NULL,   /* value_table */
99         };
100         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
101     }
102     return type;
105 static void
106 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
108     GObjectClass *object_class = (GObjectClass *) klass;
109     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
111     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
113     object_class->dispose = sp_dyna_draw_context_dispose;
115     event_context_class->setup = sp_dyna_draw_context_setup;
116     event_context_class->set = sp_dyna_draw_context_set;
117     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
120 static void
121 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
123     SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
125     event_context->cursor_shape = cursor_calligraphy_xpm;
126     event_context->hot_x = 4;
127     event_context->hot_y = 4;
129     ddc->accumulated = NULL;
130     ddc->segments = NULL;
131     ddc->currentcurve = NULL;
132     ddc->currentshape = NULL;
133     ddc->npoints = 0;
134     ddc->cal1 = NULL;
135     ddc->cal2 = NULL;
136     ddc->repr = NULL;
138     /* DynaDraw values */
139     ddc->cur = NR::Point(0,0);
140     ddc->last = NR::Point(0,0);
141     ddc->vel = NR::Point(0,0);
142     ddc->acc = NR::Point(0,0);
143     ddc->ang = NR::Point(0,0);
144     ddc->del = NR::Point(0,0);
146     /* attributes */
147     ddc->use_timeout = FALSE;
148     ddc->timer_id = 0;
149     ddc->dragging = FALSE;
151     ddc->mass = 0.3;
152     ddc->drag = DRAG_DEFAULT;
153     ddc->angle = 30.0;
154     ddc->width = 0.2;
156     ddc->vel_thin = 0.1;
157     ddc->flatness = 0.9;
160 static void
161 sp_dyna_draw_context_dispose(GObject *object)
163     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
165     if (ddc->accumulated) {
166         ddc->accumulated = sp_curve_unref(ddc->accumulated);
167     }
169     while (ddc->segments) {
170         gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
171         ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
172     }
174     if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
175     if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
176     if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
178     if (ddc->currentshape) {
179         gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
180         ddc->currentshape = NULL;
181     }
183     if (ddc->_message_context) {
184         delete ddc->_message_context;
185     }
187     G_OBJECT_CLASS(parent_class)->dispose(object);
190 static void
191 sp_dyna_draw_context_setup(SPEventContext *ec)
193     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
195     if (((SPEventContextClass *) parent_class)->setup)
196         ((SPEventContextClass *) parent_class)->setup(ec);
198     ddc->accumulated = sp_curve_new_sized(32);
199     ddc->currentcurve = sp_curve_new_sized(4);
201     ddc->cal1 = sp_curve_new_sized(32);
202     ddc->cal2 = sp_curve_new_sized(32);
204     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
205     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
206     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
207     /* fixme: Cannot we cascade it to root more clearly? */
208     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
210     sp_event_context_read(ec, "mass");
211     sp_event_context_read(ec, "drag");
212     sp_event_context_read(ec, "angle");
213     sp_event_context_read(ec, "width");
214     sp_event_context_read(ec, "thinning");
215     sp_event_context_read(ec, "tremor");
216     sp_event_context_read(ec, "flatness");
217     sp_event_context_read(ec, "usepressure");
218     sp_event_context_read(ec, "usetilt");
220     ddc->is_drawing = false;
222     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
225 static void
226 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
228     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
230     if (!strcmp(key, "mass")) {
231         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
232         ddc->mass = CLAMP(dval, -1000.0, 1000.0);
233     } else if (!strcmp(key, "drag")) {
234         double const dval = ( val ? g_ascii_strtod (val, NULL) : DRAG_DEFAULT );
235         ddc->drag = CLAMP(dval, DRAG_MIN, DRAG_MAX);
236     } else if (!strcmp(key, "angle")) {
237         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
238         ddc->angle = CLAMP (dval, -90, 90);
239     } else if (!strcmp(key, "width")) {
240         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
241         ddc->width = CLAMP(dval, -1000.0, 1000.0);
242     } else if (!strcmp(key, "thinning")) {
243         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
244         ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
245     } else if (!strcmp(key, "tremor")) {
246         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
247         ddc->tremor = CLAMP(dval, 0.0, 1.0);
248     } else if (!strcmp(key, "flatness")) {
249         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
250         ddc->flatness = CLAMP(dval, 0, 1.0);
251     } else if (!strcmp(key, "usepressure")) {
252         ddc->usepressure = (val && strcmp(val, "0"));
253     } else if (!strcmp(key, "usetilt")) {
254         ddc->usetilt = (val && strcmp(val, "0"));
255     }
257     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
260 static double
261 flerp(double f0, double f1, double p)
263     return f0 + ( f1 - f0 ) * p;
266 /* Get normalized point */
267 static NR::Point
268 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
270     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
271     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
272     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
275 /* Get view point */
276 static NR::Point
277 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
279     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
280     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
281     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
284 static void
285 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
287     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
288     dc->vel = NR::Point(0,0);
289     dc->acc = NR::Point(0,0);
290     dc->ang = NR::Point(0,0);
291     dc->del = NR::Point(0,0);
294 static void
295 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
297     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
298         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
299     else
300         dc->pressure = DDC_DEFAULT_PRESSURE;
302     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
303         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
304     else
305         dc->xtilt = DDC_DEFAULT_TILT;
307     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
308         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
309     else
310         dc->ytilt = DDC_DEFAULT_TILT;
314 static gboolean
315 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
317     NR::Point n = sp_dyna_draw_get_npoint(dc, p);
319     /* Calculate mass and drag */
320     double const mass = flerp(1.0, 160.0, dc->mass);
321     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
323     /* Calculate force and acceleration */
324     NR::Point force = n - dc->cur;
325     if ( NR::L2(force) < DYNA_EPSILON ) {
326         return FALSE;
327     }
329     dc->acc = force / mass;
331     /* Calculate new velocity */
332     dc->vel += dc->acc;
334     /* Calculate angle of drawing tool */
336     double a1;
337     if (dc->usetilt) {
338         // 1a. calculate nib angle from input device tilt:
339         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
341         if (length > 0) {
342             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
343             a1 = atan2(ang1);
344         }
345         else
346             a1 = 0.0;
347     }
348     else {
349         // 1b. fixed dc->angle (absolutely flat nib):
350         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
351         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
352         a1 = atan2(ang1);
353     }
355     // 2. perpendicular to dc->vel (absolutely non-flat nib):
356     gdouble const mag_vel = NR::L2(dc->vel);
357     if ( mag_vel < DYNA_EPSILON ) {
358         return FALSE;
359     }
360     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
362     // 3. Average them using flatness parameter:
363     // calculate angles
364     double a2 = atan2(ang2);
365     // flip a2 to force it to be in the same half-circle as a1
366     bool flipped = false;
367     if (fabs (a2-a1) > 0.5*M_PI) {
368         a2 += M_PI;
369         flipped = true;
370     }
371     // normalize a2
372     if (a2 > M_PI)
373         a2 -= 2*M_PI;
374     if (a2 < -M_PI)
375         a2 += 2*M_PI;
376     // find the flatness-weighted bisector angle, unflip if a2 was flipped
377     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
378     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
379     // convert to point
380     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
382     /* Apply drag */
383     dc->vel *= 1.0 - drag;
385     /* Update position */
386     dc->last = dc->cur;
387     dc->cur += dc->vel;
389     return TRUE;
392 static void
393 sp_dyna_draw_brush(SPDynaDrawContext *dc)
395     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
397     // How much velocity thins strokestyle
398     double vel_thin = flerp (0, 160, dc->vel_thin);
400     // Influence of pressure on thickness
401     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
403     double width = ( pressure_thick - vel_thin * NR::L2(dc->vel) ) * dc->width;
405     double tremble_left = 0, tremble_right = 0;
406     if (dc->tremor > 0) {
407         // obtain two normally distributed random variables, using polar Box-Muller transform
408         double x1, x2, w, y1, y2;
409         do {
410             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
411             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
412             w = x1 * x1 + x2 * x2;
413         } while ( w >= 1.0 );
414         w = sqrt( (-2.0 * log( w ) ) / w );
415         y1 = x1 * w;
416         y2 = x2 * w;
418         // deflect both left and right edges randomly and independently, so that:
419         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
420         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
421         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
422         // comparatively smooth and slow ones excessively jittery
423         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
424         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
425     }
427     if ( width < 0.02 * dc->width ) {
428         width = 0.02 * dc->width;
429     }
431     NR::Point del_left = 0.05 * (width + tremble_left) * dc->ang;
432     NR::Point del_right = 0.05 * (width + tremble_right) * dc->ang;
434     dc->point1[dc->npoints] = sp_dyna_draw_get_vpoint(dc, dc->cur + del_left);
435     dc->point2[dc->npoints] = sp_dyna_draw_get_vpoint(dc, dc->cur - del_right);
437     dc->del = 0.5*(del_left + del_right);
439     dc->npoints++;
442 static gint
443 sp_dyna_draw_timeout_handler(gpointer data)
445     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(data);
446     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
447     SPCanvas *canvas = SP_CANVAS(sp_desktop_canvas(desktop));
449     dc->dragging = TRUE;
451     int x, y;
452     gtk_widget_get_pointer(GTK_WIDGET(canvas), &x, &y);
453     NR::Point p = sp_canvas_window_to_world(canvas, NR::Point(x, y));
454     p = desktop->w2d(p);
455     if (! sp_dyna_draw_apply(dc, p)) {
456         return TRUE;
457     }
459     if ( dc->cur != dc->last ) {
460         sp_dyna_draw_brush(dc);
461         g_assert( dc->npoints > 0 );
462         fit_and_split(dc, FALSE);
463     }
465     return TRUE;
468 void
469 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
471     desktop->setToolboxAdjustmentValue (id, value);
474 gint
475 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
476                                   GdkEvent *event)
478     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
479     SPDesktop *desktop = event_context->desktop;
481     gint ret = FALSE;
483     switch (event->type) {
484     case GDK_BUTTON_PRESS:
485         if ( event->button.button == 1 ) {
487             SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
489             if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
490                 return TRUE;
491             }
493             NR::Point const button_w(event->button.x,
494                                      event->button.y);
495             NR::Point const button_dt(desktop->w2d(button_w));
496             sp_dyna_draw_reset(dc, button_dt);
497             sp_dyna_draw_extinput(dc, event);
498             sp_dyna_draw_apply(dc, button_dt);
499             sp_curve_reset(dc->accumulated);
500             if (dc->repr) {
501                 dc->repr = NULL;
502             }
504             /* initialize first point */
505             dc->npoints = 0;
507             sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
508                                 ( dc->use_timeout
509                                   ? ( GDK_KEY_PRESS_MASK |
510                                       GDK_BUTTON_RELEASE_MASK |
511                                       GDK_BUTTON_PRESS_MASK    )
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             if ( dc->use_timeout && !dc->timer_id ) {
520                 dc->timer_id = gtk_timeout_add(SAMPLE_TIMEOUT, sp_dyna_draw_timeout_handler, dc);
521             }
522             ret = TRUE;
524             dc->is_drawing = true;
525         }
526         break;
527     case GDK_MOTION_NOTIFY:
528         if ( dc->is_drawing && !dc->use_timeout && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
529             dc->dragging = TRUE;
531             NR::Point const motion_w(event->motion.x,
532                                      event->motion.y);
533             NR::Point const motion_dt(desktop->w2d(motion_w));
535             sp_dyna_draw_extinput(dc, event);
536             if (!sp_dyna_draw_apply(dc, motion_dt)) {
537                 ret = TRUE;
538                 break;
539             }
541             if ( dc->cur != dc->last ) {
542                 sp_dyna_draw_brush(dc);
543                 g_assert( dc->npoints > 0 );
544                 fit_and_split(dc, FALSE);
545             }
546             ret = TRUE;
547         }
548         break;
550     case GDK_BUTTON_RELEASE:
551         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
552         dc->is_drawing = false;
553         if ( event->button.button == 1
554              && dc->use_timeout
555              && dc->timer_id != 0 )
556         {
557             gtk_timeout_remove(dc->timer_id);
558             dc->timer_id = 0;
559         }
560         if ( dc->dragging && event->button.button == 1 ) {
561             dc->dragging = FALSE;
563             /* Remove all temporary line segments */
564             while (dc->segments) {
565                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
566                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
567             }
568             /* Create object */
569             fit_and_split(dc, TRUE);
570             accumulate_calligraphic(dc);
571             set_to_accumulated(dc); /* temporal implementation */
572             /* reset accumulated curve */
573             sp_curve_reset(dc->accumulated);
574             clear_current(dc);
575             if (dc->repr) {
576                 dc->repr = NULL;
577             }
578             ret = TRUE;
579         }
580         break;
581     case GDK_KEY_PRESS:
582         switch (get_group0_keyval (&event->key)) {
583         case GDK_Up:
584         case GDK_KP_Up:
585             if (!MOD__CTRL_ONLY) {
586                 dc->angle += 5.0;
587                 if (dc->angle > 90.0)
588                     dc->angle = 90.0;
589                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
590                 ret = TRUE;
591             }
592             break;
593         case GDK_Down:
594         case GDK_KP_Down:
595             if (!MOD__CTRL_ONLY) {
596                 dc->angle -= 5.0;
597                 if (dc->angle < -90.0)
598                     dc->angle = -90.0;
599                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
600                 ret = TRUE;
601             }
602             break;
603         case GDK_Right:
604         case GDK_KP_Right:
605             if (!MOD__CTRL_ONLY) {
606                 dc->width += 0.01;
607                 if (dc->width > 1.0)
608                     dc->width = 1.0;
609                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width); // the same spinbutton is for alt+x
610                 ret = TRUE;
611             }
612             break;
613         case GDK_Left:
614         case GDK_KP_Left:
615             if (!MOD__CTRL_ONLY) {
616                 dc->width -= 0.01;
617                 if (dc->width < 0.01)
618                     dc->width = 0.01;
619                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width);
620                 ret = TRUE;
621             }
622             break;
623         case GDK_x:
624         case GDK_X:
625             if (MOD__ALT_ONLY) {
626                 desktop->setToolboxFocusTo ("altx-calligraphy");
627                 ret = TRUE;
628             }
629             break;
630         case GDK_Escape:
631             sp_desktop_selection(desktop)->clear();
632             break;
634         default:
635             break;
636         }
637     default:
638         break;
639     }
641     if (!ret) {
642         if (((SPEventContextClass *) parent_class)->root_handler) {
643             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
644         }
645     }
647     return ret;
651 static void
652 clear_current(SPDynaDrawContext *dc)
654     /* reset bpath */
655     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
656     /* reset curve */
657     sp_curve_reset(dc->currentcurve);
658     sp_curve_reset(dc->cal1);
659     sp_curve_reset(dc->cal2);
660     /* reset points */
661     dc->npoints = 0;
664 static void
665 set_to_accumulated(SPDynaDrawContext *dc)
667     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
669     if (!sp_curve_empty(dc->accumulated)) {
670         NArtBpath *abp;
671         gchar *str;
673         if (!dc->repr) {
674             /* Create object */
675             Inkscape::XML::Node *repr = sp_repr_new("svg:path");
677             /* Set style */
678             sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
680             dc->repr = repr;
682             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
683             Inkscape::GC::release(dc->repr);
684             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
685             item->updateRepr();
686             sp_desktop_selection(desktop)->set(dc->repr);
687         }
688         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
689         str = sp_svg_write_path(abp);
690         g_assert( str != NULL );
691         nr_free(abp);
692         dc->repr->setAttribute("d", str);
693         g_free(str);
694     } else {
695         if (dc->repr) {
696             sp_repr_unparent(dc->repr);
697         }
698         dc->repr = NULL;
699     }
701     sp_document_done(sp_desktop_document(desktop));
704 static void
705 accumulate_calligraphic(SPDynaDrawContext *dc)
707     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
708         sp_curve_reset(dc->accumulated); /*  Is this required ?? */
709         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
710         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
711         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
712         sp_curve_closepath(dc->accumulated);
714         sp_curve_unref(rev_cal2);
716         sp_curve_reset(dc->cal1);
717         sp_curve_reset(dc->cal2);
718     }
721 static void
722 fit_and_split(SPDynaDrawContext *dc,
723               gboolean release)
725     fit_and_split_calligraphics(dc, release);
728 static double square(double const x)
730     return x * x;
733 static void
734 fit_and_split_calligraphics(SPDynaDrawContext *dc, gboolean release)
736     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
738 #ifdef DYNA_DRAW_VERBOSE
739     g_print("[F&S:R=%c]", release?'T':'F');
740 #endif
742     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
743         return; // just clicked
745     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
746 #define BEZIER_SIZE       4
747 #define BEZIER_MAX_BEZIERS  8
748 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
750 #ifdef DYNA_DRAW_VERBOSE
751         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
752                 dc->npoints, release ? "TRUE" : "FALSE");
753 #endif
755         /* Current calligraphic */
756         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
757             /* dc->npoints > 0 */
758             /* g_print("calligraphics(1|2) reset\n"); */
759             sp_curve_reset(dc->cal1);
760             sp_curve_reset(dc->cal2);
762             sp_curve_moveto(dc->cal1, dc->point1[0]);
763             sp_curve_moveto(dc->cal2, dc->point2[0]);
764         }
766         NR::Point b1[BEZIER_MAX_LENGTH];
767         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
768                                                tolerance_sq, BEZIER_MAX_BEZIERS);
769         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
771         NR::Point b2[BEZIER_MAX_LENGTH];
772         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
773                                                tolerance_sq, BEZIER_MAX_BEZIERS);
774         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
776         if ( nb1 != -1 && nb2 != -1 ) {
777             /* Fit and draw and reset state */
778 #ifdef DYNA_DRAW_VERBOSE
779             g_print("nb1:%d nb2:%d\n", nb1, nb2);
780 #endif
781             /* CanvasShape */
782             if (! release) {
783                 sp_curve_reset(dc->currentcurve);
784                 sp_curve_moveto(dc->currentcurve, b1[0]);
785                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
786                     sp_curve_curveto(dc->currentcurve, bp1[1],
787                                      bp1[2], bp1[3]);
788                 }
789                 sp_curve_lineto(dc->currentcurve,
790                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
791                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
792                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
793                 }
794                 sp_curve_closepath(dc->currentcurve);
795                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
796             }
798             /* Current calligraphic */
799             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
800                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
801             }
802             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
803                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
804             }
805         } else {
806             /* fixme: ??? */
807 #ifdef DYNA_DRAW_VERBOSE
808             g_print("[fit_and_split_calligraphics] failed to fit-cubic.\n");
809 #endif
810             draw_temporary_box(dc);
812             for (gint i = 1; i < dc->npoints; i++) {
813                 sp_curve_lineto(dc->cal1, dc->point1[i]);
814             }
815             for (gint i = 1; i < dc->npoints; i++) {
816                 sp_curve_lineto(dc->cal2, dc->point2[i]);
817             }
818         }
820         /* Fit and draw and copy last point */
821 #ifdef DYNA_DRAW_VERBOSE
822         g_print("[%d]Yup\n", dc->npoints);
823 #endif
824         if (!release) {
825             g_assert(!sp_curve_empty(dc->currentcurve));
827             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
828                                                    SP_TYPE_CANVAS_BPATH,
829                                                    NULL);
830             SPCurve *curve = sp_curve_copy(dc->currentcurve);
831             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
832             sp_curve_unref(curve);
833             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), 0x000000ff, SP_WIND_RULE_EVENODD);
834             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
835             /* fixme: Cannot we cascade it to root more clearly? */
836             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
838             dc->segments = g_slist_prepend(dc->segments, cbp);
839         }
841         dc->point1[0] = dc->point1[dc->npoints - 1];
842         dc->point2[0] = dc->point2[dc->npoints - 1];
843         dc->npoints = 1;
844     } else {
845         draw_temporary_box(dc);
846     }
849 static void
850 draw_temporary_box(SPDynaDrawContext *dc)
852     sp_curve_reset(dc->currentcurve);
853     sp_curve_moveto(dc->currentcurve, dc->point1[0]);
854     for (gint i = 1; i < dc->npoints; i++) {
855         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
856     }
857     for (gint i = dc->npoints-1; i >= 0; i--) {
858         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
859     }
860     sp_curve_closepath(dc->currentcurve);
861     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
864 /*
865   Local Variables:
866   mode:c++
867   c-file-style:"stroustrup"
868   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
869   indent-tabs-mode:nil
870   fill-column:99
871   End:
872 */
873 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :