Code

fix by dvlierop2 for snapping bugs 1579556 and 1579587
[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  *   MenTaLguY <mental@rydia.net>
11  *
12  * The original dynadraw code:
13  *   Paul Haeberli <paul@sgi.com>
14  *
15  * Copyright (C) 1998 The Free Software Foundation
16  * Copyright (C) 1999-2005 authors
17  * Copyright (C) 2001-2002 Ximian, Inc.
18  * Copyright (C) 2005-2006 bulia byak
19  * Copyright (C) 2006 MenTaLguY
20  *
21  * Released under GNU GPL, read the file 'COPYING' for more information
22  */
24 #define noDYNA_DRAW_VERBOSE
26 #include "config.h"
28 #include <gtk/gtk.h>
29 #include <gdk/gdkkeysyms.h>
30 #include <glibmm/i18n.h>
32 #include "svg/svg.h"
33 #include "display/canvas-bpath.h"
34 #include "display/bezier-utils.h"
36 #include <glib/gmem.h>
37 #include "macros.h"
38 #include "document.h"
39 #include "selection.h"
40 #include "desktop.h"
41 #include "desktop-events.h"
42 #include "desktop-handles.h"
43 #include "desktop-affine.h"
44 #include "desktop-style.h"
45 #include "message-context.h"
46 #include "pixmaps/cursor-calligraphy.xpm"
47 #include "dyna-draw-context.h"
48 #include "libnr/n-art-bpath.h"
49 #include "libnr/nr-path.h"
50 #include "xml/repr.h"
51 #include "context-fns.h"
52 #include "sp-item.h"
53 #include "inkscape.h"
54 #include "color.h"
56 #define DDC_RED_RGBA 0xff0000ff
58 #define SAMPLE_TIMEOUT 10
59 #define TOLERANCE_LINE 1.0
60 #define TOLERANCE_CALLIGRAPHIC 3.0
62 #define DYNA_EPSILON 0.5e-6
63 #define DYNA_EPSILON_START 0.5e-2
64 #define DYNA_VEL_START 1e-5
66 #define DYNA_MIN_WIDTH 1.0e-6
68 #define DRAG_MIN 0.0
69 #define DRAG_DEFAULT 1.0
70 #define DRAG_MAX 1.0
72 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
73 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
74 static void sp_dyna_draw_context_dispose(GObject *object);
76 static void sp_dyna_draw_context_setup(SPEventContext *ec);
77 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
78 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
80 static void clear_current(SPDynaDrawContext *dc);
81 static void set_to_accumulated(SPDynaDrawContext *dc);
82 static void add_cap(SPCurve *curve, NR::Point const &pre, NR::Point const &from, NR::Point const &to, NR::Point const &post, double rounding);
83 static void accumulate_calligraphic(SPDynaDrawContext *dc);
85 static void fit_and_split(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 void draw_temporary_box(SPDynaDrawContext *dc);
93 static SPEventContextClass *parent_class;
95 GtkType
96 sp_dyna_draw_context_get_type(void)
97 {
98     static GType type = 0;
99     if (!type) {
100         GTypeInfo info = {
101             sizeof(SPDynaDrawContextClass),
102             NULL, NULL,
103             (GClassInitFunc) sp_dyna_draw_context_class_init,
104             NULL, NULL,
105             sizeof(SPDynaDrawContext),
106             4,
107             (GInstanceInitFunc) sp_dyna_draw_context_init,
108             NULL,   /* value_table */
109         };
110         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
111     }
112     return type;
115 static void
116 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
118     GObjectClass *object_class = (GObjectClass *) klass;
119     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
121     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
123     object_class->dispose = sp_dyna_draw_context_dispose;
125     event_context_class->setup = sp_dyna_draw_context_setup;
126     event_context_class->set = sp_dyna_draw_context_set;
127     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
130 static void
131 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
133     SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
135     event_context->cursor_shape = cursor_calligraphy_xpm;
136     event_context->hot_x = 4;
137     event_context->hot_y = 4;
139     ddc->accumulated = NULL;
140     ddc->segments = NULL;
141     ddc->currentcurve = NULL;
142     ddc->currentshape = NULL;
143     ddc->npoints = 0;
144     ddc->cal1 = NULL;
145     ddc->cal2 = NULL;
146     ddc->repr = NULL;
148     /* DynaDraw values */
149     ddc->cur = NR::Point(0,0);
150     ddc->last = NR::Point(0,0);
151     ddc->vel = NR::Point(0,0);
152     ddc->vel_max = 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->dragging = FALSE;
160     ddc->mass = 0.3;
161     ddc->drag = DRAG_DEFAULT;
162     ddc->angle = 30.0;
163     ddc->width = 0.2;
165     ddc->vel_thin = 0.1;
166     ddc->flatness = 0.9;
167     ddc->cap_rounding = 0.0;
169     ddc->abs_width = false;
170     ddc->keep_selected = true;
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     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
218     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
219     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
220     /* fixme: Cannot we cascade it to root more clearly? */
221     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
223     sp_event_context_read(ec, "mass");
224     sp_event_context_read(ec, "wiggle");
225     sp_event_context_read(ec, "angle");
226     sp_event_context_read(ec, "width");
227     sp_event_context_read(ec, "thinning");
228     sp_event_context_read(ec, "tremor");
229     sp_event_context_read(ec, "flatness");
230     sp_event_context_read(ec, "usepressure");
231     sp_event_context_read(ec, "usetilt");
232     sp_event_context_read(ec, "abs_width");
233     sp_event_context_read(ec, "keep_selected");
234     sp_event_context_read(ec, "cap_rounding");
236     ddc->is_drawing = false;
238     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
241 static void
242 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
244     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
246     if (!strcmp(key, "mass")) {
247         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
248         ddc->mass = CLAMP(dval, -1000.0, 1000.0);
249     } else if (!strcmp(key, "wiggle")) {
250         double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
251         ddc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
252     } else if (!strcmp(key, "angle")) {
253         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
254         ddc->angle = CLAMP (dval, -90, 90);
255     } else if (!strcmp(key, "width")) {
256         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
257         ddc->width = CLAMP(dval, -1000.0, 1000.0);
258     } else if (!strcmp(key, "thinning")) {
259         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
260         ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
261     } else if (!strcmp(key, "tremor")) {
262         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
263         ddc->tremor = CLAMP(dval, 0.0, 1.0);
264     } else if (!strcmp(key, "flatness")) {
265         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
266         ddc->flatness = CLAMP(dval, 0, 1.0);
267     } else if (!strcmp(key, "usepressure")) {
268         ddc->usepressure = (val && strcmp(val, "0"));
269     } else if (!strcmp(key, "usetilt")) {
270         ddc->usetilt = (val && strcmp(val, "0"));
271     } else if (!strcmp(key, "abs_width")) {
272         ddc->abs_width = (val && strcmp(val, "0"));
273     } else if (!strcmp(key, "keep_selected")) {
274         ddc->keep_selected = (val && strcmp(val, "0"));
275     } else if (!strcmp(key, "cap_rounding")) {
276         ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
277     }
279     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
282 static double
283 flerp(double f0, double f1, double p)
285     return f0 + ( f1 - f0 ) * p;
288 /* Get normalized point */
289 static NR::Point
290 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
292     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
293     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
294     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
297 /* Get view point */
298 static NR::Point
299 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
301     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
302     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
303     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
306 static void
307 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
309     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
310     dc->vel = NR::Point(0,0);
311     dc->vel_max = 0;
312     dc->acc = NR::Point(0,0);
313     dc->ang = NR::Point(0,0);
314     dc->del = NR::Point(0,0);
317 static void
318 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
320     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
321         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
322     else
323         dc->pressure = DDC_DEFAULT_PRESSURE;
325     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
326         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
327     else
328         dc->xtilt = DDC_DEFAULT_TILT;
330     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
331         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
332     else
333         dc->ytilt = DDC_DEFAULT_TILT;
337 static gboolean
338 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
340     NR::Point n = sp_dyna_draw_get_npoint(dc, p);
342     /* Calculate mass and drag */
343     double const mass = flerp(1.0, 160.0, dc->mass);
344     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
346     /* Calculate force and acceleration */
347     NR::Point force = n - dc->cur;
348     if ( NR::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && NR::L2(force) < DYNA_EPSILON_START)) {
349         return FALSE;
350     }
352     dc->acc = force / mass;
354     /* Calculate new velocity */
355     dc->vel += dc->acc;
357     if (NR::L2(dc->vel) > dc->vel_max)
358         dc->vel_max = NR::L2(dc->vel);
360     /* Calculate angle of drawing tool */
362     double a1;
363     if (dc->usetilt) {
364         // 1a. calculate nib angle from input device tilt:
365         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
367         if (length > 0) {
368             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
369             a1 = atan2(ang1);
370         }
371         else
372             a1 = 0.0;
373     }
374     else {
375         // 1b. fixed dc->angle (absolutely flat nib):
376         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
377         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
378         a1 = atan2(ang1);
379     }
381     // 2. perpendicular to dc->vel (absolutely non-flat nib):
382     gdouble const mag_vel = NR::L2(dc->vel);
383     if ( mag_vel < DYNA_EPSILON ) {
384         return FALSE;
385     }
386     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
388     // 3. Average them using flatness parameter:
389     // calculate angles
390     double a2 = atan2(ang2);
391     // flip a2 to force it to be in the same half-circle as a1
392     bool flipped = false;
393     if (fabs (a2-a1) > 0.5*M_PI) {
394         a2 += M_PI;
395         flipped = true;
396     }
397     // normalize a2
398     if (a2 > M_PI)
399         a2 -= 2*M_PI;
400     if (a2 < -M_PI)
401         a2 += 2*M_PI;
402     // find the flatness-weighted bisector angle, unflip if a2 was flipped
403     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
404     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
406     double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
408     if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
409         return FALSE;
410     }
412     // convert to point
413     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
415 //    g_print ("force %g  acc %g  vel_max %g  vel %g  a1 %g  a2 %g  new_ang %g\n", NR::L2(force), NR::L2(dc->acc), dc->vel_max, NR::L2(dc->vel), a1, a2, new_ang);
417     /* Apply drag */
418     dc->vel *= 1.0 - drag;
420     /* Update position */
421     dc->last = dc->cur;
422     dc->cur += dc->vel;
424     return TRUE;
427 static void
428 sp_dyna_draw_brush(SPDynaDrawContext *dc)
430     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
432     // How much velocity thins strokestyle
433     double vel_thin = flerp (0, 160, dc->vel_thin);
435     // Influence of pressure on thickness
436     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
438     double width = ( pressure_thick - vel_thin * NR::L2(dc->vel) ) * dc->width;
440     double tremble_left = 0, tremble_right = 0;
441     if (dc->tremor > 0) {
442         // obtain two normally distributed random variables, using polar Box-Muller transform
443         double x1, x2, w, y1, y2;
444         do {
445             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
446             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
447             w = x1 * x1 + x2 * x2;
448         } while ( w >= 1.0 );
449         w = sqrt( (-2.0 * log( w ) ) / w );
450         y1 = x1 * w;
451         y2 = x2 * w;
453         // deflect both left and right edges randomly and independently, so that:
454         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
455         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
456         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
457         // comparatively smooth and slow ones excessively jittery
458         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
459         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
460     }
462     if ( width < 0.02 * dc->width ) {
463         width = 0.02 * dc->width;
464     }
466     double dezoomify_factor = 0.05 * 1000;
467     if (!dc->abs_width) {
468         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
469     }
471     NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
472     NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
474     NR::Point abs_middle = sp_dyna_draw_get_vpoint(dc, dc->cur);
476     dc->point1[dc->npoints] = abs_middle + del_left;
477     dc->point2[dc->npoints] = abs_middle - del_right;
479     dc->del = 0.5*(del_left + del_right);
481     dc->npoints++;
484 void
485 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
487     desktop->setToolboxAdjustmentValue (id, value);
490 static void
491 calligraphic_cancel(SPDynaDrawContext *dc)
493     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
494     dc->dragging = FALSE;
495     dc->is_drawing = false;
496     sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
497             /* Remove all temporary line segments */
498             while (dc->segments) {
499                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
500                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
501             }
502             /* reset accumulated curve */
503             sp_curve_reset(dc->accumulated);
504             clear_current(dc);
505             if (dc->repr) {
506                 dc->repr = NULL;
507             }
511 gint
512 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
513                                   GdkEvent *event)
515     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
516     SPDesktop *desktop = event_context->desktop;
518     gint ret = FALSE;
520     switch (event->type) {
521     case GDK_BUTTON_PRESS:
522         if ( event->button.button == 1 ) {
524             SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
526             if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
527                 return TRUE;
528             }
530             NR::Point const button_w(event->button.x,
531                                      event->button.y);
532             NR::Point const button_dt(desktop->w2d(button_w));
533             sp_dyna_draw_reset(dc, button_dt);
534             sp_dyna_draw_extinput(dc, event);
535             sp_dyna_draw_apply(dc, button_dt);
536             sp_curve_reset(dc->accumulated);
537             if (dc->repr) {
538                 dc->repr = NULL;
539             }
541             /* initialize first point */
542             dc->npoints = 0;
544             sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
545                                 ( GDK_KEY_PRESS_MASK |
546                                   GDK_BUTTON_RELEASE_MASK |
547                                   GDK_POINTER_MOTION_MASK |
548                                   GDK_BUTTON_PRESS_MASK ),
549                                 NULL,
550                                 event->button.time);
552             ret = TRUE;
554             dc->is_drawing = true;
555         }
556         break;
557     case GDK_MOTION_NOTIFY:
558         if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
559             dc->dragging = TRUE;
561             NR::Point const motion_w(event->motion.x,
562                                      event->motion.y);
563             NR::Point const motion_dt(desktop->w2d(motion_w));
565             sp_dyna_draw_extinput(dc, event);
566             if (!sp_dyna_draw_apply(dc, motion_dt)) {
567                 ret = TRUE;
568                 break;
569             }
571             if ( dc->cur != dc->last ) {
572                 sp_dyna_draw_brush(dc);
573                 g_assert( dc->npoints > 0 );
574                 fit_and_split(dc, FALSE);
575             }
576             ret = TRUE;
577         }
578         break;
580     case GDK_BUTTON_RELEASE:
581         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
582         dc->is_drawing = false;
584         if ( dc->dragging && event->button.button == 1 ) {
585             dc->dragging = FALSE;
587             NR::Point const motion_w(event->button.x, event->button.y);
588             NR::Point const motion_dt(desktop->w2d(motion_w));
589             sp_dyna_draw_apply(dc, motion_dt);
591             /* Remove all temporary line segments */
592             while (dc->segments) {
593                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
594                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
595             }
596             /* Create object */
597             fit_and_split(dc, TRUE);
598             accumulate_calligraphic(dc);
599             set_to_accumulated(dc); /* temporal implementation */
600             /* reset accumulated curve */
601             sp_curve_reset(dc->accumulated);
602             clear_current(dc);
603             if (dc->repr) {
604                 dc->repr = NULL;
605             }
606             ret = TRUE;
607         }
608         break;
609     case GDK_KEY_PRESS:
610         switch (get_group0_keyval (&event->key)) {
611         case GDK_Up:
612         case GDK_KP_Up:
613             if (!MOD__CTRL_ONLY) {
614                 dc->angle += 5.0;
615                 if (dc->angle > 90.0)
616                     dc->angle = 90.0;
617                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
618                 ret = TRUE;
619             }
620             break;
621         case GDK_Down:
622         case GDK_KP_Down:
623             if (!MOD__CTRL_ONLY) {
624                 dc->angle -= 5.0;
625                 if (dc->angle < -90.0)
626                     dc->angle = -90.0;
627                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
628                 ret = TRUE;
629             }
630             break;
631         case GDK_Right:
632         case GDK_KP_Right:
633             if (!MOD__CTRL_ONLY) {
634                 dc->width += 0.01;
635                 if (dc->width > 1.0)
636                     dc->width = 1.0;
637                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
638                 ret = TRUE;
639             }
640             break;
641         case GDK_Left:
642         case GDK_KP_Left:
643             if (!MOD__CTRL_ONLY) {
644                 dc->width -= 0.01;
645                 if (dc->width < 0.01)
646                     dc->width = 0.01;
647                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
648                 ret = TRUE;
649             }
650             break;
651         case GDK_x:
652         case GDK_X:
653             if (MOD__ALT_ONLY) {
654                 desktop->setToolboxFocusTo ("altx-calligraphy");
655                 ret = TRUE;
656             }
657             break;
658         case GDK_Escape:
659             if (dc->is_drawing) {
660                 // if drawing, cancel, otherwise pass it up for deselecting
661                 calligraphic_cancel (dc);
662                 ret = TRUE;
663             }
664             break;
665         case GDK_z:
666         case GDK_Z:
667             if (MOD__CTRL_ONLY && dc->is_drawing) {
668                 // if drawing, cancel, otherwise pass it up for undo
669                 calligraphic_cancel (dc);
670                 ret = TRUE;
671             }
672             break;
673         default:
674             break;
675         }
676     default:
677         break;
678     }
680     if (!ret) {
681         if (((SPEventContextClass *) parent_class)->root_handler) {
682             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
683         }
684     }
686     return ret;
690 static void
691 clear_current(SPDynaDrawContext *dc)
693     /* reset bpath */
694     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
695     /* reset curve */
696     sp_curve_reset(dc->currentcurve);
697     sp_curve_reset(dc->cal1);
698     sp_curve_reset(dc->cal2);
699     /* reset points */
700     dc->npoints = 0;
703 static void
704 set_to_accumulated(SPDynaDrawContext *dc)
706     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
708     if (!sp_curve_empty(dc->accumulated)) {
709         NArtBpath *abp;
710         gchar *str;
712         if (!dc->repr) {
713             /* Create object */
714             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
715             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
717             /* Set style */
718             sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
720             dc->repr = repr;
722             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
723             Inkscape::GC::release(dc->repr);
724             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
725             item->updateRepr();
726             if (dc->keep_selected) {
727                 sp_desktop_selection(desktop)->set(dc->repr);
728             } else {
729                 sp_desktop_selection(desktop)->clear();
730             }
731         }
732         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
733         str = sp_svg_write_path(abp);
734         g_assert( str != NULL );
735         g_free(abp);
736         dc->repr->setAttribute("d", str);
737         g_free(str);
738     } else {
739         if (dc->repr) {
740             sp_repr_unparent(dc->repr);
741         }
742         dc->repr = NULL;
743     }
745     sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC, 
746                      _("Create calligraphic stroke"));
749 static void
750 add_cap(SPCurve *curve,
751         NR::Point const &pre, NR::Point const &from,
752         NR::Point const &to, NR::Point const &post,
753         double rounding)
755     NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
756     double mag = NR::L2(vel);
758     NR::Point v_in = from - pre;
759     double mag_in = NR::L2(v_in);
760     if ( mag_in > DYNA_EPSILON ) {
761         v_in = mag * v_in / mag_in;
762     } else {
763         v_in = NR::Point(0, 0);
764     }
766     NR::Point v_out = to - post;
767     double mag_out = NR::L2(v_out);
768     if ( mag_out > DYNA_EPSILON ) {
769         v_out = mag * v_out / mag_out;
770     } else {
771         v_out = NR::Point(0, 0);
772     }
774     if ( NR::L2(v_in) > DYNA_EPSILON || NR::L2(v_out) > DYNA_EPSILON ) {
775         sp_curve_curveto(curve, from + v_in, to + v_out, to);
776     }
779 static void
780 accumulate_calligraphic(SPDynaDrawContext *dc)
782     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
783         sp_curve_reset(dc->accumulated); /*  Is this required ?? */
784         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
786         g_assert(dc->cal1->end > 1);
787         g_assert(rev_cal2->end > 1);
788         g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
789         g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
790         g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
791         g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
792         g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
793         g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
795         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
797         add_cap(dc->accumulated, SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->c(2), SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->c(3), SP_CURVE_SEGMENT(rev_cal2, 0)->c(3), SP_CURVE_SEGMENT(rev_cal2, 1)->c(1), dc->cap_rounding);
799         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
801         add_cap(dc->accumulated, SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->c(2), SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->c(3), SP_CURVE_SEGMENT(dc->cal1, 0)->c(3), SP_CURVE_SEGMENT(dc->cal1, 1)->c(1), dc->cap_rounding);
803         sp_curve_closepath(dc->accumulated);
805         sp_curve_unref(rev_cal2);
807         sp_curve_reset(dc->cal1);
808         sp_curve_reset(dc->cal2);
809     }
812 static double square(double const x)
814     return x * x;
817 static void
818 fit_and_split(SPDynaDrawContext *dc, gboolean release)
820     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
822 #ifdef DYNA_DRAW_VERBOSE
823     g_print("[F&S:R=%c]", release?'T':'F');
824 #endif
826     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
827         return; // just clicked
829     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
830 #define BEZIER_SIZE       4
831 #define BEZIER_MAX_BEZIERS  8
832 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
834 #ifdef DYNA_DRAW_VERBOSE
835         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
836                 dc->npoints, release ? "TRUE" : "FALSE");
837 #endif
839         /* Current calligraphic */
840         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
841             /* dc->npoints > 0 */
842             /* g_print("calligraphics(1|2) reset\n"); */
843             sp_curve_reset(dc->cal1);
844             sp_curve_reset(dc->cal2);
846             sp_curve_moveto(dc->cal1, dc->point1[0]);
847             sp_curve_moveto(dc->cal2, dc->point2[0]);
848         }
850         NR::Point b1[BEZIER_MAX_LENGTH];
851         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
852                                                tolerance_sq, BEZIER_MAX_BEZIERS);
853         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
855         NR::Point b2[BEZIER_MAX_LENGTH];
856         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
857                                                tolerance_sq, BEZIER_MAX_BEZIERS);
858         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
860         if ( nb1 != -1 && nb2 != -1 ) {
861             /* Fit and draw and reset state */
862 #ifdef DYNA_DRAW_VERBOSE
863             g_print("nb1:%d nb2:%d\n", nb1, nb2);
864 #endif
865             /* CanvasShape */
866             if (! release) {
867                 sp_curve_reset(dc->currentcurve);
868                 sp_curve_moveto(dc->currentcurve, b1[0]);
869                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
870                     sp_curve_curveto(dc->currentcurve, bp1[1],
871                                      bp1[2], bp1[3]);
872                 }
873                 sp_curve_lineto(dc->currentcurve,
874                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
875                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
876                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
877                 }
878                 // FIXME: dc->segments is always NULL at this point??
879                 if (!dc->segments) { // first segment
880                     add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
881                 }
882                 sp_curve_closepath(dc->currentcurve);
883                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
884             }
886             /* Current calligraphic */
887             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
888                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
889             }
890             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
891                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
892             }
893         } else {
894             /* fixme: ??? */
895 #ifdef DYNA_DRAW_VERBOSE
896             g_print("[fit_and_split] failed to fit-cubic.\n");
897 #endif
898             draw_temporary_box(dc);
900             for (gint i = 1; i < dc->npoints; i++) {
901                 sp_curve_lineto(dc->cal1, dc->point1[i]);
902             }
903             for (gint i = 1; i < dc->npoints; i++) {
904                 sp_curve_lineto(dc->cal2, dc->point2[i]);
905             }
906         }
908         /* Fit and draw and copy last point */
909 #ifdef DYNA_DRAW_VERBOSE
910         g_print("[%d]Yup\n", dc->npoints);
911 #endif
912         if (!release) {
913             g_assert(!sp_curve_empty(dc->currentcurve));
915             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
916                                                    SP_TYPE_CANVAS_BPATH,
917                                                    NULL);
918             SPCurve *curve = sp_curve_copy(dc->currentcurve);
919             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
920             sp_curve_unref(curve);
922             guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
923             //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
924             double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
925             double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
926             //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
927             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
928             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
929             //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);
930             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
931             /* fixme: Cannot we cascade it to root more clearly? */
932             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
934             dc->segments = g_slist_prepend(dc->segments, cbp);
935         }
937         dc->point1[0] = dc->point1[dc->npoints - 1];
938         dc->point2[0] = dc->point2[dc->npoints - 1];
939         dc->npoints = 1;
940     } else {
941         draw_temporary_box(dc);
942     }
945 static void
946 draw_temporary_box(SPDynaDrawContext *dc)
948     sp_curve_reset(dc->currentcurve);
950     sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
951     for (gint i = dc->npoints-2; i >= 0; i--) {
952         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
953     }
954     for (gint i = 0; i < dc->npoints; i++) {
955         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
956     }
957     if (dc->npoints >= 2) {
958         add_cap(dc->currentcurve, dc->point2[dc->npoints-2], dc->point2[dc->npoints-1], dc->point1[dc->npoints-1], dc->point1[dc->npoints-2], dc->cap_rounding);
959     }
961     sp_curve_closepath(dc->currentcurve);
962     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
965 /*
966   Local Variables:
967   mode:c++
968   c-file-style:"stroustrup"
969   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
970   indent-tabs-mode:nil
971   fill-column:99
972   End:
973 */
974 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :