Code

dyna-draw-context and eraser-context: replace check for empty path with 2geomified...
[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-2007 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>
31 #include <string>
32 #include <cstring>
33 #include <numeric>
35 #include "svg/svg.h"
36 #include "display/canvas-bpath.h"
37 #include "display/bezier-utils.h"
38 #include "display/curve.h"
39 #include <glib/gmem.h>
40 #include "macros.h"
41 #include "document.h"
42 #include "selection.h"
43 #include "desktop.h"
44 #include "desktop-events.h"
45 #include "desktop-handles.h"
46 #include "desktop-affine.h"
47 #include "desktop-style.h"
48 #include "message-context.h"
49 #include "prefs-utils.h"
50 #include "pixmaps/cursor-calligraphy.xpm"
51 #include "libnr/n-art-bpath.h"
52 #include "libnr/nr-path.h"
53 #include "libnr/nr-matrix-ops.h"
54 #include "libnr/nr-scale-translate-ops.h"
55 #include "libnr/nr-convert2geom.h"
56 #include "xml/repr.h"
57 #include "context-fns.h"
58 #include "sp-item.h"
59 #include "inkscape.h"
60 #include "color.h"
61 #include "splivarot.h"
62 #include "sp-item-group.h"
63 #include "sp-shape.h"
64 #include "sp-path.h"
65 #include "sp-text.h"
66 #include "display/canvas-bpath.h"
67 #include "display/canvas-arena.h"
68 #include "livarot/Shape.h"
69 #include <2geom/isnan.h>
70 #include <2geom/pathvector.h>
72 #include "dyna-draw-context.h"
74 #define DDC_RED_RGBA 0xff0000ff
76 #define TOLERANCE_CALLIGRAPHIC 0.1
78 #define DYNA_EPSILON 0.5e-6
79 #define DYNA_EPSILON_START 0.5e-2
80 #define DYNA_VEL_START 1e-5
82 #define DYNA_MIN_WIDTH 1.0e-6
84 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
85 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
86 static void sp_dyna_draw_context_dispose(GObject *object);
88 static void sp_dyna_draw_context_setup(SPEventContext *ec);
89 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
90 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
92 static void clear_current(SPDynaDrawContext *dc);
93 static void set_to_accumulated(SPDynaDrawContext *dc, bool unionize);
94 static void add_cap(SPCurve *curve, NR::Point const &from, NR::Point const &to, double rounding);
95 static bool accumulate_calligraphic(SPDynaDrawContext *dc);
97 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
99 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
100 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
101 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
102 static void draw_temporary_box(SPDynaDrawContext *dc);
105 static SPEventContextClass *dd_parent_class = 0;
107 GType sp_dyna_draw_context_get_type(void)
109     static GType type = 0;
110     if (!type) {
111         GTypeInfo info = {
112             sizeof(SPDynaDrawContextClass),
113             0, // base_init
114             0, // base_finalize
115             (GClassInitFunc)sp_dyna_draw_context_class_init,
116             0, // class_finalize
117             0, // class_data
118             sizeof(SPDynaDrawContext),
119             0, // n_preallocs
120             (GInstanceInitFunc)sp_dyna_draw_context_init,
121             0 // value_table
122         };
123         type = g_type_register_static(SP_TYPE_COMMON_CONTEXT, "SPDynaDrawContext", &info, static_cast<GTypeFlags>(0));
124     }
125     return type;
128 static void
129 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
131     GObjectClass *object_class = (GObjectClass *) klass;
132     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
134     dd_parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
136     object_class->dispose = sp_dyna_draw_context_dispose;
138     event_context_class->setup = sp_dyna_draw_context_setup;
139     event_context_class->set = sp_dyna_draw_context_set;
140     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
143 static void
144 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
146     ddc->cursor_shape = cursor_calligraphy_xpm;
147     ddc->hot_x = 4;
148     ddc->hot_y = 4;
150     ddc->vel_thin = 0.1;
151     ddc->flatness = 0.9;
152     ddc->cap_rounding = 0.0;
154     ddc->abs_width = false;
155     ddc->keep_selected = true;
157     ddc->hatch_spacing = 0;
158     ddc->hatch_spacing_step = 0;
159     new (&ddc->hatch_pointer_past) std::list<double>();
160     new (&ddc->hatch_nearest_past) std::list<double>();
161     ddc->hatch_last_nearest = NR::Point(0,0);
162     ddc->hatch_last_pointer = NR::Point(0,0);
163     ddc->hatch_vector_accumulated = NR::Point(0,0);
164     ddc->hatch_escaped = false;
165     ddc->hatch_area = NULL;
166     ddc->hatch_item = NULL;
167     ddc->hatch_livarot_path = NULL;
169     ddc->trace_bg = false;
172 static void
173 sp_dyna_draw_context_dispose(GObject *object)
175     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
177     if (ddc->hatch_area) {
178         gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
179         ddc->hatch_area = NULL;
180     }
183     G_OBJECT_CLASS(dd_parent_class)->dispose(object);
185     ddc->hatch_pointer_past.~list();
186     ddc->hatch_nearest_past.~list();
189 static void
190 sp_dyna_draw_context_setup(SPEventContext *ec)
192     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
194     if (((SPEventContextClass *) dd_parent_class)->setup)
195         ((SPEventContextClass *) dd_parent_class)->setup(ec);
197     ddc->accumulated = new SPCurve(32);
198     ddc->currentcurve = new SPCurve(4);
200     ddc->cal1 = new SPCurve(32);
201     ddc->cal2 = new SPCurve(32);
203     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
204     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
205     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
206     /* fixme: Cannot we cascade it to root more clearly? */
207     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
209     {
210         /* TODO: this can be done either with an arcto, and should maybe also be put in a general file (other tools use this as well) */
211         SPCurve *c = new SPCurve();
212         const double C1 = 0.552;
213         c->moveto(-1,0);
214         c->curveto(-1, C1, -C1, 1, 0, 1 );
215         c->curveto(C1, 1, 1, C1, 1, 0 );
216         c->curveto(1, -C1, C1, -1, 0, -1 );
217         c->curveto(-C1, -1, -1, -C1, -1, 0 );
218         c->closepath();
219         ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
220         c->unref();
221         sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
222         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
223         sp_canvas_item_hide(ddc->hatch_area);
224     }
226     sp_event_context_read(ec, "mass");
227     sp_event_context_read(ec, "wiggle");
228     sp_event_context_read(ec, "angle");
229     sp_event_context_read(ec, "width");
230     sp_event_context_read(ec, "thinning");
231     sp_event_context_read(ec, "tremor");
232     sp_event_context_read(ec, "flatness");
233     sp_event_context_read(ec, "tracebackground");
234     sp_event_context_read(ec, "usepressure");
235     sp_event_context_read(ec, "usetilt");
236     sp_event_context_read(ec, "abs_width");
237     sp_event_context_read(ec, "keep_selected");
238     sp_event_context_read(ec, "cap_rounding");
240     ddc->is_drawing = false;
242     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
244     if (prefs_get_int_attribute("tools.calligraphic", "selcue", 0) != 0) {
245         ec->enableSelectionCue();
246     }
249 static void
250 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
252     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
254     if (!strcmp(key, "tracebackground")) {
255         ddc->trace_bg = (val && strcmp(val, "0"));
256     } else if (!strcmp(key, "keep_selected")) {
257         ddc->keep_selected = (val && strcmp(val, "0"));
258     } else {
259         //pass on up to parent class to handle common attributes.
260         if ( dd_parent_class->set ) {
261             dd_parent_class->set(ec, key, val);
262         }
263     }
265     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
268 static double
269 flerp(double f0, double f1, double p)
271     return f0 + ( f1 - f0 ) * p;
274 /* Get normalized point */
275 static NR::Point
276 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
278     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
279     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
280     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
283 /* Get view point */
284 static NR::Point
285 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
287     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
288     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
289     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
292 static void
293 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
295     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
296     dc->vel = NR::Point(0,0);
297     dc->vel_max = 0;
298     dc->acc = NR::Point(0,0);
299     dc->ang = NR::Point(0,0);
300     dc->del = NR::Point(0,0);
303 static void
304 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
306     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
307         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
308     else
309         dc->pressure = DDC_DEFAULT_PRESSURE;
311     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
312         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
313     else
314         dc->xtilt = DDC_DEFAULT_TILT;
316     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
317         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
318     else
319         dc->ytilt = DDC_DEFAULT_TILT;
323 static gboolean
324 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
326     NR::Point n = sp_dyna_draw_get_npoint(dc, p);
328     /* Calculate mass and drag */
329     double const mass = flerp(1.0, 160.0, dc->mass);
330     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
332     /* Calculate force and acceleration */
333     NR::Point force = n - dc->cur;
335     // If force is below the absolute threshold DYNA_EPSILON,
336     // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
337     // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
338     // discard this move. 
339     // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
340     // especially bothersome at the start of the stroke where we don't yet have the inertia to
341     // smooth them out.
342     if ( NR::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && NR::L2(force) < DYNA_EPSILON_START)) {
343         return FALSE;
344     }
346     dc->acc = force / mass;
348     /* Calculate new velocity */
349     dc->vel += dc->acc;
351     if (NR::L2(dc->vel) > dc->vel_max)
352         dc->vel_max = NR::L2(dc->vel);
354     /* Calculate angle of drawing tool */
356     double a1;
357     if (dc->usetilt) {
358         // 1a. calculate nib angle from input device tilt:
359         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
361         if (length > 0) {
362             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
363             a1 = atan2(ang1);
364         }
365         else
366             a1 = 0.0;
367     }
368     else {
369         // 1b. fixed dc->angle (absolutely flat nib):
370         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
371         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
372         a1 = atan2(ang1);
373     }
375     // 2. perpendicular to dc->vel (absolutely non-flat nib):
376     gdouble const mag_vel = NR::L2(dc->vel);
377     if ( mag_vel < DYNA_EPSILON ) {
378         return FALSE;
379     }
380     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
382     // 3. Average them using flatness parameter:
383     // calculate angles
384     double a2 = atan2(ang2);
385     // flip a2 to force it to be in the same half-circle as a1
386     bool flipped = false;
387     if (fabs (a2-a1) > 0.5*M_PI) {
388         a2 += M_PI;
389         flipped = true;
390     }
391     // normalize a2
392     if (a2 > M_PI)
393         a2 -= 2*M_PI;
394     if (a2 < -M_PI)
395         a2 += 2*M_PI;
396     // find the flatness-weighted bisector angle, unflip if a2 was flipped
397     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
398     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
400     // Try to detect a sudden flip when the new angle differs too much from the previous for the
401     // current velocity; in that case discard this move
402     double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
403     if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
404         return FALSE;
405     }
407     // convert to point
408     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
410 //    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);
412     /* Apply drag */
413     dc->vel *= 1.0 - drag;
415     /* Update position */
416     dc->last = dc->cur;
417     dc->cur += dc->vel;
419     return TRUE;
422 static void
423 sp_dyna_draw_brush(SPDynaDrawContext *dc)
425     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
427     // How much velocity thins strokestyle
428     double vel_thin = flerp (0, 160, dc->vel_thin);
430     // Influence of pressure on thickness
431     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
433     // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
434     // drag)
435     NR::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
436     NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush); 
438     double trace_thick = 1;
439     if (dc->trace_bg) {
440         // pick single pixel
441         NRPixBlock pb;
442         int x = (int) floor(brush_w[NR::X]);
443         int y = (int) floor(brush_w[NR::Y]);
444         nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
445         sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
446         const unsigned char *s = NR_PIXBLOCK_PX(&pb);
447         double R = s[0] / 255.0;
448         double G = s[1] / 255.0;
449         double B = s[2] / 255.0;
450         double A = s[3] / 255.0;
451         double max = MAX (MAX (R, G), B);
452         double min = MIN (MIN (R, G), B);
453         double L = A * (max + min)/2 + (1 - A); // blend with white bg
454         trace_thick = 1 - L;
455         //g_print ("L %g thick %g\n", L, trace_thick);
456     }
458     double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
460     double tremble_left = 0, tremble_right = 0;
461     if (dc->tremor > 0) {
462         // obtain two normally distributed random variables, using polar Box-Muller transform
463         double x1, x2, w, y1, y2;
464         do {
465             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
466             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
467             w = x1 * x1 + x2 * x2;
468         } while ( w >= 1.0 );
469         w = sqrt( (-2.0 * log( w ) ) / w );
470         y1 = x1 * w;
471         y2 = x2 * w;
473         // deflect both left and right edges randomly and independently, so that:
474         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
475         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
476         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
477         // comparatively smooth and slow ones excessively jittery
478         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
479         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
480     }
482     if ( width < 0.02 * dc->width ) {
483         width = 0.02 * dc->width;
484     }
486     double dezoomify_factor = 0.05 * 1000;
487     if (!dc->abs_width) {
488         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
489     }
491     NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
492     NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
494     dc->point1[dc->npoints] = brush + del_left;
495     dc->point2[dc->npoints] = brush - del_right;
497     dc->del = 0.5*(del_left + del_right);
499     dc->npoints++;
502 void
503 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
505     desktop->setToolboxAdjustmentValue (id, value);
508 static void
509 calligraphic_cancel(SPDynaDrawContext *dc)
511     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
512     dc->dragging = FALSE;
513     dc->is_drawing = false;
514     sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
515             /* Remove all temporary line segments */
516             while (dc->segments) {
517                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
518                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
519             }
520             /* reset accumulated curve */
521             dc->accumulated->reset();
522             clear_current(dc);
523             if (dc->repr) {
524                 dc->repr = NULL;
525             }
529 gint
530 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
531                                   GdkEvent *event)
533     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
534     SPDesktop *desktop = event_context->desktop;
536     gint ret = FALSE;
538     switch (event->type) {
539         case GDK_BUTTON_PRESS:
540             if (event->button.button == 1 && !event_context->space_panning) {
542                 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
544                 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
545                     return TRUE;
546                 }
548                 NR::Point const button_w(event->button.x,
549                                          event->button.y);
550                 NR::Point const button_dt(desktop->w2d(button_w));
551                 sp_dyna_draw_reset(dc, button_dt);
552                 sp_dyna_draw_extinput(dc, event);
553                 sp_dyna_draw_apply(dc, button_dt);
554                 dc->accumulated->reset();
555                 if (dc->repr) {
556                     dc->repr = NULL;
557                 }
559                 /* initialize first point */
560                 dc->npoints = 0;
562                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
563                                     ( GDK_KEY_PRESS_MASK |
564                                       GDK_BUTTON_RELEASE_MASK |
565                                       GDK_POINTER_MOTION_MASK |
566                                       GDK_BUTTON_PRESS_MASK ),
567                                     NULL,
568                                     event->button.time);
570                 ret = TRUE;
572                 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
573                 dc->is_drawing = true;
574             }
575             break;
576         case GDK_MOTION_NOTIFY:
577         {
578             NR::Point const motion_w(event->motion.x,
579                                      event->motion.y);
580             NR::Point motion_dt(desktop->w2d(motion_w));
581             sp_dyna_draw_extinput(dc, event);
583             dc->_message_context->clear();
585             // for hatching:
586             double hatch_dist = 0;
587             NR::Point hatch_unit_vector(0,0);
588             NR::Point nearest(0,0);
589             NR::Point pointer(0,0);
590             NR::Matrix motion_to_curve(NR::identity());
592             if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
594                 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
595                 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
596                     // One item selected, and it's a path;
597                     // let's try to track it as a guide
599                     if (selected != dc->hatch_item) {
600                         dc->hatch_item = selected;
601                         if (dc->hatch_livarot_path)
602                             delete dc->hatch_livarot_path;
603                         dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
604                         dc->hatch_livarot_path->ConvertWithBackData(0.01);
605                     }
607                     // calculate pointer point in the guide item's coords
608                     motion_to_curve = from_2geom(sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected));
609                     pointer = motion_dt * motion_to_curve;
611                     // calculate the nearest point on the guide path
612                     NR::Maybe<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
613                     nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
616                     // distance from pointer to nearest
617                     hatch_dist = NR::L2(pointer - nearest);
618                     // unit-length vector
619                     hatch_unit_vector = (pointer - nearest)/hatch_dist;
621                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
622                 } else {
623                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
624                 }
625             } 
627             if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
628                 dc->dragging = TRUE;
630                 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
632 #define SPEED_ELEMENTS 12
633 #define SPEED_MIN 0.12
634 #define SPEED_NORMAL 0.65
636                     // speed is the movement of the nearest point along the guide path, divided by
637                     // the movement of the pointer at the same period; it is averaged for the last
638                     // SPEED_ELEMENTS motion events.  Normally, as you track the guide path, speed
639                     // is about 1, i.e. the nearest point on the path is moved by about the same
640                     // distance as the pointer. If the speed starts to decrease, we are losing
641                     // contact with the guide; if it drops below SPEED_MIN, we are on our own and
642                     // not attracted to guide anymore. Most often this happens when you have
643                     // tracked to the end of a guide calligraphic stroke and keep moving
644                     // further. We try to handle this situation gracefully: not stick with the
645                     // guide forever but let go of it smoothly and without sharp jerks (non-zero
646                     // mass recommended; with zero mass, jerks are still quite noticeable).
648                     double speed = 1;
649                     if (NR::L2(dc->hatch_last_nearest) != 0) {
650                         // the distance nearest moved since the last motion event
651                         double nearest_moved = NR::L2(nearest - dc->hatch_last_nearest);
652                         // the distance pointer moved since the last motion event
653                         double pointer_moved = NR::L2(pointer - dc->hatch_last_pointer);
654                         // store them in stacks limited to SPEED_ELEMENTS
655                         dc->hatch_nearest_past.push_front(nearest_moved);
656                         if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
657                             dc->hatch_nearest_past.pop_back();
658                         dc->hatch_pointer_past.push_front(pointer_moved);
659                         if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
660                             dc->hatch_pointer_past.pop_back();
662                         // If the stacks are full,
663                         if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
664                             // calculate the sums of all stored movements
665                             double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
666                             double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
667                             // and divide to get the speed
668                             speed = nearest_sum/pointer_sum;
669                             //g_print ("nearest sum %g  pointer_sum %g  speed %g\n", nearest_sum, pointer_sum, speed);
670                         }
671                     }
673                     if (   dc->hatch_escaped  // already escaped, do not reattach
674                         || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
675                         || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
676                         ) {
677                         // We are NOT attracted to the guide!
679                         //g_print ("\nlast_nearest %g %g   nearest %g %g  pointer %g %g  pos %d %g\n", dc->last_nearest[NR::X], dc->last_nearest[NR::Y], nearest[NR::X], nearest[NR::Y], pointer[NR::X], pointer[NR::Y], position->piece, position->t);
681                         // Remember hatch_escaped so we don't get
682                         // attracted again until the end of this stroke
683                         dc->hatch_escaped = true;
685                     } else {
687                         // Calculate angle cosine of this vector-to-guide and all past vectors
688                         // summed, to detect if we accidentally flipped to the other side of the
689                         // guide
690                         double dot = NR::dot (pointer - nearest, dc->hatch_vector_accumulated);
691                         dot /= NR::L2(pointer - nearest) * NR::L2(dc->hatch_vector_accumulated);
693                         if (dc->hatch_spacing != 0) { // spacing was already set
694                             double target;
695                             if (speed > SPEED_NORMAL) {
696                                 // all ok, strictly obey the spacing
697                                 target = dc->hatch_spacing;
698                             } else {
699                                 // looks like we're starting to lose speed,
700                                 // so _gradually_ let go attraction to prevent jerks
701                                 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;                            
702                             }
703                             if (!IS_NAN(dot) && dot < -0.5) {// flip
704                                 target = -target;
705                             }
707                             // This is the track pointer that we will use instead of the real one
708                             NR::Point new_pointer = nearest + target * hatch_unit_vector;
710                             // some limited feedback: allow persistent pulling to slightly change
711                             // the spacing
712                             dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
714                             // return it to the desktop coords
715                             motion_dt = new_pointer * motion_to_curve.inverse();
717                         } else {
718                             // this is the first motion event, set the dist 
719                             dc->hatch_spacing = hatch_dist;
720                         }
722                         // remember last points
723                         dc->hatch_last_pointer = pointer;
724                         dc->hatch_last_nearest = nearest;
725                         dc->hatch_vector_accumulated += (pointer - nearest);
726                     }
728                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
730                 } else {
731                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
732                 }
734                 if (!sp_dyna_draw_apply(dc, motion_dt)) {
735                     ret = TRUE;
736                     break;
737                 }
739                 if ( dc->cur != dc->last ) {
740                     sp_dyna_draw_brush(dc);
741                     g_assert( dc->npoints > 0 );
742                     fit_and_split(dc, FALSE);
743                 }
744                 ret = TRUE;
745             }
747             // Draw the hatching circle if necessary
748             if (event->motion.state & GDK_CONTROL_MASK) { 
749                 if (dc->hatch_spacing == 0 && hatch_dist != 0) { 
750                     // Haven't set spacing yet: gray, center free, update radius live
751                     NR::Point c = desktop->w2d(motion_w);
752                     NR::Matrix const sm (NR::scale(hatch_dist, hatch_dist) * NR::translate(c));
753                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
754                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
755                     sp_canvas_item_show(dc->hatch_area);
756                 } else if (dc->dragging && !dc->hatch_escaped) {
757                     // Tracking: green, center snapped, fixed radius
758                     NR::Point c = motion_dt;
759                     NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
760                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
761                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
762                     sp_canvas_item_show(dc->hatch_area);
763                 } else if (dc->dragging && dc->hatch_escaped) {
764                     // Tracking escaped: red, center free, fixed radius
765                     NR::Point c = desktop->w2d(motion_w);
766                     NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
768                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
769                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
770                     sp_canvas_item_show(dc->hatch_area);
771                 } else {
772                     // Not drawing but spacing set: gray, center snapped, fixed radius
773                     NR::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
774                     if (!IS_NAN(c[NR::X]) && !IS_NAN(c[NR::Y])) {
775                         NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
776                         sp_canvas_item_affine_absolute(dc->hatch_area, sm);
777                         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
778                         sp_canvas_item_show(dc->hatch_area);
779                     }
780                 }
781             } else {
782                 sp_canvas_item_hide(dc->hatch_area);
783             }
784         }
785         break;
788     case GDK_BUTTON_RELEASE:
789     {
790         NR::Point const motion_w(event->button.x, event->button.y);
791         NR::Point const motion_dt(desktop->w2d(motion_w));
793         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
794         sp_canvas_end_forced_full_redraws(desktop->canvas);
795         dc->is_drawing = false;
797         if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
798             dc->dragging = FALSE;
800             sp_dyna_draw_apply(dc, motion_dt);
802             /* Remove all temporary line segments */
803             while (dc->segments) {
804                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
805                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
806             }
808             /* Create object */
809             fit_and_split(dc, TRUE);
810             if (accumulate_calligraphic(dc))
811                 set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK); // performs document_done
812             else
813                 g_warning ("Failed to create path: invalid data in dc->cal1 or dc->cal2");
815             /* reset accumulated curve */
816             dc->accumulated->reset();
818             clear_current(dc);
819             if (dc->repr) {
820                 dc->repr = NULL;
821             }
823             if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
824             if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
825             dc->hatch_last_nearest = NR::Point(0,0);
826             dc->hatch_last_pointer = NR::Point(0,0);
827             dc->hatch_vector_accumulated = NR::Point(0,0);
828             dc->hatch_escaped = false;
829             dc->hatch_item = NULL;
830             dc->hatch_livarot_path = NULL;
832             if (dc->hatch_spacing != 0 && !dc->keep_selected) { 
833                 // we do not select the newly drawn path, so increase spacing by step
834                 if (dc->hatch_spacing_step == 0) {
835                     dc->hatch_spacing_step = dc->hatch_spacing;
836                 }
837                 dc->hatch_spacing += dc->hatch_spacing_step;
838             }
840             dc->_message_context->clear();
841             ret = TRUE;
842         }
843         break;
844     }
846     case GDK_KEY_PRESS:
847         switch (get_group0_keyval (&event->key)) {
848         case GDK_Up:
849         case GDK_KP_Up:
850             if (!MOD__CTRL_ONLY) {
851                 dc->angle += 5.0;
852                 if (dc->angle > 90.0)
853                     dc->angle = 90.0;
854                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
855                 ret = TRUE;
856             }
857             break;
858         case GDK_Down:
859         case GDK_KP_Down:
860             if (!MOD__CTRL_ONLY) {
861                 dc->angle -= 5.0;
862                 if (dc->angle < -90.0)
863                     dc->angle = -90.0;
864                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
865                 ret = TRUE;
866             }
867             break;
868         case GDK_Right:
869         case GDK_KP_Right:
870             if (!MOD__CTRL_ONLY) {
871                 dc->width += 0.01;
872                 if (dc->width > 1.0)
873                     dc->width = 1.0;
874                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
875                 ret = TRUE;
876             }
877             break;
878         case GDK_Left:
879         case GDK_KP_Left:
880             if (!MOD__CTRL_ONLY) {
881                 dc->width -= 0.01;
882                 if (dc->width < 0.01)
883                     dc->width = 0.01;
884                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
885                 ret = TRUE;
886             }
887             break;
888         case GDK_Home:
889         case GDK_KP_Home:
890             dc->width = 0.01;
891             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
892             ret = TRUE;
893             break;
894         case GDK_End:
895         case GDK_KP_End:
896             dc->width = 1.0;
897             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
898             ret = TRUE;
899             break;
900         case GDK_x:
901         case GDK_X:
902             if (MOD__ALT_ONLY) {
903                 desktop->setToolboxFocusTo ("altx-calligraphy");
904                 ret = TRUE;
905             }
906             break;
907         case GDK_Escape:
908             if (dc->is_drawing) {
909                 // if drawing, cancel, otherwise pass it up for deselecting
910                 calligraphic_cancel (dc);
911                 ret = TRUE;
912             }
913             break;
914         case GDK_z:
915         case GDK_Z:
916             if (MOD__CTRL_ONLY && dc->is_drawing) {
917                 // if drawing, cancel, otherwise pass it up for undo
918                 calligraphic_cancel (dc);
919                 ret = TRUE;
920             }
921             break;
922         default:
923             break;
924         }
925         break;
927     case GDK_KEY_RELEASE:
928         switch (get_group0_keyval(&event->key)) {
929             case GDK_Control_L:
930             case GDK_Control_R:
931                 dc->_message_context->clear();
932                 dc->hatch_spacing = 0;
933                 dc->hatch_spacing_step = 0;
934                 break;
935             default:
936                 break;
937         }
939     default:
940         break;
941     }
943     if (!ret) {
944         if (((SPEventContextClass *) dd_parent_class)->root_handler) {
945             ret = ((SPEventContextClass *) dd_parent_class)->root_handler(event_context, event);
946         }
947     }
949     return ret;
953 static void
954 clear_current(SPDynaDrawContext *dc)
956     /* reset bpath */
957     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
958     /* reset curve */
959     dc->currentcurve->reset();
960     dc->cal1->reset();
961     dc->cal2->reset();
962     /* reset points */
963     dc->npoints = 0;
966 static void
967 set_to_accumulated(SPDynaDrawContext *dc, bool unionize)
969     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
971     if (!dc->accumulated->is_empty()) {
972         if (!dc->repr) {
973             /* Create object */
974             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
975             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
977             /* Set style */
978             sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
980             dc->repr = repr;
982             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
983             Inkscape::GC::release(dc->repr);
984             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
985             item->updateRepr();
986         }
987         Geom::PathVector pathv = dc->accumulated->get_pathvector() * to_2geom(sp_desktop_dt2root_affine(desktop));
988         gchar *str = sp_svg_write_path(pathv);
989         g_assert( str != NULL );
990         dc->repr->setAttribute("d", str);
991         g_free(str);
993         if (unionize) {
994             sp_desktop_selection(desktop)->add(dc->repr);
995             sp_selected_path_union_skip_undo();
996         } else {
997             if (dc->keep_selected) {
998                 sp_desktop_selection(desktop)->set(dc->repr);
999             } 
1000         }
1002     } else {
1003         if (dc->repr) {
1004             sp_repr_unparent(dc->repr);
1005         }
1006         dc->repr = NULL;
1007     }
1009     sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC, 
1010                      _("Draw calligraphic stroke"));
1013 static void
1014 add_cap(SPCurve *curve,
1015         NR::Point const &from,
1016         NR::Point const &to, 
1017         double rounding)
1019     if (NR::L2( to - from ) > DYNA_EPSILON) {
1020         NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
1021         double mag = NR::L2(vel);
1023         NR::Point v = mag * NR::rot90( to - from ) / NR::L2( to - from );
1024         curve->curveto(from + v, to + v, to);
1025     }
1028 static bool
1029 accumulate_calligraphic(SPDynaDrawContext *dc)
1031         if (
1032             dc->cal1->is_empty() ||
1033             dc->cal2->is_empty() ||
1034             (dc->cal1->get_segment_count() <= 0) ||
1035             dc->cal1->first_path()->closed() 
1036             ) {
1037             dc->cal1->reset();
1038             dc->cal2->reset();
1039             return false; // failure
1040         }
1042         SPCurve *rev_cal2 = dc->cal2->create_reverse();
1043         if (
1044             (rev_cal2->get_segment_count() <= 0) ||
1045             rev_cal2->first_path()->closed() 
1046             ) {
1047             rev_cal2->unref();
1048             dc->cal1->reset();
1049             dc->cal2->reset();
1050             return false; // failure
1051         }
1053         Geom::CubicBezier const * dc_cal1_firstseg  = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->first_segment() );
1054         Geom::CubicBezier const * rev_cal2_firstseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->first_segment() );
1055         Geom::CubicBezier const * dc_cal1_lastseg   = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->last_segment() );
1056         Geom::CubicBezier const * rev_cal2_lastseg  = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->last_segment() );
1058         if (
1059             !dc_cal1_firstseg ||
1060             !rev_cal2_firstseg ||
1061             !dc_cal1_lastseg ||
1062             !rev_cal2_lastseg 
1063             ) {
1064             rev_cal2->unref();
1065             dc->cal1->reset();
1066             dc->cal2->reset();
1067             return false; // failure
1068         }
1070         dc->accumulated->reset(); /*  Is this required ?? */
1072         dc->accumulated->append(dc->cal1, false);
1074         add_cap(dc->accumulated, (*dc_cal1_lastseg)[3], (*rev_cal2_firstseg)[0], dc->cap_rounding);
1076         dc->accumulated->append(rev_cal2, true);
1078         add_cap(dc->accumulated, (*rev_cal2_lastseg)[3], (*dc_cal1_firstseg)[0], dc->cap_rounding);
1080         dc->accumulated->closepath();
1082         rev_cal2->unref();
1084         dc->cal1->reset();
1085         dc->cal2->reset();
1087         return true; // success
1090 static double square(double const x)
1092     return x * x;
1095 static void
1096 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1098     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
1100 #ifdef DYNA_DRAW_VERBOSE
1101     g_print("[F&S:R=%c]", release?'T':'F');
1102 #endif
1104     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1105         return; // just clicked
1107     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1108 #define BEZIER_SIZE       4
1109 #define BEZIER_MAX_BEZIERS  8
1110 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1112 #ifdef DYNA_DRAW_VERBOSE
1113         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1114                 dc->npoints, release ? "TRUE" : "FALSE");
1115 #endif
1117         /* Current calligraphic */
1118         if ( dc->cal1->is_empty() || dc->cal2->is_empty() ) {
1119             /* dc->npoints > 0 */
1120             /* g_print("calligraphics(1|2) reset\n"); */
1121             dc->cal1->reset();
1122             dc->cal2->reset();
1124             dc->cal1->moveto(dc->point1[0]);
1125             dc->cal2->moveto(dc->point2[0]);
1126         }
1128         NR::Point b1[BEZIER_MAX_LENGTH];
1129         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1130                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1131         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1133         NR::Point b2[BEZIER_MAX_LENGTH];
1134         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1135                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1136         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1138         if ( nb1 != -1 && nb2 != -1 ) {
1139             /* Fit and draw and reset state */
1140 #ifdef DYNA_DRAW_VERBOSE
1141             g_print("nb1:%d nb2:%d\n", nb1, nb2);
1142 #endif
1143             /* CanvasShape */
1144             if (! release) {
1145                 dc->currentcurve->reset();
1146                 dc->currentcurve->moveto(b1[0]);
1147                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1148                     dc->currentcurve->curveto(bp1[1],
1149                                      bp1[2], bp1[3]);
1150                 }
1151                 dc->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]);
1152                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1153                     dc->currentcurve->curveto(bp2[2], bp2[1], bp2[0]);
1154                 }
1155                 // FIXME: dc->segments is always NULL at this point??
1156                 if (!dc->segments) { // first segment
1157                     add_cap(dc->currentcurve, b2[0], b1[0], dc->cap_rounding);
1158                 }
1159                 dc->currentcurve->closepath();
1160                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1161             }
1163             /* Current calligraphic */
1164             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1165                 dc->cal1->curveto(bp1[1], bp1[2], bp1[3]);
1166             }
1167             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1168                 dc->cal2->curveto(bp2[1], bp2[2], bp2[3]);
1169             }
1170         } else {
1171             /* fixme: ??? */
1172 #ifdef DYNA_DRAW_VERBOSE
1173             g_print("[fit_and_split] failed to fit-cubic.\n");
1174 #endif
1175             draw_temporary_box(dc);
1177             for (gint i = 1; i < dc->npoints; i++) {
1178                 dc->cal1->lineto(dc->point1[i]);
1179             }
1180             for (gint i = 1; i < dc->npoints; i++) {
1181                 dc->cal2->lineto(dc->point2[i]);
1182             }
1183         }
1185         /* Fit and draw and copy last point */
1186 #ifdef DYNA_DRAW_VERBOSE
1187         g_print("[%d]Yup\n", dc->npoints);
1188 #endif
1189         if (!release) {
1190             g_assert(!dc->currentcurve->is_empty());
1192             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1193                                                    SP_TYPE_CANVAS_BPATH,
1194                                                    NULL);
1195             SPCurve *curve = dc->currentcurve->copy();
1196             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1197             curve->unref();
1199             guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1200             //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1201             double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
1202             double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1203             //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1204             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1205             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1206             //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);
1207             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1208             /* fixme: Cannot we cascade it to root more clearly? */
1209             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1211             dc->segments = g_slist_prepend(dc->segments, cbp);
1212         }
1214         dc->point1[0] = dc->point1[dc->npoints - 1];
1215         dc->point2[0] = dc->point2[dc->npoints - 1];
1216         dc->npoints = 1;
1217     } else {
1218         draw_temporary_box(dc);
1219     }
1222 static void
1223 draw_temporary_box(SPDynaDrawContext *dc)
1225     dc->currentcurve->reset();
1227     dc->currentcurve->moveto(dc->point2[dc->npoints-1]);
1228     for (gint i = dc->npoints-2; i >= 0; i--) {
1229         dc->currentcurve->lineto(dc->point2[i]);
1230     }
1231     for (gint i = 0; i < dc->npoints; i++) {
1232         dc->currentcurve->lineto(dc->point1[i]);
1233     }
1235     if (dc->npoints >= 2) {
1236         add_cap(dc->currentcurve, dc->point1[dc->npoints-1], dc->point2[dc->npoints-1], dc->cap_rounding);
1237     }
1239     dc->currentcurve->closepath();
1240     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1243 /*
1244   Local Variables:
1245   mode:c++
1246   c-file-style:"stroustrup"
1247   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1248   indent-tabs-mode:nil
1249   fill-column:99
1250   End:
1251 */
1252 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :