Code

bulk trailing spaces removal. consistency through MD5 of binary
[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 /*
22  * TODO: Tue Oct  2 22:57:15 2001
23  *  - Decide control point behavior when use_calligraphic==1.
24  *  - Decide to use NORMALIZED_COORDINATE or not.
25  *  - Bug fix.
26  */
28 #define noDYNA_DRAW_VERBOSE
30 #include "config.h"
32 #include <gtk/gtk.h>
33 #include <gdk/gdkkeysyms.h>
35 #include "svg/svg.h"
36 #include "display/canvas-bpath.h"
37 #include "display/bezier-utils.h"
39 #include "macros.h"
40 #include "document.h"
41 #include "selection.h"
42 #include "desktop.h"
43 #include "desktop-events.h"
44 #include "desktop-handles.h"
45 #include "desktop-affine.h"
46 #include "desktop-style.h"
47 #include "message-context.h"
48 #include "pixmaps/cursor-calligraphy.xpm"
49 #include "dyna-draw-context.h"
50 #include "libnr/n-art-bpath.h"
51 #include "libnr/nr-path.h"
52 #include "xml/repr.h"
53 #include "context-fns.h"
54 #include "sp-item.h"
56 #define DDC_RED_RGBA 0xff0000ff
57 #define DDC_GREEN_RGBA 0x000000ff
59 #define SAMPLE_TIMEOUT 10
60 #define TOLERANCE_LINE 1.0
61 #define TOLERANCE_CALLIGRAPHIC 3.0
62 #define DYNA_EPSILON 1.0e-6
64 #define DYNA_MIN_WIDTH 1.0e-6
66 #define DRAG_MIN 0.0
67 #define DRAG_DEFAULT 1.0
68 #define DRAG_MAX 1.0
70 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
71 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
72 static void sp_dyna_draw_context_dispose(GObject *object);
74 static void sp_dyna_draw_context_setup(SPEventContext *ec);
75 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
76 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
78 static void clear_current(SPDynaDrawContext *dc);
79 static void set_to_accumulated(SPDynaDrawContext *dc);
80 static void concat_current_line(SPDynaDrawContext *dc);
81 static void accumulate_calligraphic(SPDynaDrawContext *dc);
83 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
84 static void fit_and_split_line(SPDynaDrawContext *ddc, gboolean release);
85 static void fit_and_split_calligraphics(SPDynaDrawContext *ddc, gboolean release);
87 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
88 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
89 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
90 static NR::Point sp_dyna_draw_get_curr_vpoint(SPDynaDrawContext const *ddc);
91 static void draw_temporary_box(SPDynaDrawContext *dc);
94 static SPEventContextClass *parent_class;
96 GtkType
97 sp_dyna_draw_context_get_type(void)
98 {
99     static GType type = 0;
100     if (!type) {
101         GTypeInfo info = {
102             sizeof(SPDynaDrawContextClass),
103             NULL, NULL,
104             (GClassInitFunc) sp_dyna_draw_context_class_init,
105             NULL, NULL,
106             sizeof(SPDynaDrawContext),
107             4,
108             (GInstanceInitFunc) sp_dyna_draw_context_init,
109             NULL,   /* value_table */
110         };
111         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
112     }
113     return type;
116 static void
117 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
119     GObjectClass *object_class = (GObjectClass *) klass;
120     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
122     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
124     object_class->dispose = sp_dyna_draw_context_dispose;
126     event_context_class->setup = sp_dyna_draw_context_setup;
127     event_context_class->set = sp_dyna_draw_context_set;
128     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
131 static void
132 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
134     SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
136     event_context->cursor_shape = cursor_calligraphy_xpm;
137     event_context->hot_x = 4;
138     event_context->hot_y = 4;
140     ddc->accumulated = NULL;
141     ddc->segments = NULL;
142     ddc->currentcurve = NULL;
143     ddc->currentshape = NULL;
144     ddc->npoints = 0;
145     ddc->cal1 = NULL;
146     ddc->cal2 = NULL;
147     ddc->repr = NULL;
149     /* DynaDraw values */
150     ddc->cur = NR::Point(0,0);
151     ddc->last = NR::Point(0,0);
152     ddc->vel = NR::Point(0,0);
153     ddc->acc = NR::Point(0,0);
154     ddc->ang = NR::Point(0,0);
155     ddc->del = NR::Point(0,0);
157     /* attributes */
158     ddc->use_timeout = FALSE;
159     ddc->use_calligraphic = TRUE;
160     ddc->timer_id = 0;
161     ddc->dragging = FALSE;
162     ddc->dynahand = FALSE;
164     ddc->mass = 0.3;
165     ddc->drag = DRAG_DEFAULT;
166     ddc->angle = 30.0;
167     ddc->width = 0.2;
169     ddc->vel_thin = 0.1;
170     ddc->flatness = 0.9;
173 static void
174 sp_dyna_draw_context_dispose(GObject *object)
176     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
178     if (ddc->accumulated) {
179         ddc->accumulated = sp_curve_unref(ddc->accumulated);
180     }
182     while (ddc->segments) {
183         gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
184         ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
185     }
187     if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
188     if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
189     if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
191     if (ddc->currentshape) {
192         gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
193         ddc->currentshape = NULL;
194     }
196     if (ddc->_message_context) {
197         delete ddc->_message_context;
198     }
200     G_OBJECT_CLASS(parent_class)->dispose(object);
203 static void
204 sp_dyna_draw_context_setup(SPEventContext *ec)
206     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
208     if (((SPEventContextClass *) parent_class)->setup)
209         ((SPEventContextClass *) parent_class)->setup(ec);
211     ddc->accumulated = sp_curve_new_sized(32);
212     ddc->currentcurve = sp_curve_new_sized(4);
214     ddc->cal1 = sp_curve_new_sized(32);
215     ddc->cal2 = sp_curve_new_sized(32);
217     /* style should be changed when dc->use_calligraphc is touched */
218     ddc->currentshape = sp_canvas_item_new(SP_DT_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, "flatness");
230     sp_event_context_read(ec, "usepressure");
231     sp_event_context_read(ec, "usetilt");
233     ddc->is_drawing = false;
235     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
238 static void
239 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
241     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
243     if (!strcmp(key, "mass")) {
244         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
245         ddc->mass = CLAMP(dval, -1000.0, 1000.0);
246     } else if (!strcmp(key, "drag")) {
247         double const dval = ( val ? g_ascii_strtod (val, NULL) : DRAG_DEFAULT );
248         ddc->drag = CLAMP(dval, DRAG_MIN, DRAG_MAX);
249     } else if (!strcmp(key, "angle")) {
250         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
251         ddc->angle = CLAMP (dval, -90, 90);
252     } else if (!strcmp(key, "width")) {
253         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
254         ddc->width = CLAMP(dval, -1000.0, 1000.0);
255     } else if (!strcmp(key, "thinning")) {
256         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
257         ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
258     } else if (!strcmp(key, "flatness")) {
259         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
260         ddc->flatness = CLAMP(dval, 0, 1.0);
261     } else if (!strcmp(key, "usepressure")) {
262         ddc->usepressure = (val && strcmp(val, "0"));
263     } else if (!strcmp(key, "usetilt")) {
264         ddc->usetilt = (val && strcmp(val, "0"));
265     }
267     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
270 static double
271 flerp(double f0, double f1, double p)
273     return f0 + ( f1 - f0 ) * p;
276 /* Get normalized point */
277 static NR::Point
278 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
280     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
281     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
282     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
285 /* Get view point */
286 static NR::Point
287 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
289     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
290     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
291     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
294 /* Get current view point */
295 static NR::Point sp_dyna_draw_get_curr_vpoint(SPDynaDrawContext const *dc)
297     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
298     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
299     return NR::Point(dc->cur[NR::X] * max + drect.min()[NR::X], dc->cur[NR::Y] * max + drect.min()[NR::Y]);
302 static void
303 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
305     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
306     dc->vel = NR::Point(0,0);
307     dc->acc = NR::Point(0,0);
308     dc->ang = NR::Point(0,0);
309     dc->del = NR::Point(0,0);
312 static void
313 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
315     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
316         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
317     else
318         dc->pressure = DDC_DEFAULT_PRESSURE;
320     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
321         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
322     else
323         dc->xtilt = DDC_DEFAULT_TILT;
325     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
326         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
327     else
328         dc->ytilt = DDC_DEFAULT_TILT;
332 static gboolean
333 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
335     NR::Point n = sp_dyna_draw_get_npoint(dc, p);
337     /* Calculate mass and drag */
338     double const mass = flerp(1.0, 160.0, dc->mass);
339     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
341     /* Calculate force and acceleration */
342     NR::Point force = n - dc->cur;
343     if ( NR::L2(force) < DYNA_EPSILON ) {
344         return FALSE;
345     }
347     dc->acc = force / mass;
349     /* Calculate new velocity */
350     dc->vel += dc->acc;
352     /* Calculate angle of drawing tool */
354     double a1;
355     if (dc->usetilt) {
356         // 1a. calculate nib angle from input device tilt:
357         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
359         if (length > 0) {
360             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
361             a1 = atan2(ang1);
362         }
363         else
364             a1 = 0.0;
365     }
366     else {
367         // 1b. fixed dc->angle (absolutely flat nib):
368         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
369         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
370         a1 = atan2(ang1);
371     }
373     // 2. perpendicular to dc->vel (absolutely non-flat nib):
374     gdouble const mag_vel = NR::L2(dc->vel);
375     if ( mag_vel < DYNA_EPSILON ) {
376         return FALSE;
377     }
378     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
380     // 3. Average them using flatness parameter:
381     // calculate angles
382     double a2 = atan2(ang2);
383     // flip a2 to force it to be in the same half-circle as a1
384     bool flipped = false;
385     if (fabs (a2-a1) > 0.5*M_PI) {
386         a2 += M_PI;
387         flipped = true;
388     }
389     // normalize a2
390     if (a2 > M_PI)
391         a2 -= 2*M_PI;
392     if (a2 < -M_PI)
393         a2 += 2*M_PI;
394     // find the flatness-weighted bisector angle, unflip if a2 was flipped
395     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
396     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
397     // convert to point
398     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
400     /* Apply drag */
401     dc->vel *= 1.0 - drag;
403     /* Update position */
404     dc->last = dc->cur;
405     dc->cur += dc->vel;
407     return TRUE;
410 static void
411 sp_dyna_draw_brush(SPDynaDrawContext *dc)
413     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
415     if (dc->use_calligraphic) {
416         /* calligraphics */
418         // How much velocity thins strokestyle
419         double vel_thin = flerp (0, 160, dc->vel_thin);
421         // Influence of pressure on thickness
422         double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
424         double width = ( pressure_thick - vel_thin * NR::L2(dc->vel) ) * dc->width;
425         if ( width < 0.02 * dc->width ) {
426             width = 0.02 * dc->width;
427         }
429         NR::Point del = 0.05 * width * dc->ang;
431         dc->point1[dc->npoints] = sp_dyna_draw_get_vpoint(dc, dc->cur + del);
432         dc->point2[dc->npoints] = sp_dyna_draw_get_vpoint(dc, dc->cur - del);
434         dc->del = del;
435     } else {
436         dc->point1[dc->npoints] = sp_dyna_draw_get_curr_vpoint(dc);
437     }
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_DT_CANVAS(desktop));
449     dc->dragging = TRUE;
450     dc->dynahand = TRUE;
452     int x, y;
453     gtk_widget_get_pointer(GTK_WIDGET(canvas), &x, &y);
454     NR::Point p = sp_canvas_window_to_world(canvas, NR::Point(x, y));
455     p = desktop->w2d(p);
456     if (! sp_dyna_draw_apply(dc, p)) {
457         return TRUE;
458     }
460     if ( dc->cur != dc->last ) {
461         sp_dyna_draw_brush(dc);
462         g_assert( dc->npoints > 0 );
463         fit_and_split(dc, FALSE);
464     }
466     return TRUE;
469 void
470 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
472     desktop->setToolboxAdjustmentValue (id, value);
475 gint
476 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
477                                   GdkEvent *event)
479     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
480     SPDesktop *desktop = event_context->desktop;
482     gint ret = FALSE;
484     switch (event->type) {
485     case GDK_BUTTON_PRESS:
486         if ( event->button.button == 1 ) {
488             SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
490             if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
491                 return TRUE;
492             }
494             NR::Point const button_w(event->button.x,
495                                      event->button.y);
496             NR::Point const button_dt(desktop->w2d(button_w));
497             sp_dyna_draw_reset(dc, button_dt);
498             sp_dyna_draw_extinput(dc, event);
499             sp_dyna_draw_apply(dc, button_dt);
500             sp_curve_reset(dc->accumulated);
501             if (dc->repr) {
502                 dc->repr = NULL;
503             }
505             /* initialize first point */
506             dc->npoints = 0;
508             sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
509                                 ( dc->use_timeout
510                                   ? ( GDK_KEY_PRESS_MASK |
511                                       GDK_BUTTON_RELEASE_MASK |
512                                       GDK_BUTTON_PRESS_MASK    )
513                                   : ( GDK_KEY_PRESS_MASK |
514                                       GDK_BUTTON_RELEASE_MASK |
515                                       GDK_POINTER_MOTION_MASK |
516                                       GDK_BUTTON_PRESS_MASK    ) ),
517                                 NULL,
518                                 event->button.time);
520             if ( dc->use_timeout && !dc->timer_id ) {
521                 dc->timer_id = gtk_timeout_add(SAMPLE_TIMEOUT, sp_dyna_draw_timeout_handler, dc);
522             }
523             ret = TRUE;
525             dc->is_drawing = true;
526         }
527         break;
528     case GDK_MOTION_NOTIFY:
529         if ( dc->is_drawing && !dc->use_timeout && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
530             dc->dragging = TRUE;
531             dc->dynahand = TRUE;
533             NR::Point const motion_w(event->motion.x,
534                                      event->motion.y);
535             NR::Point const motion_dt(desktop->w2d(motion_w));
537             sp_dyna_draw_extinput(dc, event);
538             if (!sp_dyna_draw_apply(dc, motion_dt)) {
539                 ret = TRUE;
540                 break;
541             }
543             if ( dc->cur != dc->last ) {
544                 sp_dyna_draw_brush(dc);
545                 g_assert( dc->npoints > 0 );
546                 fit_and_split(dc, FALSE);
547             }
548             ret = TRUE;
549         }
550         break;
552     case GDK_BUTTON_RELEASE:
553         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
554         dc->is_drawing = false;
555         if ( event->button.button == 1
556              && dc->use_timeout
557              && dc->timer_id != 0 )
558         {
559             gtk_timeout_remove(dc->timer_id);
560             dc->timer_id = 0;
561         }
562         if ( dc->dragging && event->button.button == 1 ) {
563             dc->dragging = FALSE;
565             /* release */
566             if (dc->dynahand) {
567                 dc->dynahand = FALSE;
568                 /* Remove all temporary line segments */
569                 while (dc->segments) {
570                     gtk_object_destroy(GTK_OBJECT(dc->segments->data));
571                     dc->segments = g_slist_remove(dc->segments, dc->segments->data);
572                 }
573                 /* Create object */
574                 fit_and_split(dc, TRUE);
575                 if (dc->use_calligraphic) {
576                     accumulate_calligraphic(dc);
577                 } else {
578                     concat_current_line(dc);
579                 }
580                 set_to_accumulated(dc); /* temporal implementation */
581                 if (dc->use_calligraphic /* || dc->cinside*/) {
582                     /* reset accumulated curve */
583                     sp_curve_reset(dc->accumulated);
584                     clear_current(dc);
585                     if (dc->repr) {
586                         dc->repr = NULL;
587                     }
588                 }
589             }
590             ret = TRUE;
591         }
592         break;
593     case GDK_KEY_PRESS:
594         switch (get_group0_keyval (&event->key)) {
595         case GDK_Up:
596         case GDK_KP_Up:
597             if (!MOD__CTRL_ONLY) {
598                 dc->angle += 5.0;
599                 if (dc->angle > 90.0)
600                     dc->angle = 90.0;
601                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
602                 ret = TRUE;
603             }
604             break;
605         case GDK_Down:
606         case GDK_KP_Down:
607             if (!MOD__CTRL_ONLY) {
608                 dc->angle -= 5.0;
609                 if (dc->angle < -90.0)
610                     dc->angle = -90.0;
611                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
612                 ret = TRUE;
613             }
614             break;
615         case GDK_Right:
616         case GDK_KP_Right:
617             if (!MOD__CTRL_ONLY) {
618                 dc->width += 0.01;
619                 if (dc->width > 1.0)
620                     dc->width = 1.0;
621                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width); // the same spinbutton is for alt+x
622                 ret = TRUE;
623             }
624             break;
625         case GDK_Left:
626         case GDK_KP_Left:
627             if (!MOD__CTRL_ONLY) {
628                 dc->width -= 0.01;
629                 if (dc->width < 0.01)
630                     dc->width = 0.01;
631                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width);
632                 ret = TRUE;
633             }
634             break;
635         case GDK_x:
636         case GDK_X:
637             if (MOD__ALT_ONLY) {
638                 desktop->setToolboxFocusTo ("altx-calligraphy");
639                 ret = TRUE;
640             }
641             break;
642         case GDK_Escape:
643             SP_DT_SELECTION(desktop)->clear();
644             break;
646         default:
647             break;
648         }
649     default:
650         break;
651     }
653     if (!ret) {
654         if (((SPEventContextClass *) parent_class)->root_handler) {
655             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
656         }
657     }
659     return ret;
663 static void
664 clear_current(SPDynaDrawContext *dc)
666     /* reset bpath */
667     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
668     /* reset curve */
669     sp_curve_reset(dc->currentcurve);
670     sp_curve_reset(dc->cal1);
671     sp_curve_reset(dc->cal2);
672     /* reset points */
673     dc->npoints = 0;
676 static void
677 set_to_accumulated(SPDynaDrawContext *dc)
679     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
681     if (!sp_curve_empty(dc->accumulated)) {
682         NArtBpath *abp;
683         gchar *str;
685         if (!dc->repr) {
686             /* Create object */
687             Inkscape::XML::Node *repr = sp_repr_new("svg:path");
689             /* Set style */
690             sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
692             dc->repr = repr;
694             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
695             Inkscape::GC::release(dc->repr);
696             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
697             item->updateRepr();
698             SP_DT_SELECTION(desktop)->set(dc->repr);
699         }
700         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
701         str = sp_svg_write_path(abp);
702         g_assert( str != NULL );
703         nr_free(abp);
704         dc->repr->setAttribute("d", str);
705         g_free(str);
706     } else {
707         if (dc->repr) {
708             sp_repr_unparent(dc->repr);
709         }
710         dc->repr = NULL;
711     }
713     sp_document_done(SP_DT_DOCUMENT(desktop));
716 static void
717 concat_current_line(SPDynaDrawContext *dc)
719     if (!sp_curve_empty(dc->currentcurve)) {
720         NArtBpath *bpath;
721         if (sp_curve_empty(dc->accumulated)) {
722             bpath = sp_curve_first_bpath(dc->currentcurve);
723             g_assert( bpath->code == NR_MOVETO_OPEN );
724             sp_curve_moveto(dc->accumulated, bpath->x3, bpath->y3);
725         }
726         bpath = sp_curve_last_bpath(dc->currentcurve);
727         if ( bpath->code == NR_CURVETO ) {
728             sp_curve_curveto(dc->accumulated,
729                              bpath->x1, bpath->y1,
730                              bpath->x2, bpath->y2,
731                              bpath->x3, bpath->y3);
732         } else if ( bpath->code == NR_LINETO ) {
733             sp_curve_lineto(dc->accumulated, bpath->x3, bpath->y3);
734         } else {
735             g_assert_not_reached();
736         }
737     }
740 static void
741 accumulate_calligraphic(SPDynaDrawContext *dc)
743     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
744         sp_curve_reset(dc->accumulated); /*  Is this required ?? */
745         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
746         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
747         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
748         sp_curve_closepath(dc->accumulated);
750         sp_curve_unref(rev_cal2);
752         sp_curve_reset(dc->cal1);
753         sp_curve_reset(dc->cal2);
754     }
757 static void
758 fit_and_split(SPDynaDrawContext *dc,
759               gboolean release)
761     if (dc->use_calligraphic) {
762         fit_and_split_calligraphics(dc, release);
763     } else {
764         fit_and_split_line(dc, release);
765     }
768 static double square(double const x)
770     return x * x;
773 static void
774 fit_and_split_line(SPDynaDrawContext *dc,
775                    gboolean release)
777     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_LINE );
779     NR::Point b[4];
780     double const n_segs = sp_bezier_fit_cubic(b, dc->point1, dc->npoints, tolerance_sq);
781     if ( n_segs > 0
782          && dc->npoints < SAMPLING_SIZE )
783     {
784         /* Fit and draw and reset state */
785 #ifdef DYNA_DRAW_VERBOSE
786         g_print("%d", dc->npoints);
787 #endif
788         sp_curve_reset(dc->currentcurve);
789         sp_curve_moveto(dc->currentcurve, b[0]);
790         sp_curve_curveto(dc->currentcurve, b[1], b[2], b[3]);
791         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
792     } else {
793         /* Fit and draw and copy last point */
794 #ifdef DYNA_DRAW_VERBOSE
795         g_print("[%d]Yup\n", dc->npoints);
796 #endif
797         g_assert(!sp_curve_empty(dc->currentcurve));
798         concat_current_line(dc);
800         SPCanvasItem *cbp = sp_canvas_item_new(SP_DT_SKETCH(SP_EVENT_CONTEXT(dc)->desktop),
801                                                SP_TYPE_CANVAS_BPATH,
802                                                NULL);
803         SPCurve *curve = sp_curve_copy(dc->currentcurve);
804         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(cbp), curve);
805         sp_curve_unref(curve);
806         /* fixme: We have to parse style color somehow */
807         sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), DDC_GREEN_RGBA, SP_WIND_RULE_EVENODD);
808         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x000000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
809         /* fixme: Cannot we cascade it to root more clearly? */
810         g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
812         dc->segments = g_slist_prepend(dc->segments, cbp);
813         dc->point1[0] = dc->point1[dc->npoints - 2];
814         dc->npoints = 1;
815     }
818 static void
819 fit_and_split_calligraphics(SPDynaDrawContext *dc, gboolean release)
821     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
823 #ifdef DYNA_DRAW_VERBOSE
824     g_print("[F&S:R=%c]", release?'T':'F');
825 #endif
827     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
828         return; // just clicked
830     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
831 #define BEZIER_SIZE       4
832 #define BEZIER_MAX_BEZIERS  8
833 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
835 #ifdef DYNA_DRAW_VERBOSE
836         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
837                 dc->npoints, release ? "TRUE" : "FALSE");
838 #endif
840         /* Current calligraphic */
841         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
842             /* dc->npoints > 0 */
843             /* g_print("calligraphics(1|2) reset\n"); */
844             sp_curve_reset(dc->cal1);
845             sp_curve_reset(dc->cal2);
847             sp_curve_moveto(dc->cal1, dc->point1[0]);
848             sp_curve_moveto(dc->cal2, dc->point2[0]);
849         }
851         NR::Point b1[BEZIER_MAX_LENGTH];
852         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
853                                                tolerance_sq, BEZIER_MAX_BEZIERS);
854         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
856         NR::Point b2[BEZIER_MAX_LENGTH];
857         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
858                                                tolerance_sq, BEZIER_MAX_BEZIERS);
859         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
861         if ( nb1 != -1 && nb2 != -1 ) {
862             /* Fit and draw and reset state */
863 #ifdef DYNA_DRAW_VERBOSE
864             g_print("nb1:%d nb2:%d\n", nb1, nb2);
865 #endif
866             /* CanvasShape */
867             if (! release) {
868                 sp_curve_reset(dc->currentcurve);
869                 sp_curve_moveto(dc->currentcurve, b1[0]);
870                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
871                     sp_curve_curveto(dc->currentcurve, bp1[1],
872                                      bp1[2], bp1[3]);
873                 }
874                 sp_curve_lineto(dc->currentcurve,
875                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
876                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
877                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
878                 }
879                 sp_curve_closepath(dc->currentcurve);
880                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
881             }
883             /* Current calligraphic */
884             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
885                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
886             }
887             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
888                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
889             }
890         } else {
891             /* fixme: ??? */
892 #ifdef DYNA_DRAW_VERBOSE
893             g_print("[fit_and_split_calligraphics] failed to fit-cubic.\n");
894 #endif
895             draw_temporary_box(dc);
897             for (gint i = 1; i < dc->npoints; i++) {
898                 sp_curve_lineto(dc->cal1, dc->point1[i]);
899             }
900             for (gint i = 1; i < dc->npoints; i++) {
901                 sp_curve_lineto(dc->cal2, dc->point2[i]);
902             }
903         }
905         /* Fit and draw and copy last point */
906 #ifdef DYNA_DRAW_VERBOSE
907         g_print("[%d]Yup\n", dc->npoints);
908 #endif
909         if (!release) {
910             g_assert(!sp_curve_empty(dc->currentcurve));
912             SPCanvasItem *cbp = sp_canvas_item_new(SP_DT_SKETCH(SP_EVENT_CONTEXT(dc)->desktop),
913                                                    SP_TYPE_CANVAS_BPATH,
914                                                    NULL);
915             SPCurve *curve = sp_curve_copy(dc->currentcurve);
916             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
917             sp_curve_unref(curve);
918             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), 0x000000ff, SP_WIND_RULE_EVENODD);
919             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
920             /* fixme: Cannot we cascade it to root more clearly? */
921             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
923             dc->segments = g_slist_prepend(dc->segments, cbp);
924         }
926         dc->point1[0] = dc->point1[dc->npoints - 1];
927         dc->point2[0] = dc->point2[dc->npoints - 1];
928         dc->npoints = 1;
929     } else {
930         draw_temporary_box(dc);
931     }
934 static void
935 draw_temporary_box(SPDynaDrawContext *dc)
937     sp_curve_reset(dc->currentcurve);
938     sp_curve_moveto(dc->currentcurve, dc->point1[0]);
939     for (gint i = 1; i < dc->npoints; i++) {
940         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
941     }
942     for (gint i = dc->npoints-1; i >= 0; i--) {
943         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
944     }
945     sp_curve_closepath(dc->currentcurve);
946     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
949 /*
950   Local Variables:
951   mode:c++
952   c-file-style:"stroustrup"
953   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
954   indent-tabs-mode:nil
955   fill-column:99
956   End:
957 */
958 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :