Code

patch from Gustav Broberg: undo annotations and history dialog
[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 <glib/gmem.h>
33 #include "macros.h"
34 #include "document.h"
35 #include "selection.h"
36 #include "desktop.h"
37 #include "desktop-events.h"
38 #include "desktop-handles.h"
39 #include "desktop-affine.h"
40 #include "desktop-style.h"
41 #include "message-context.h"
42 #include "pixmaps/cursor-calligraphy.xpm"
43 #include "pixmaps/cursor-calligraphy.pixbuf"
44 #include "dyna-draw-context.h"
45 #include "libnr/n-art-bpath.h"
46 #include "libnr/nr-path.h"
47 #include "xml/repr.h"
48 #include "context-fns.h"
49 #include "sp-item.h"
50 #include "inkscape.h"
51 #include "color.h"
53 #define DDC_RED_RGBA 0xff0000ff
55 #define SAMPLE_TIMEOUT 10
56 #define TOLERANCE_LINE 1.0
57 #define TOLERANCE_CALLIGRAPHIC 3.0
58 #define DYNA_EPSILON 1.0e-6
60 #define DYNA_MIN_WIDTH 1.0e-6
62 #define DRAG_MIN 0.0
63 #define DRAG_DEFAULT 1.0
64 #define DRAG_MAX 1.0
66 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
67 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
68 static void sp_dyna_draw_context_dispose(GObject *object);
70 static void sp_dyna_draw_context_setup(SPEventContext *ec);
71 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
72 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
74 static void clear_current(SPDynaDrawContext *dc);
75 static void set_to_accumulated(SPDynaDrawContext *dc);
76 static void accumulate_calligraphic(SPDynaDrawContext *dc);
78 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
79 static void fit_and_split_calligraphics(SPDynaDrawContext *ddc, gboolean release);
81 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
82 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
83 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
84 static void draw_temporary_box(SPDynaDrawContext *dc);
87 static SPEventContextClass *parent_class;
89 GtkType
90 sp_dyna_draw_context_get_type(void)
91 {
92     static GType type = 0;
93     if (!type) {
94         GTypeInfo info = {
95             sizeof(SPDynaDrawContextClass),
96             NULL, NULL,
97             (GClassInitFunc) sp_dyna_draw_context_class_init,
98             NULL, NULL,
99             sizeof(SPDynaDrawContext),
100             4,
101             (GInstanceInitFunc) sp_dyna_draw_context_init,
102             NULL,   /* value_table */
103         };
104         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
105     }
106     return type;
109 static void
110 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
112     GObjectClass *object_class = (GObjectClass *) klass;
113     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
115     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
117     object_class->dispose = sp_dyna_draw_context_dispose;
119     event_context_class->setup = sp_dyna_draw_context_setup;
120     event_context_class->set = sp_dyna_draw_context_set;
121     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
124 static void
125 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
127     SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
129     event_context->cursor_shape = cursor_calligraphy_xpm;
130     event_context->cursor_pixbuf = gdk_pixbuf_new_from_inline(
131             -1,
132             cursor_calligraphy_pixbuf,
133             FALSE,
134             NULL);  
135     event_context->hot_x = 4;
136     event_context->hot_y = 4;
138     ddc->accumulated = NULL;
139     ddc->segments = NULL;
140     ddc->currentcurve = NULL;
141     ddc->currentshape = NULL;
142     ddc->npoints = 0;
143     ddc->cal1 = NULL;
144     ddc->cal2 = NULL;
145     ddc->repr = NULL;
147     /* DynaDraw values */
148     ddc->cur = NR::Point(0,0);
149     ddc->last = NR::Point(0,0);
150     ddc->vel = NR::Point(0,0);
151     ddc->acc = NR::Point(0,0);
152     ddc->ang = NR::Point(0,0);
153     ddc->del = NR::Point(0,0);
155     /* attributes */
156     ddc->dragging = FALSE;
158     ddc->mass = 0.3;
159     ddc->drag = DRAG_DEFAULT;
160     ddc->angle = 30.0;
161     ddc->width = 0.2;
163     ddc->vel_thin = 0.1;
164     ddc->flatness = 0.9;
166     ddc->abs_width = false;
167     ddc->keep_selected = true;
170 static void
171 sp_dyna_draw_context_dispose(GObject *object)
173     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
175     if (ddc->accumulated) {
176         ddc->accumulated = sp_curve_unref(ddc->accumulated);
177     }
179     while (ddc->segments) {
180         gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
181         ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
182     }
184     if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
185     if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
186     if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
188     if (ddc->currentshape) {
189         gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
190         ddc->currentshape = NULL;
191     }
193     if (ddc->_message_context) {
194         delete ddc->_message_context;
195     }
197     G_OBJECT_CLASS(parent_class)->dispose(object);
200 static void
201 sp_dyna_draw_context_setup(SPEventContext *ec)
203     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
205     if (((SPEventContextClass *) parent_class)->setup)
206         ((SPEventContextClass *) parent_class)->setup(ec);
208     ddc->accumulated = sp_curve_new_sized(32);
209     ddc->currentcurve = sp_curve_new_sized(4);
211     ddc->cal1 = sp_curve_new_sized(32);
212     ddc->cal2 = sp_curve_new_sized(32);
214     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
215     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
216     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
217     /* fixme: Cannot we cascade it to root more clearly? */
218     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
220     sp_event_context_read(ec, "mass");
221     sp_event_context_read(ec, "drag");
222     sp_event_context_read(ec, "angle");
223     sp_event_context_read(ec, "width");
224     sp_event_context_read(ec, "thinning");
225     sp_event_context_read(ec, "tremor");
226     sp_event_context_read(ec, "flatness");
227     sp_event_context_read(ec, "usepressure");
228     sp_event_context_read(ec, "usetilt");
229     sp_event_context_read(ec, "abs_width");
230     sp_event_context_read(ec, "keep_selected");
232     ddc->is_drawing = false;
234     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
237 static void
238 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
240     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
242     if (!strcmp(key, "mass")) {
243         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
244         ddc->mass = CLAMP(dval, -1000.0, 1000.0);
245     } else if (!strcmp(key, "drag")) {
246         double const dval = ( val ? g_ascii_strtod (val, NULL) : DRAG_DEFAULT );
247         ddc->drag = CLAMP(dval, DRAG_MIN, DRAG_MAX);
248     } else if (!strcmp(key, "angle")) {
249         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
250         ddc->angle = CLAMP (dval, -90, 90);
251     } else if (!strcmp(key, "width")) {
252         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
253         ddc->width = CLAMP(dval, -1000.0, 1000.0);
254     } else if (!strcmp(key, "thinning")) {
255         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
256         ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
257     } else if (!strcmp(key, "tremor")) {
258         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
259         ddc->tremor = CLAMP(dval, 0.0, 1.0);
260     } else if (!strcmp(key, "flatness")) {
261         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
262         ddc->flatness = CLAMP(dval, 0, 1.0);
263     } else if (!strcmp(key, "usepressure")) {
264         ddc->usepressure = (val && strcmp(val, "0"));
265     } else if (!strcmp(key, "usetilt")) {
266         ddc->usetilt = (val && strcmp(val, "0"));
267     } else if (!strcmp(key, "abs_width")) {
268         ddc->abs_width = (val && strcmp(val, "0"));
269     } else if (!strcmp(key, "keep_selected")) {
270         ddc->keep_selected = (val && strcmp(val, "0"));
271     }
273     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
276 static double
277 flerp(double f0, double f1, double p)
279     return f0 + ( f1 - f0 ) * p;
282 /* Get normalized point */
283 static NR::Point
284 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
286     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
287     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
288     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
291 /* Get view point */
292 static NR::Point
293 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
295     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
296     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
297     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
300 static void
301 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
303     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
304     dc->vel = NR::Point(0,0);
305     dc->acc = NR::Point(0,0);
306     dc->ang = NR::Point(0,0);
307     dc->del = NR::Point(0,0);
310 static void
311 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
313     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
314         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
315     else
316         dc->pressure = DDC_DEFAULT_PRESSURE;
318     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
319         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
320     else
321         dc->xtilt = DDC_DEFAULT_TILT;
323     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
324         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
325     else
326         dc->ytilt = DDC_DEFAULT_TILT;
330 static gboolean
331 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
333     NR::Point n = sp_dyna_draw_get_npoint(dc, p);
335     /* Calculate mass and drag */
336     double const mass = flerp(1.0, 160.0, dc->mass);
337     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
339     /* Calculate force and acceleration */
340     NR::Point force = n - dc->cur;
341     if ( NR::L2(force) < DYNA_EPSILON ) {
342         return FALSE;
343     }
345     dc->acc = force / mass;
347     /* Calculate new velocity */
348     dc->vel += dc->acc;
350     /* Calculate angle of drawing tool */
352     double a1;
353     if (dc->usetilt) {
354         // 1a. calculate nib angle from input device tilt:
355         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
357         if (length > 0) {
358             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
359             a1 = atan2(ang1);
360         }
361         else
362             a1 = 0.0;
363     }
364     else {
365         // 1b. fixed dc->angle (absolutely flat nib):
366         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
367         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
368         a1 = atan2(ang1);
369     }
371     // 2. perpendicular to dc->vel (absolutely non-flat nib):
372     gdouble const mag_vel = NR::L2(dc->vel);
373     if ( mag_vel < DYNA_EPSILON ) {
374         return FALSE;
375     }
376     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
378     // 3. Average them using flatness parameter:
379     // calculate angles
380     double a2 = atan2(ang2);
381     // flip a2 to force it to be in the same half-circle as a1
382     bool flipped = false;
383     if (fabs (a2-a1) > 0.5*M_PI) {
384         a2 += M_PI;
385         flipped = true;
386     }
387     // normalize a2
388     if (a2 > M_PI)
389         a2 -= 2*M_PI;
390     if (a2 < -M_PI)
391         a2 += 2*M_PI;
392     // find the flatness-weighted bisector angle, unflip if a2 was flipped
393     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
394     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
395     // convert to point
396     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
398     /* Apply drag */
399     dc->vel *= 1.0 - drag;
401     /* Update position */
402     dc->last = dc->cur;
403     dc->cur += dc->vel;
405     return TRUE;
408 static void
409 sp_dyna_draw_brush(SPDynaDrawContext *dc)
411     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
413     // How much velocity thins strokestyle
414     double vel_thin = flerp (0, 160, dc->vel_thin);
416     // Influence of pressure on thickness
417     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
419     double width = ( pressure_thick - vel_thin * NR::L2(dc->vel) ) * dc->width;
421     double tremble_left = 0, tremble_right = 0;
422     if (dc->tremor > 0) {
423         // obtain two normally distributed random variables, using polar Box-Muller transform
424         double x1, x2, w, y1, y2;
425         do {
426             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
427             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
428             w = x1 * x1 + x2 * x2;
429         } while ( w >= 1.0 );
430         w = sqrt( (-2.0 * log( w ) ) / w );
431         y1 = x1 * w;
432         y2 = x2 * w;
434         // deflect both left and right edges randomly and independently, so that:
435         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
436         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
437         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
438         // comparatively smooth and slow ones excessively jittery
439         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
440         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
441     }
443     if ( width < 0.02 * dc->width ) {
444         width = 0.02 * dc->width;
445     }
447     double dezoomify_factor = 0.05 * 1000;
448     if (!dc->abs_width) {
449         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
450     }
452     NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
453     NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
455     NR::Point abs_middle = sp_dyna_draw_get_vpoint(dc, dc->cur);
457     dc->point1[dc->npoints] = abs_middle + del_left;
458     dc->point2[dc->npoints] = abs_middle - del_right;
460     dc->del = 0.5*(del_left + del_right);
462     dc->npoints++;
465 void
466 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
468     desktop->setToolboxAdjustmentValue (id, value);
471 gint
472 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
473                                   GdkEvent *event)
475     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
476     SPDesktop *desktop = event_context->desktop;
478     gint ret = FALSE;
480     switch (event->type) {
481     case GDK_BUTTON_PRESS:
482         if ( event->button.button == 1 ) {
484             SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
486             if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
487                 return TRUE;
488             }
490             NR::Point const button_w(event->button.x,
491                                      event->button.y);
492             NR::Point const button_dt(desktop->w2d(button_w));
493             sp_dyna_draw_reset(dc, button_dt);
494             sp_dyna_draw_extinput(dc, event);
495             sp_dyna_draw_apply(dc, button_dt);
496             sp_curve_reset(dc->accumulated);
497             if (dc->repr) {
498                 dc->repr = NULL;
499             }
501             /* initialize first point */
502             dc->npoints = 0;
504             sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
505                                 ( GDK_KEY_PRESS_MASK |
506                                   GDK_BUTTON_RELEASE_MASK |
507                                   GDK_POINTER_MOTION_MASK |
508                                   GDK_BUTTON_PRESS_MASK ),
509                                 NULL,
510                                 event->button.time);
512             ret = TRUE;
514             dc->is_drawing = true;
515         }
516         break;
517     case GDK_MOTION_NOTIFY:
518         if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
519             dc->dragging = TRUE;
521             NR::Point const motion_w(event->motion.x,
522                                      event->motion.y);
523             NR::Point const motion_dt(desktop->w2d(motion_w));
525             sp_dyna_draw_extinput(dc, event);
526             if (!sp_dyna_draw_apply(dc, motion_dt)) {
527                 ret = TRUE;
528                 break;
529             }
531             if ( dc->cur != dc->last ) {
532                 sp_dyna_draw_brush(dc);
533                 g_assert( dc->npoints > 0 );
534                 fit_and_split(dc, FALSE);
535             }
536             ret = TRUE;
537         }
538         break;
540     case GDK_BUTTON_RELEASE:
541         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
542         dc->is_drawing = false;
543         if ( dc->dragging && event->button.button == 1 ) {
544             dc->dragging = FALSE;
546             /* Remove all temporary line segments */
547             while (dc->segments) {
548                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
549                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
550             }
551             /* Create object */
552             fit_and_split(dc, TRUE);
553             accumulate_calligraphic(dc);
554             set_to_accumulated(dc); /* temporal implementation */
555             /* reset accumulated curve */
556             sp_curve_reset(dc->accumulated);
557             clear_current(dc);
558             if (dc->repr) {
559                 dc->repr = NULL;
560             }
561             ret = TRUE;
562         }
563         break;
564     case GDK_KEY_PRESS:
565         switch (get_group0_keyval (&event->key)) {
566         case GDK_Up:
567         case GDK_KP_Up:
568             if (!MOD__CTRL_ONLY) {
569                 dc->angle += 5.0;
570                 if (dc->angle > 90.0)
571                     dc->angle = 90.0;
572                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
573                 ret = TRUE;
574             }
575             break;
576         case GDK_Down:
577         case GDK_KP_Down:
578             if (!MOD__CTRL_ONLY) {
579                 dc->angle -= 5.0;
580                 if (dc->angle < -90.0)
581                     dc->angle = -90.0;
582                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
583                 ret = TRUE;
584             }
585             break;
586         case GDK_Right:
587         case GDK_KP_Right:
588             if (!MOD__CTRL_ONLY) {
589                 dc->width += 0.01;
590                 if (dc->width > 1.0)
591                     dc->width = 1.0;
592                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
593                 ret = TRUE;
594             }
595             break;
596         case GDK_Left:
597         case GDK_KP_Left:
598             if (!MOD__CTRL_ONLY) {
599                 dc->width -= 0.01;
600                 if (dc->width < 0.01)
601                     dc->width = 0.01;
602                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
603                 ret = TRUE;
604             }
605             break;
606         case GDK_x:
607         case GDK_X:
608             if (MOD__ALT_ONLY) {
609                 desktop->setToolboxFocusTo ("altx-calligraphy");
610                 ret = TRUE;
611             }
612             break;
613         case GDK_Escape:
614             sp_desktop_selection(desktop)->clear();
615             break;
617         default:
618             break;
619         }
620     default:
621         break;
622     }
624     if (!ret) {
625         if (((SPEventContextClass *) parent_class)->root_handler) {
626             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
627         }
628     }
630     return ret;
634 static void
635 clear_current(SPDynaDrawContext *dc)
637     /* reset bpath */
638     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
639     /* reset curve */
640     sp_curve_reset(dc->currentcurve);
641     sp_curve_reset(dc->cal1);
642     sp_curve_reset(dc->cal2);
643     /* reset points */
644     dc->npoints = 0;
647 static void
648 set_to_accumulated(SPDynaDrawContext *dc)
650     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
652     if (!sp_curve_empty(dc->accumulated)) {
653         NArtBpath *abp;
654         gchar *str;
656         if (!dc->repr) {
657             /* Create object */
658             Inkscape::XML::Node *repr = sp_repr_new("svg:path");
660             /* Set style */
661             sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
663             dc->repr = repr;
665             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
666             Inkscape::GC::release(dc->repr);
667             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
668             item->updateRepr();
669             if (dc->keep_selected) {
670                 sp_desktop_selection(desktop)->set(dc->repr);
671             } else {
672                 sp_desktop_selection(desktop)->clear();
673             }
674         }
675         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
676         str = sp_svg_write_path(abp);
677         g_assert( str != NULL );
678         g_free(abp);
679         dc->repr->setAttribute("d", str);
680         g_free(str);
681     } else {
682         if (dc->repr) {
683             sp_repr_unparent(dc->repr);
684         }
685         dc->repr = NULL;
686     }
688     sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC, 
689                      /* TODO: annotate */ "dyna-draw-context.cpp:689");
692 static void
693 accumulate_calligraphic(SPDynaDrawContext *dc)
695     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
696         sp_curve_reset(dc->accumulated); /*  Is this required ?? */
697         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
698         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
699         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
700         sp_curve_closepath(dc->accumulated);
702         sp_curve_unref(rev_cal2);
704         sp_curve_reset(dc->cal1);
705         sp_curve_reset(dc->cal2);
706     }
709 static void
710 fit_and_split(SPDynaDrawContext *dc,
711               gboolean release)
713     fit_and_split_calligraphics(dc, release);
716 static double square(double const x)
718     return x * x;
721 static void
722 fit_and_split_calligraphics(SPDynaDrawContext *dc, gboolean release)
724     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
726 #ifdef DYNA_DRAW_VERBOSE
727     g_print("[F&S:R=%c]", release?'T':'F');
728 #endif
730     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
731         return; // just clicked
733     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
734 #define BEZIER_SIZE       4
735 #define BEZIER_MAX_BEZIERS  8
736 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
738 #ifdef DYNA_DRAW_VERBOSE
739         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
740                 dc->npoints, release ? "TRUE" : "FALSE");
741 #endif
743         /* Current calligraphic */
744         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
745             /* dc->npoints > 0 */
746             /* g_print("calligraphics(1|2) reset\n"); */
747             sp_curve_reset(dc->cal1);
748             sp_curve_reset(dc->cal2);
750             sp_curve_moveto(dc->cal1, dc->point1[0]);
751             sp_curve_moveto(dc->cal2, dc->point2[0]);
752         }
754         NR::Point b1[BEZIER_MAX_LENGTH];
755         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
756                                                tolerance_sq, BEZIER_MAX_BEZIERS);
757         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
759         NR::Point b2[BEZIER_MAX_LENGTH];
760         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
761                                                tolerance_sq, BEZIER_MAX_BEZIERS);
762         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
764         if ( nb1 != -1 && nb2 != -1 ) {
765             /* Fit and draw and reset state */
766 #ifdef DYNA_DRAW_VERBOSE
767             g_print("nb1:%d nb2:%d\n", nb1, nb2);
768 #endif
769             /* CanvasShape */
770             if (! release) {
771                 sp_curve_reset(dc->currentcurve);
772                 sp_curve_moveto(dc->currentcurve, b1[0]);
773                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
774                     sp_curve_curveto(dc->currentcurve, bp1[1],
775                                      bp1[2], bp1[3]);
776                 }
777                 sp_curve_lineto(dc->currentcurve,
778                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
779                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
780                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
781                 }
782                 sp_curve_closepath(dc->currentcurve);
783                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
784             }
786             /* Current calligraphic */
787             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
788                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
789             }
790             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
791                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
792             }
793         } else {
794             /* fixme: ??? */
795 #ifdef DYNA_DRAW_VERBOSE
796             g_print("[fit_and_split_calligraphics] failed to fit-cubic.\n");
797 #endif
798             draw_temporary_box(dc);
800             for (gint i = 1; i < dc->npoints; i++) {
801                 sp_curve_lineto(dc->cal1, dc->point1[i]);
802             }
803             for (gint i = 1; i < dc->npoints; i++) {
804                 sp_curve_lineto(dc->cal2, dc->point2[i]);
805             }
806         }
808         /* Fit and draw and copy last point */
809 #ifdef DYNA_DRAW_VERBOSE
810         g_print("[%d]Yup\n", dc->npoints);
811 #endif
812         if (!release) {
813             g_assert(!sp_curve_empty(dc->currentcurve));
815             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
816                                                    SP_TYPE_CANVAS_BPATH,
817                                                    NULL);
818             SPCurve *curve = sp_curve_copy(dc->currentcurve);
819             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
820             sp_curve_unref(curve);
822             guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
823             //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
824             double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
825             double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
826             //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
827             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
828             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
829             //sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), ((strokeColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*strokeOpacity)), 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
830             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
831             /* fixme: Cannot we cascade it to root more clearly? */
832             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
834             dc->segments = g_slist_prepend(dc->segments, cbp);
835         }
837         dc->point1[0] = dc->point1[dc->npoints - 1];
838         dc->point2[0] = dc->point2[dc->npoints - 1];
839         dc->npoints = 1;
840     } else {
841         draw_temporary_box(dc);
842     }
845 static void
846 draw_temporary_box(SPDynaDrawContext *dc)
848     sp_curve_reset(dc->currentcurve);
849     sp_curve_moveto(dc->currentcurve, dc->point1[0]);
850     for (gint i = 1; i < dc->npoints; i++) {
851         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
852     }
853     for (gint i = dc->npoints-1; i >= 0; i--) {
854         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
855     }
856     sp_curve_closepath(dc->currentcurve);
857     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
860 /*
861   Local Variables:
862   mode:c++
863   c-file-style:"stroustrup"
864   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
865   indent-tabs-mode:nil
866   fill-column:99
867   End:
868 */
869 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :