Code

excise never-used code and stale comments
[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
50 #define DDC_GREEN_RGBA 0x000000ff
52 #define SAMPLE_TIMEOUT 10
53 #define TOLERANCE_LINE 1.0
54 #define TOLERANCE_CALLIGRAPHIC 3.0
55 #define DYNA_EPSILON 1.0e-6
57 #define DYNA_MIN_WIDTH 1.0e-6
59 #define DRAG_MIN 0.0
60 #define DRAG_DEFAULT 1.0
61 #define DRAG_MAX 1.0
63 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
64 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
65 static void sp_dyna_draw_context_dispose(GObject *object);
67 static void sp_dyna_draw_context_setup(SPEventContext *ec);
68 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
69 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
71 static void clear_current(SPDynaDrawContext *dc);
72 static void set_to_accumulated(SPDynaDrawContext *dc);
73 static void accumulate_calligraphic(SPDynaDrawContext *dc);
75 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
76 static void fit_and_split_calligraphics(SPDynaDrawContext *ddc, gboolean release);
78 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
79 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
80 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
81 static void draw_temporary_box(SPDynaDrawContext *dc);
84 static SPEventContextClass *parent_class;
86 GtkType
87 sp_dyna_draw_context_get_type(void)
88 {
89     static GType type = 0;
90     if (!type) {
91         GTypeInfo info = {
92             sizeof(SPDynaDrawContextClass),
93             NULL, NULL,
94             (GClassInitFunc) sp_dyna_draw_context_class_init,
95             NULL, NULL,
96             sizeof(SPDynaDrawContext),
97             4,
98             (GInstanceInitFunc) sp_dyna_draw_context_init,
99             NULL,   /* value_table */
100         };
101         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
102     }
103     return type;
106 static void
107 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
109     GObjectClass *object_class = (GObjectClass *) klass;
110     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
112     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
114     object_class->dispose = sp_dyna_draw_context_dispose;
116     event_context_class->setup = sp_dyna_draw_context_setup;
117     event_context_class->set = sp_dyna_draw_context_set;
118     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
121 static void
122 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
124     SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
126     event_context->cursor_shape = cursor_calligraphy_xpm;
127     event_context->hot_x = 4;
128     event_context->hot_y = 4;
130     ddc->accumulated = NULL;
131     ddc->segments = NULL;
132     ddc->currentcurve = NULL;
133     ddc->currentshape = NULL;
134     ddc->npoints = 0;
135     ddc->cal1 = NULL;
136     ddc->cal2 = NULL;
137     ddc->repr = NULL;
139     /* DynaDraw values */
140     ddc->cur = NR::Point(0,0);
141     ddc->last = NR::Point(0,0);
142     ddc->vel = NR::Point(0,0);
143     ddc->acc = NR::Point(0,0);
144     ddc->ang = NR::Point(0,0);
145     ddc->del = NR::Point(0,0);
147     /* attributes */
148     ddc->use_timeout = FALSE;
149     ddc->timer_id = 0;
150     ddc->dragging = FALSE;
151     ddc->dynahand = FALSE;
153     ddc->mass = 0.3;
154     ddc->drag = DRAG_DEFAULT;
155     ddc->angle = 30.0;
156     ddc->width = 0.2;
158     ddc->vel_thin = 0.1;
159     ddc->flatness = 0.9;
162 static void
163 sp_dyna_draw_context_dispose(GObject *object)
165     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
167     if (ddc->accumulated) {
168         ddc->accumulated = sp_curve_unref(ddc->accumulated);
169     }
171     while (ddc->segments) {
172         gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
173         ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
174     }
176     if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
177     if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
178     if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
180     if (ddc->currentshape) {
181         gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
182         ddc->currentshape = NULL;
183     }
185     if (ddc->_message_context) {
186         delete ddc->_message_context;
187     }
189     G_OBJECT_CLASS(parent_class)->dispose(object);
192 static void
193 sp_dyna_draw_context_setup(SPEventContext *ec)
195     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
197     if (((SPEventContextClass *) parent_class)->setup)
198         ((SPEventContextClass *) parent_class)->setup(ec);
200     ddc->accumulated = sp_curve_new_sized(32);
201     ddc->currentcurve = sp_curve_new_sized(4);
203     ddc->cal1 = sp_curve_new_sized(32);
204     ddc->cal2 = sp_curve_new_sized(32);
206     ddc->currentshape = sp_canvas_item_new(SP_DT_SKETCH(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
207     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
208     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
209     /* fixme: Cannot we cascade it to root more clearly? */
210     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
212     sp_event_context_read(ec, "mass");
213     sp_event_context_read(ec, "drag");
214     sp_event_context_read(ec, "angle");
215     sp_event_context_read(ec, "width");
216     sp_event_context_read(ec, "thinning");
217     sp_event_context_read(ec, "tremor");
218     sp_event_context_read(ec, "flatness");
219     sp_event_context_read(ec, "usepressure");
220     sp_event_context_read(ec, "usetilt");
222     ddc->is_drawing = false;
224     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
227 static void
228 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
230     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
232     if (!strcmp(key, "mass")) {
233         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
234         ddc->mass = CLAMP(dval, -1000.0, 1000.0);
235     } else if (!strcmp(key, "drag")) {
236         double const dval = ( val ? g_ascii_strtod (val, NULL) : DRAG_DEFAULT );
237         ddc->drag = CLAMP(dval, DRAG_MIN, DRAG_MAX);
238     } else if (!strcmp(key, "angle")) {
239         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
240         ddc->angle = CLAMP (dval, -90, 90);
241     } else if (!strcmp(key, "width")) {
242         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
243         ddc->width = CLAMP(dval, -1000.0, 1000.0);
244     } else if (!strcmp(key, "thinning")) {
245         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
246         ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
247     } else if (!strcmp(key, "tremor")) {
248         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
249         ddc->tremor = CLAMP(dval, 0.0, 1.0);
250     } else if (!strcmp(key, "flatness")) {
251         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
252         ddc->flatness = CLAMP(dval, 0, 1.0);
253     } else if (!strcmp(key, "usepressure")) {
254         ddc->usepressure = (val && strcmp(val, "0"));
255     } else if (!strcmp(key, "usetilt")) {
256         ddc->usetilt = (val && strcmp(val, "0"));
257     }
259     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
262 static double
263 flerp(double f0, double f1, double p)
265     return f0 + ( f1 - f0 ) * p;
268 /* Get normalized point */
269 static NR::Point
270 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
272     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
273     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
274     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
277 /* Get view point */
278 static NR::Point
279 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
281     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
282     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
283     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
286 static void
287 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
289     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
290     dc->vel = NR::Point(0,0);
291     dc->acc = NR::Point(0,0);
292     dc->ang = NR::Point(0,0);
293     dc->del = NR::Point(0,0);
296 static void
297 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
299     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
300         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
301     else
302         dc->pressure = DDC_DEFAULT_PRESSURE;
304     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
305         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
306     else
307         dc->xtilt = DDC_DEFAULT_TILT;
309     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
310         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
311     else
312         dc->ytilt = DDC_DEFAULT_TILT;
316 static gboolean
317 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
319     NR::Point n = sp_dyna_draw_get_npoint(dc, p);
321     /* Calculate mass and drag */
322     double const mass = flerp(1.0, 160.0, dc->mass);
323     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
325     /* Calculate force and acceleration */
326     NR::Point force = n - dc->cur;
327     if ( NR::L2(force) < DYNA_EPSILON ) {
328         return FALSE;
329     }
331     dc->acc = force / mass;
333     /* Calculate new velocity */
334     dc->vel += dc->acc;
336     /* Calculate angle of drawing tool */
338     double a1;
339     if (dc->usetilt) {
340         // 1a. calculate nib angle from input device tilt:
341         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
343         if (length > 0) {
344             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
345             a1 = atan2(ang1);
346         }
347         else
348             a1 = 0.0;
349     }
350     else {
351         // 1b. fixed dc->angle (absolutely flat nib):
352         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
353         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
354         a1 = atan2(ang1);
355     }
357     // 2. perpendicular to dc->vel (absolutely non-flat nib):
358     gdouble const mag_vel = NR::L2(dc->vel);
359     if ( mag_vel < DYNA_EPSILON ) {
360         return FALSE;
361     }
362     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
364     // 3. Average them using flatness parameter:
365     // calculate angles
366     double a2 = atan2(ang2);
367     // flip a2 to force it to be in the same half-circle as a1
368     bool flipped = false;
369     if (fabs (a2-a1) > 0.5*M_PI) {
370         a2 += M_PI;
371         flipped = true;
372     }
373     // normalize a2
374     if (a2 > M_PI)
375         a2 -= 2*M_PI;
376     if (a2 < -M_PI)
377         a2 += 2*M_PI;
378     // find the flatness-weighted bisector angle, unflip if a2 was flipped
379     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
380     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
381     // convert to point
382     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
384     /* Apply drag */
385     dc->vel *= 1.0 - drag;
387     /* Update position */
388     dc->last = dc->cur;
389     dc->cur += dc->vel;
391     return TRUE;
394 static void
395 sp_dyna_draw_brush(SPDynaDrawContext *dc)
397     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
399     // How much velocity thins strokestyle
400     double vel_thin = flerp (0, 160, dc->vel_thin);
402     // Influence of pressure on thickness
403     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
405     double width = ( pressure_thick - vel_thin * NR::L2(dc->vel) ) * dc->width;
407     double tremble_left = 0, tremble_right = 0;
408     if (dc->tremor > 0) {
409         // obtain two normally distributed random variables, using polar Box-Muller transform
410         double x1, x2, w, y1, y2;
411         do {
412             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
413             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
414             w = x1 * x1 + x2 * x2;
415         } while ( w >= 1.0 );
416         w = sqrt( (-2.0 * log( w ) ) / w );
417         y1 = x1 * w;
418         y2 = x2 * w;
420         // deflect both left and right edges randomly and independently, so that:
421         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
422         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
423         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
424         // comparatively smooth and slow ones excessively jittery
425         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
426         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
427     }
429     if ( width < 0.02 * dc->width ) {
430         width = 0.02 * dc->width;
431     }
433     NR::Point del_left = 0.05 * (width + tremble_left) * dc->ang;
434     NR::Point del_right = 0.05 * (width + tremble_right) * dc->ang;
436     dc->point1[dc->npoints] = sp_dyna_draw_get_vpoint(dc, dc->cur + del_left);
437     dc->point2[dc->npoints] = sp_dyna_draw_get_vpoint(dc, dc->cur - del_right);
439     dc->del = 0.5*(del_left + del_right);
441     dc->npoints++;
444 static gint
445 sp_dyna_draw_timeout_handler(gpointer data)
447     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(data);
448     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
449     SPCanvas *canvas = SP_CANVAS(SP_DT_CANVAS(desktop));
451     dc->dragging = TRUE;
452     dc->dynahand = TRUE;
454     int x, y;
455     gtk_widget_get_pointer(GTK_WIDGET(canvas), &x, &y);
456     NR::Point p = sp_canvas_window_to_world(canvas, NR::Point(x, y));
457     p = desktop->w2d(p);
458     if (! sp_dyna_draw_apply(dc, p)) {
459         return TRUE;
460     }
462     if ( dc->cur != dc->last ) {
463         sp_dyna_draw_brush(dc);
464         g_assert( dc->npoints > 0 );
465         fit_and_split(dc, FALSE);
466     }
468     return TRUE;
471 void
472 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
474     desktop->setToolboxAdjustmentValue (id, value);
477 gint
478 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
479                                   GdkEvent *event)
481     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
482     SPDesktop *desktop = event_context->desktop;
484     gint ret = FALSE;
486     switch (event->type) {
487     case GDK_BUTTON_PRESS:
488         if ( event->button.button == 1 ) {
490             SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
492             if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
493                 return TRUE;
494             }
496             NR::Point const button_w(event->button.x,
497                                      event->button.y);
498             NR::Point const button_dt(desktop->w2d(button_w));
499             sp_dyna_draw_reset(dc, button_dt);
500             sp_dyna_draw_extinput(dc, event);
501             sp_dyna_draw_apply(dc, button_dt);
502             sp_curve_reset(dc->accumulated);
503             if (dc->repr) {
504                 dc->repr = NULL;
505             }
507             /* initialize first point */
508             dc->npoints = 0;
510             sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
511                                 ( dc->use_timeout
512                                   ? ( GDK_KEY_PRESS_MASK |
513                                       GDK_BUTTON_RELEASE_MASK |
514                                       GDK_BUTTON_PRESS_MASK    )
515                                   : ( GDK_KEY_PRESS_MASK |
516                                       GDK_BUTTON_RELEASE_MASK |
517                                       GDK_POINTER_MOTION_MASK |
518                                       GDK_BUTTON_PRESS_MASK    ) ),
519                                 NULL,
520                                 event->button.time);
522             if ( dc->use_timeout && !dc->timer_id ) {
523                 dc->timer_id = gtk_timeout_add(SAMPLE_TIMEOUT, sp_dyna_draw_timeout_handler, dc);
524             }
525             ret = TRUE;
527             dc->is_drawing = true;
528         }
529         break;
530     case GDK_MOTION_NOTIFY:
531         if ( dc->is_drawing && !dc->use_timeout && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
532             dc->dragging = TRUE;
533             dc->dynahand = TRUE;
535             NR::Point const motion_w(event->motion.x,
536                                      event->motion.y);
537             NR::Point const motion_dt(desktop->w2d(motion_w));
539             sp_dyna_draw_extinput(dc, event);
540             if (!sp_dyna_draw_apply(dc, motion_dt)) {
541                 ret = TRUE;
542                 break;
543             }
545             if ( dc->cur != dc->last ) {
546                 sp_dyna_draw_brush(dc);
547                 g_assert( dc->npoints > 0 );
548                 fit_and_split(dc, FALSE);
549             }
550             ret = TRUE;
551         }
552         break;
554     case GDK_BUTTON_RELEASE:
555         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
556         dc->is_drawing = false;
557         if ( event->button.button == 1
558              && dc->use_timeout
559              && dc->timer_id != 0 )
560         {
561             gtk_timeout_remove(dc->timer_id);
562             dc->timer_id = 0;
563         }
564         if ( dc->dragging && event->button.button == 1 ) {
565             dc->dragging = FALSE;
567             /* release */
568             if (dc->dynahand) {
569                 dc->dynahand = FALSE;
570                 /* Remove all temporary line segments */
571                 while (dc->segments) {
572                     gtk_object_destroy(GTK_OBJECT(dc->segments->data));
573                     dc->segments = g_slist_remove(dc->segments, dc->segments->data);
574                 }
575                 /* Create object */
576                 fit_and_split(dc, TRUE);
577                 accumulate_calligraphic(dc);
578                 set_to_accumulated(dc); /* temporal implementation */
579                 /* reset accumulated curve */
580                 sp_curve_reset(dc->accumulated);
581                 clear_current(dc);
582                 if (dc->repr) {
583                     dc->repr = NULL;
584                 }
585             }
586             ret = TRUE;
587         }
588         break;
589     case GDK_KEY_PRESS:
590         switch (get_group0_keyval (&event->key)) {
591         case GDK_Up:
592         case GDK_KP_Up:
593             if (!MOD__CTRL_ONLY) {
594                 dc->angle += 5.0;
595                 if (dc->angle > 90.0)
596                     dc->angle = 90.0;
597                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
598                 ret = TRUE;
599             }
600             break;
601         case GDK_Down:
602         case GDK_KP_Down:
603             if (!MOD__CTRL_ONLY) {
604                 dc->angle -= 5.0;
605                 if (dc->angle < -90.0)
606                     dc->angle = -90.0;
607                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
608                 ret = TRUE;
609             }
610             break;
611         case GDK_Right:
612         case GDK_KP_Right:
613             if (!MOD__CTRL_ONLY) {
614                 dc->width += 0.01;
615                 if (dc->width > 1.0)
616                     dc->width = 1.0;
617                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width); // the same spinbutton is for alt+x
618                 ret = TRUE;
619             }
620             break;
621         case GDK_Left:
622         case GDK_KP_Left:
623             if (!MOD__CTRL_ONLY) {
624                 dc->width -= 0.01;
625                 if (dc->width < 0.01)
626                     dc->width = 0.01;
627                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width);
628                 ret = TRUE;
629             }
630             break;
631         case GDK_x:
632         case GDK_X:
633             if (MOD__ALT_ONLY) {
634                 desktop->setToolboxFocusTo ("altx-calligraphy");
635                 ret = TRUE;
636             }
637             break;
638         case GDK_Escape:
639             SP_DT_SELECTION(desktop)->clear();
640             break;
642         default:
643             break;
644         }
645     default:
646         break;
647     }
649     if (!ret) {
650         if (((SPEventContextClass *) parent_class)->root_handler) {
651             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
652         }
653     }
655     return ret;
659 static void
660 clear_current(SPDynaDrawContext *dc)
662     /* reset bpath */
663     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
664     /* reset curve */
665     sp_curve_reset(dc->currentcurve);
666     sp_curve_reset(dc->cal1);
667     sp_curve_reset(dc->cal2);
668     /* reset points */
669     dc->npoints = 0;
672 static void
673 set_to_accumulated(SPDynaDrawContext *dc)
675     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
677     if (!sp_curve_empty(dc->accumulated)) {
678         NArtBpath *abp;
679         gchar *str;
681         if (!dc->repr) {
682             /* Create object */
683             Inkscape::XML::Node *repr = sp_repr_new("svg:path");
685             /* Set style */
686             sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
688             dc->repr = repr;
690             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
691             Inkscape::GC::release(dc->repr);
692             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
693             item->updateRepr();
694             SP_DT_SELECTION(desktop)->set(dc->repr);
695         }
696         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
697         str = sp_svg_write_path(abp);
698         g_assert( str != NULL );
699         nr_free(abp);
700         dc->repr->setAttribute("d", str);
701         g_free(str);
702     } else {
703         if (dc->repr) {
704             sp_repr_unparent(dc->repr);
705         }
706         dc->repr = NULL;
707     }
709     sp_document_done(SP_DT_DOCUMENT(desktop));
712 static void
713 accumulate_calligraphic(SPDynaDrawContext *dc)
715     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
716         sp_curve_reset(dc->accumulated); /*  Is this required ?? */
717         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
718         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
719         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
720         sp_curve_closepath(dc->accumulated);
722         sp_curve_unref(rev_cal2);
724         sp_curve_reset(dc->cal1);
725         sp_curve_reset(dc->cal2);
726     }
729 static void
730 fit_and_split(SPDynaDrawContext *dc,
731               gboolean release)
733     fit_and_split_calligraphics(dc, release);
736 static double square(double const x)
738     return x * x;
741 static void
742 fit_and_split_calligraphics(SPDynaDrawContext *dc, gboolean release)
744     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
746 #ifdef DYNA_DRAW_VERBOSE
747     g_print("[F&S:R=%c]", release?'T':'F');
748 #endif
750     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
751         return; // just clicked
753     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
754 #define BEZIER_SIZE       4
755 #define BEZIER_MAX_BEZIERS  8
756 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
758 #ifdef DYNA_DRAW_VERBOSE
759         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
760                 dc->npoints, release ? "TRUE" : "FALSE");
761 #endif
763         /* Current calligraphic */
764         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
765             /* dc->npoints > 0 */
766             /* g_print("calligraphics(1|2) reset\n"); */
767             sp_curve_reset(dc->cal1);
768             sp_curve_reset(dc->cal2);
770             sp_curve_moveto(dc->cal1, dc->point1[0]);
771             sp_curve_moveto(dc->cal2, dc->point2[0]);
772         }
774         NR::Point b1[BEZIER_MAX_LENGTH];
775         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
776                                                tolerance_sq, BEZIER_MAX_BEZIERS);
777         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
779         NR::Point b2[BEZIER_MAX_LENGTH];
780         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
781                                                tolerance_sq, BEZIER_MAX_BEZIERS);
782         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
784         if ( nb1 != -1 && nb2 != -1 ) {
785             /* Fit and draw and reset state */
786 #ifdef DYNA_DRAW_VERBOSE
787             g_print("nb1:%d nb2:%d\n", nb1, nb2);
788 #endif
789             /* CanvasShape */
790             if (! release) {
791                 sp_curve_reset(dc->currentcurve);
792                 sp_curve_moveto(dc->currentcurve, b1[0]);
793                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
794                     sp_curve_curveto(dc->currentcurve, bp1[1],
795                                      bp1[2], bp1[3]);
796                 }
797                 sp_curve_lineto(dc->currentcurve,
798                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
799                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
800                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
801                 }
802                 sp_curve_closepath(dc->currentcurve);
803                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
804             }
806             /* Current calligraphic */
807             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
808                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
809             }
810             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
811                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
812             }
813         } else {
814             /* fixme: ??? */
815 #ifdef DYNA_DRAW_VERBOSE
816             g_print("[fit_and_split_calligraphics] failed to fit-cubic.\n");
817 #endif
818             draw_temporary_box(dc);
820             for (gint i = 1; i < dc->npoints; i++) {
821                 sp_curve_lineto(dc->cal1, dc->point1[i]);
822             }
823             for (gint i = 1; i < dc->npoints; i++) {
824                 sp_curve_lineto(dc->cal2, dc->point2[i]);
825             }
826         }
828         /* Fit and draw and copy last point */
829 #ifdef DYNA_DRAW_VERBOSE
830         g_print("[%d]Yup\n", dc->npoints);
831 #endif
832         if (!release) {
833             g_assert(!sp_curve_empty(dc->currentcurve));
835             SPCanvasItem *cbp = sp_canvas_item_new(SP_DT_SKETCH(SP_EVENT_CONTEXT(dc)->desktop),
836                                                    SP_TYPE_CANVAS_BPATH,
837                                                    NULL);
838             SPCurve *curve = sp_curve_copy(dc->currentcurve);
839             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
840             sp_curve_unref(curve);
841             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), 0x000000ff, SP_WIND_RULE_EVENODD);
842             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
843             /* fixme: Cannot we cascade it to root more clearly? */
844             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
846             dc->segments = g_slist_prepend(dc->segments, cbp);
847         }
849         dc->point1[0] = dc->point1[dc->npoints - 1];
850         dc->point2[0] = dc->point2[dc->npoints - 1];
851         dc->npoints = 1;
852     } else {
853         draw_temporary_box(dc);
854     }
857 static void
858 draw_temporary_box(SPDynaDrawContext *dc)
860     sp_curve_reset(dc->currentcurve);
861     sp_curve_moveto(dc->currentcurve, dc->point1[0]);
862     for (gint i = 1; i < dc->npoints; i++) {
863         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
864     }
865     for (gint i = dc->npoints-1; i >= 0; i--) {
866         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
867     }
868     sp_curve_closepath(dc->currentcurve);
869     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
872 /*
873   Local Variables:
874   mode:c++
875   c-file-style:"stroustrup"
876   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
877   indent-tabs-mode:nil
878   fill-column:99
879   End:
880 */
881 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :