Code

replace nr_new() with g_new(), and try to converge on using the glib allocator a...
[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 "dyna-draw-context.h"
44 #include "libnr/n-art-bpath.h"
45 #include "libnr/nr-path.h"
46 #include "xml/repr.h"
47 #include "context-fns.h"
48 #include "sp-item.h"
49 #include "inkscape.h"
50 #include "color.h"
52 #define DDC_RED_RGBA 0xff0000ff
54 #define SAMPLE_TIMEOUT 10
55 #define TOLERANCE_LINE 1.0
56 #define TOLERANCE_CALLIGRAPHIC 3.0
57 #define DYNA_EPSILON 1.0e-6
59 #define DYNA_MIN_WIDTH 1.0e-6
61 #define DRAG_MIN 0.0
62 #define DRAG_DEFAULT 1.0
63 #define DRAG_MAX 1.0
65 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
66 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
67 static void sp_dyna_draw_context_dispose(GObject *object);
69 static void sp_dyna_draw_context_setup(SPEventContext *ec);
70 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
71 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
73 static void clear_current(SPDynaDrawContext *dc);
74 static void set_to_accumulated(SPDynaDrawContext *dc);
75 static void accumulate_calligraphic(SPDynaDrawContext *dc);
77 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
78 static void fit_and_split_calligraphics(SPDynaDrawContext *ddc, gboolean release);
80 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
81 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
82 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
83 static void draw_temporary_box(SPDynaDrawContext *dc);
86 static SPEventContextClass *parent_class;
88 GtkType
89 sp_dyna_draw_context_get_type(void)
90 {
91     static GType type = 0;
92     if (!type) {
93         GTypeInfo info = {
94             sizeof(SPDynaDrawContextClass),
95             NULL, NULL,
96             (GClassInitFunc) sp_dyna_draw_context_class_init,
97             NULL, NULL,
98             sizeof(SPDynaDrawContext),
99             4,
100             (GInstanceInitFunc) sp_dyna_draw_context_init,
101             NULL,   /* value_table */
102         };
103         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
104     }
105     return type;
108 static void
109 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
111     GObjectClass *object_class = (GObjectClass *) klass;
112     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
114     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
116     object_class->dispose = sp_dyna_draw_context_dispose;
118     event_context_class->setup = sp_dyna_draw_context_setup;
119     event_context_class->set = sp_dyna_draw_context_set;
120     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
123 static void
124 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
126     SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
128     event_context->cursor_shape = cursor_calligraphy_xpm;
129     event_context->hot_x = 4;
130     event_context->hot_y = 4;
132     ddc->accumulated = NULL;
133     ddc->segments = NULL;
134     ddc->currentcurve = NULL;
135     ddc->currentshape = NULL;
136     ddc->npoints = 0;
137     ddc->cal1 = NULL;
138     ddc->cal2 = NULL;
139     ddc->repr = NULL;
141     /* DynaDraw values */
142     ddc->cur = NR::Point(0,0);
143     ddc->last = NR::Point(0,0);
144     ddc->vel = NR::Point(0,0);
145     ddc->acc = NR::Point(0,0);
146     ddc->ang = NR::Point(0,0);
147     ddc->del = NR::Point(0,0);
149     /* attributes */
150     ddc->dragging = FALSE;
152     ddc->mass = 0.3;
153     ddc->drag = DRAG_DEFAULT;
154     ddc->angle = 30.0;
155     ddc->width = 0.2;
157     ddc->vel_thin = 0.1;
158     ddc->flatness = 0.9;
160     ddc->abs_width = false;
161     ddc->keep_selected = true;
164 static void
165 sp_dyna_draw_context_dispose(GObject *object)
167     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
169     if (ddc->accumulated) {
170         ddc->accumulated = sp_curve_unref(ddc->accumulated);
171     }
173     while (ddc->segments) {
174         gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
175         ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
176     }
178     if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
179     if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
180     if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
182     if (ddc->currentshape) {
183         gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
184         ddc->currentshape = NULL;
185     }
187     if (ddc->_message_context) {
188         delete ddc->_message_context;
189     }
191     G_OBJECT_CLASS(parent_class)->dispose(object);
194 static void
195 sp_dyna_draw_context_setup(SPEventContext *ec)
197     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
199     if (((SPEventContextClass *) parent_class)->setup)
200         ((SPEventContextClass *) parent_class)->setup(ec);
202     ddc->accumulated = sp_curve_new_sized(32);
203     ddc->currentcurve = sp_curve_new_sized(4);
205     ddc->cal1 = sp_curve_new_sized(32);
206     ddc->cal2 = sp_curve_new_sized(32);
208     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
209     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
210     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
211     /* fixme: Cannot we cascade it to root more clearly? */
212     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
214     sp_event_context_read(ec, "mass");
215     sp_event_context_read(ec, "drag");
216     sp_event_context_read(ec, "angle");
217     sp_event_context_read(ec, "width");
218     sp_event_context_read(ec, "thinning");
219     sp_event_context_read(ec, "tremor");
220     sp_event_context_read(ec, "flatness");
221     sp_event_context_read(ec, "usepressure");
222     sp_event_context_read(ec, "usetilt");
223     sp_event_context_read(ec, "abs_width");
224     sp_event_context_read(ec, "keep_selected");
226     ddc->is_drawing = false;
228     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
231 static void
232 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
234     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
236     if (!strcmp(key, "mass")) {
237         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
238         ddc->mass = CLAMP(dval, -1000.0, 1000.0);
239     } else if (!strcmp(key, "drag")) {
240         double const dval = ( val ? g_ascii_strtod (val, NULL) : DRAG_DEFAULT );
241         ddc->drag = CLAMP(dval, DRAG_MIN, DRAG_MAX);
242     } else if (!strcmp(key, "angle")) {
243         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
244         ddc->angle = CLAMP (dval, -90, 90);
245     } else if (!strcmp(key, "width")) {
246         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
247         ddc->width = CLAMP(dval, -1000.0, 1000.0);
248     } else if (!strcmp(key, "thinning")) {
249         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
250         ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
251     } else if (!strcmp(key, "tremor")) {
252         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
253         ddc->tremor = CLAMP(dval, 0.0, 1.0);
254     } else if (!strcmp(key, "flatness")) {
255         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
256         ddc->flatness = CLAMP(dval, 0, 1.0);
257     } else if (!strcmp(key, "usepressure")) {
258         ddc->usepressure = (val && strcmp(val, "0"));
259     } else if (!strcmp(key, "usetilt")) {
260         ddc->usetilt = (val && strcmp(val, "0"));
261     } else if (!strcmp(key, "abs_width")) {
262         ddc->abs_width = (val && strcmp(val, "0"));
263     } else if (!strcmp(key, "keep_selected")) {
264         ddc->keep_selected = (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 static void
295 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
297     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
298     dc->vel = NR::Point(0,0);
299     dc->acc = NR::Point(0,0);
300     dc->ang = NR::Point(0,0);
301     dc->del = NR::Point(0,0);
304 static void
305 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
307     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
308         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
309     else
310         dc->pressure = DDC_DEFAULT_PRESSURE;
312     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
313         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
314     else
315         dc->xtilt = DDC_DEFAULT_TILT;
317     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
318         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
319     else
320         dc->ytilt = DDC_DEFAULT_TILT;
324 static gboolean
325 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
327     NR::Point n = sp_dyna_draw_get_npoint(dc, p);
329     /* Calculate mass and drag */
330     double const mass = flerp(1.0, 160.0, dc->mass);
331     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
333     /* Calculate force and acceleration */
334     NR::Point force = n - dc->cur;
335     if ( NR::L2(force) < DYNA_EPSILON ) {
336         return FALSE;
337     }
339     dc->acc = force / mass;
341     /* Calculate new velocity */
342     dc->vel += dc->acc;
344     /* Calculate angle of drawing tool */
346     double a1;
347     if (dc->usetilt) {
348         // 1a. calculate nib angle from input device tilt:
349         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
351         if (length > 0) {
352             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
353             a1 = atan2(ang1);
354         }
355         else
356             a1 = 0.0;
357     }
358     else {
359         // 1b. fixed dc->angle (absolutely flat nib):
360         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
361         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
362         a1 = atan2(ang1);
363     }
365     // 2. perpendicular to dc->vel (absolutely non-flat nib):
366     gdouble const mag_vel = NR::L2(dc->vel);
367     if ( mag_vel < DYNA_EPSILON ) {
368         return FALSE;
369     }
370     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
372     // 3. Average them using flatness parameter:
373     // calculate angles
374     double a2 = atan2(ang2);
375     // flip a2 to force it to be in the same half-circle as a1
376     bool flipped = false;
377     if (fabs (a2-a1) > 0.5*M_PI) {
378         a2 += M_PI;
379         flipped = true;
380     }
381     // normalize a2
382     if (a2 > M_PI)
383         a2 -= 2*M_PI;
384     if (a2 < -M_PI)
385         a2 += 2*M_PI;
386     // find the flatness-weighted bisector angle, unflip if a2 was flipped
387     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
388     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
389     // convert to point
390     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
392     /* Apply drag */
393     dc->vel *= 1.0 - drag;
395     /* Update position */
396     dc->last = dc->cur;
397     dc->cur += dc->vel;
399     return TRUE;
402 static void
403 sp_dyna_draw_brush(SPDynaDrawContext *dc)
405     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
407     // How much velocity thins strokestyle
408     double vel_thin = flerp (0, 160, dc->vel_thin);
410     // Influence of pressure on thickness
411     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
413     double width = ( pressure_thick - vel_thin * NR::L2(dc->vel) ) * dc->width;
415     double tremble_left = 0, tremble_right = 0;
416     if (dc->tremor > 0) {
417         // obtain two normally distributed random variables, using polar Box-Muller transform
418         double x1, x2, w, y1, y2;
419         do {
420             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
421             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
422             w = x1 * x1 + x2 * x2;
423         } while ( w >= 1.0 );
424         w = sqrt( (-2.0 * log( w ) ) / w );
425         y1 = x1 * w;
426         y2 = x2 * w;
428         // deflect both left and right edges randomly and independently, so that:
429         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
430         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
431         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
432         // comparatively smooth and slow ones excessively jittery
433         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
434         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
435     }
437     if ( width < 0.02 * dc->width ) {
438         width = 0.02 * dc->width;
439     }
441     double dezoomify_factor = 0.05 * 1000;
442     if (!dc->abs_width) {
443         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
444     }
446     NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
447     NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
449     NR::Point abs_middle = sp_dyna_draw_get_vpoint(dc, dc->cur);
451     dc->point1[dc->npoints] = abs_middle + del_left;
452     dc->point2[dc->npoints] = abs_middle - del_right;
454     dc->del = 0.5*(del_left + del_right);
456     dc->npoints++;
459 void
460 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
462     desktop->setToolboxAdjustmentValue (id, value);
465 gint
466 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
467                                   GdkEvent *event)
469     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
470     SPDesktop *desktop = event_context->desktop;
472     gint ret = FALSE;
474     switch (event->type) {
475     case GDK_BUTTON_PRESS:
476         if ( event->button.button == 1 ) {
478             SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
480             if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
481                 return TRUE;
482             }
484             NR::Point const button_w(event->button.x,
485                                      event->button.y);
486             NR::Point const button_dt(desktop->w2d(button_w));
487             sp_dyna_draw_reset(dc, button_dt);
488             sp_dyna_draw_extinput(dc, event);
489             sp_dyna_draw_apply(dc, button_dt);
490             sp_curve_reset(dc->accumulated);
491             if (dc->repr) {
492                 dc->repr = NULL;
493             }
495             /* initialize first point */
496             dc->npoints = 0;
498             sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
499                                 ( GDK_KEY_PRESS_MASK |
500                                   GDK_BUTTON_RELEASE_MASK |
501                                   GDK_POINTER_MOTION_MASK |
502                                   GDK_BUTTON_PRESS_MASK ),
503                                 NULL,
504                                 event->button.time);
506             ret = TRUE;
508             dc->is_drawing = true;
509         }
510         break;
511     case GDK_MOTION_NOTIFY:
512         if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
513             dc->dragging = TRUE;
515             NR::Point const motion_w(event->motion.x,
516                                      event->motion.y);
517             NR::Point const motion_dt(desktop->w2d(motion_w));
519             sp_dyna_draw_extinput(dc, event);
520             if (!sp_dyna_draw_apply(dc, motion_dt)) {
521                 ret = TRUE;
522                 break;
523             }
525             if ( dc->cur != dc->last ) {
526                 sp_dyna_draw_brush(dc);
527                 g_assert( dc->npoints > 0 );
528                 fit_and_split(dc, FALSE);
529             }
530             ret = TRUE;
531         }
532         break;
534     case GDK_BUTTON_RELEASE:
535         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
536         dc->is_drawing = false;
537         if ( dc->dragging && event->button.button == 1 ) {
538             dc->dragging = FALSE;
540             /* Remove all temporary line segments */
541             while (dc->segments) {
542                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
543                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
544             }
545             /* Create object */
546             fit_and_split(dc, TRUE);
547             accumulate_calligraphic(dc);
548             set_to_accumulated(dc); /* temporal implementation */
549             /* reset accumulated curve */
550             sp_curve_reset(dc->accumulated);
551             clear_current(dc);
552             if (dc->repr) {
553                 dc->repr = NULL;
554             }
555             ret = TRUE;
556         }
557         break;
558     case GDK_KEY_PRESS:
559         switch (get_group0_keyval (&event->key)) {
560         case GDK_Up:
561         case GDK_KP_Up:
562             if (!MOD__CTRL_ONLY) {
563                 dc->angle += 5.0;
564                 if (dc->angle > 90.0)
565                     dc->angle = 90.0;
566                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
567                 ret = TRUE;
568             }
569             break;
570         case GDK_Down:
571         case GDK_KP_Down:
572             if (!MOD__CTRL_ONLY) {
573                 dc->angle -= 5.0;
574                 if (dc->angle < -90.0)
575                     dc->angle = -90.0;
576                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
577                 ret = TRUE;
578             }
579             break;
580         case GDK_Right:
581         case GDK_KP_Right:
582             if (!MOD__CTRL_ONLY) {
583                 dc->width += 0.01;
584                 if (dc->width > 1.0)
585                     dc->width = 1.0;
586                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
587                 ret = TRUE;
588             }
589             break;
590         case GDK_Left:
591         case GDK_KP_Left:
592             if (!MOD__CTRL_ONLY) {
593                 dc->width -= 0.01;
594                 if (dc->width < 0.01)
595                     dc->width = 0.01;
596                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
597                 ret = TRUE;
598             }
599             break;
600         case GDK_x:
601         case GDK_X:
602             if (MOD__ALT_ONLY) {
603                 desktop->setToolboxFocusTo ("altx-calligraphy");
604                 ret = TRUE;
605             }
606             break;
607         case GDK_Escape:
608             sp_desktop_selection(desktop)->clear();
609             break;
611         default:
612             break;
613         }
614     default:
615         break;
616     }
618     if (!ret) {
619         if (((SPEventContextClass *) parent_class)->root_handler) {
620             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
621         }
622     }
624     return ret;
628 static void
629 clear_current(SPDynaDrawContext *dc)
631     /* reset bpath */
632     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
633     /* reset curve */
634     sp_curve_reset(dc->currentcurve);
635     sp_curve_reset(dc->cal1);
636     sp_curve_reset(dc->cal2);
637     /* reset points */
638     dc->npoints = 0;
641 static void
642 set_to_accumulated(SPDynaDrawContext *dc)
644     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
646     if (!sp_curve_empty(dc->accumulated)) {
647         NArtBpath *abp;
648         gchar *str;
650         if (!dc->repr) {
651             /* Create object */
652             Inkscape::XML::Node *repr = sp_repr_new("svg:path");
654             /* Set style */
655             sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
657             dc->repr = repr;
659             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
660             Inkscape::GC::release(dc->repr);
661             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
662             item->updateRepr();
663             if (dc->keep_selected) {
664                 sp_desktop_selection(desktop)->set(dc->repr);
665             } else {
666                 sp_desktop_selection(desktop)->clear();
667             }
668         }
669         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
670         str = sp_svg_write_path(abp);
671         g_assert( str != NULL );
672         g_free(abp);
673         dc->repr->setAttribute("d", str);
674         g_free(str);
675     } else {
676         if (dc->repr) {
677             sp_repr_unparent(dc->repr);
678         }
679         dc->repr = NULL;
680     }
682     sp_document_done(sp_desktop_document(desktop));
685 static void
686 accumulate_calligraphic(SPDynaDrawContext *dc)
688     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
689         sp_curve_reset(dc->accumulated); /*  Is this required ?? */
690         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
691         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
692         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
693         sp_curve_closepath(dc->accumulated);
695         sp_curve_unref(rev_cal2);
697         sp_curve_reset(dc->cal1);
698         sp_curve_reset(dc->cal2);
699     }
702 static void
703 fit_and_split(SPDynaDrawContext *dc,
704               gboolean release)
706     fit_and_split_calligraphics(dc, release);
709 static double square(double const x)
711     return x * x;
714 static void
715 fit_and_split_calligraphics(SPDynaDrawContext *dc, gboolean release)
717     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
719 #ifdef DYNA_DRAW_VERBOSE
720     g_print("[F&S:R=%c]", release?'T':'F');
721 #endif
723     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
724         return; // just clicked
726     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
727 #define BEZIER_SIZE       4
728 #define BEZIER_MAX_BEZIERS  8
729 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
731 #ifdef DYNA_DRAW_VERBOSE
732         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
733                 dc->npoints, release ? "TRUE" : "FALSE");
734 #endif
736         /* Current calligraphic */
737         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
738             /* dc->npoints > 0 */
739             /* g_print("calligraphics(1|2) reset\n"); */
740             sp_curve_reset(dc->cal1);
741             sp_curve_reset(dc->cal2);
743             sp_curve_moveto(dc->cal1, dc->point1[0]);
744             sp_curve_moveto(dc->cal2, dc->point2[0]);
745         }
747         NR::Point b1[BEZIER_MAX_LENGTH];
748         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
749                                                tolerance_sq, BEZIER_MAX_BEZIERS);
750         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
752         NR::Point b2[BEZIER_MAX_LENGTH];
753         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
754                                                tolerance_sq, BEZIER_MAX_BEZIERS);
755         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
757         if ( nb1 != -1 && nb2 != -1 ) {
758             /* Fit and draw and reset state */
759 #ifdef DYNA_DRAW_VERBOSE
760             g_print("nb1:%d nb2:%d\n", nb1, nb2);
761 #endif
762             /* CanvasShape */
763             if (! release) {
764                 sp_curve_reset(dc->currentcurve);
765                 sp_curve_moveto(dc->currentcurve, b1[0]);
766                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
767                     sp_curve_curveto(dc->currentcurve, bp1[1],
768                                      bp1[2], bp1[3]);
769                 }
770                 sp_curve_lineto(dc->currentcurve,
771                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
772                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
773                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
774                 }
775                 sp_curve_closepath(dc->currentcurve);
776                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
777             }
779             /* Current calligraphic */
780             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
781                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
782             }
783             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
784                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
785             }
786         } else {
787             /* fixme: ??? */
788 #ifdef DYNA_DRAW_VERBOSE
789             g_print("[fit_and_split_calligraphics] failed to fit-cubic.\n");
790 #endif
791             draw_temporary_box(dc);
793             for (gint i = 1; i < dc->npoints; i++) {
794                 sp_curve_lineto(dc->cal1, dc->point1[i]);
795             }
796             for (gint i = 1; i < dc->npoints; i++) {
797                 sp_curve_lineto(dc->cal2, dc->point2[i]);
798             }
799         }
801         /* Fit and draw and copy last point */
802 #ifdef DYNA_DRAW_VERBOSE
803         g_print("[%d]Yup\n", dc->npoints);
804 #endif
805         if (!release) {
806             g_assert(!sp_curve_empty(dc->currentcurve));
808             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
809                                                    SP_TYPE_CANVAS_BPATH,
810                                                    NULL);
811             SPCurve *curve = sp_curve_copy(dc->currentcurve);
812             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
813             sp_curve_unref(curve);
815             guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
816             //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
817             double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
818             double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
819             //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
820             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
821             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
822             //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);
823             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
824             /* fixme: Cannot we cascade it to root more clearly? */
825             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
827             dc->segments = g_slist_prepend(dc->segments, cbp);
828         }
830         dc->point1[0] = dc->point1[dc->npoints - 1];
831         dc->point2[0] = dc->point2[dc->npoints - 1];
832         dc->npoints = 1;
833     } else {
834         draw_temporary_box(dc);
835     }
838 static void
839 draw_temporary_box(SPDynaDrawContext *dc)
841     sp_curve_reset(dc->currentcurve);
842     sp_curve_moveto(dc->currentcurve, dc->point1[0]);
843     for (gint i = 1; i < dc->npoints; i++) {
844         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
845     }
846     for (gint i = dc->npoints-1; i >= 0; i--) {
847         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
848     }
849     sp_curve_closepath(dc->currentcurve);
850     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
853 /*
854   Local Variables:
855   mode:c++
856   c-file-style:"stroustrup"
857   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
858   indent-tabs-mode:nil
859   fill-column:99
860   End:
861 */
862 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :