Code

show waiting cursor while ExecutionEnv is working
[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 <2geom/isnan.h>
38 #include <2geom/pathvector.h>
39 #include <2geom/bezier-utils.h>
40 #include "display/curve.h"
41 #include <glib/gmem.h>
42 #include "macros.h"
43 #include "document.h"
44 #include "selection.h"
45 #include "desktop.h"
46 #include "desktop-events.h"
47 #include "desktop-handles.h"
48 #include "desktop-affine.h"
49 #include "desktop-style.h"
50 #include "message-context.h"
51 #include "preferences.h"
52 #include "pixmaps/cursor-calligraphy.xpm"
53 #include "xml/repr.h"
54 #include "context-fns.h"
55 #include "sp-item.h"
56 #include "inkscape.h"
57 #include "color.h"
58 #include "splivarot.h"
59 #include "sp-item-group.h"
60 #include "sp-shape.h"
61 #include "sp-path.h"
62 #include "sp-text.h"
63 #include "display/canvas-bpath.h"
64 #include "display/canvas-arena.h"
65 #include "livarot/Shape.h"
67 #include "dyna-draw-context.h"
69 #define DDC_RED_RGBA 0xff0000ff
71 #define TOLERANCE_CALLIGRAPHIC 0.1
73 #define DYNA_EPSILON 0.5e-6
74 #define DYNA_EPSILON_START 0.5e-2
75 #define DYNA_VEL_START 1e-5
77 #define DYNA_MIN_WIDTH 1.0e-6
79 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
80 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
81 static void sp_dyna_draw_context_dispose(GObject *object);
83 static void sp_dyna_draw_context_setup(SPEventContext *ec);
84 static void sp_dyna_draw_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *value);
85 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
87 static void clear_current(SPDynaDrawContext *dc);
88 static void set_to_accumulated(SPDynaDrawContext *dc, bool unionize, bool subtract);
89 static void add_cap(SPCurve *curve, Geom::Point const &from, Geom::Point const &to, double rounding);
90 static bool accumulate_calligraphic(SPDynaDrawContext *dc);
92 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
94 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, Geom::Point p);
95 static Geom::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, Geom::Point v);
96 static Geom::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, Geom::Point n);
97 static void draw_temporary_box(SPDynaDrawContext *dc);
100 static SPEventContextClass *dd_parent_class = 0;
102 GType sp_dyna_draw_context_get_type(void)
104     static GType type = 0;
105     if (!type) {
106         GTypeInfo info = {
107             sizeof(SPDynaDrawContextClass),
108             0, // base_init
109             0, // base_finalize
110             (GClassInitFunc)sp_dyna_draw_context_class_init,
111             0, // class_finalize
112             0, // class_data
113             sizeof(SPDynaDrawContext),
114             0, // n_preallocs
115             (GInstanceInitFunc)sp_dyna_draw_context_init,
116             0 // value_table
117         };
118         type = g_type_register_static(SP_TYPE_COMMON_CONTEXT, "SPDynaDrawContext", &info, static_cast<GTypeFlags>(0));
119     }
120     return type;
123 static void
124 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
126     GObjectClass *object_class = (GObjectClass *) klass;
127     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
129     dd_parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
131     object_class->dispose = sp_dyna_draw_context_dispose;
133     event_context_class->setup = sp_dyna_draw_context_setup;
134     event_context_class->set = sp_dyna_draw_context_set;
135     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
138 static void
139 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
141     ddc->cursor_shape = cursor_calligraphy_xpm;
142     ddc->hot_x = 4;
143     ddc->hot_y = 4;
145     ddc->vel_thin = 0.1;
146     ddc->flatness = 0.9;
147     ddc->cap_rounding = 0.0;
149     ddc->abs_width = false;
150     ddc->keep_selected = true;
152     ddc->hatch_spacing = 0;
153     ddc->hatch_spacing_step = 0;
154     new (&ddc->hatch_pointer_past) std::list<double>();
155     new (&ddc->hatch_nearest_past) std::list<double>();
156     new (&ddc->inertia_vectors) std::list<Geom::Point>();
157     new (&ddc->hatch_vectors) std::list<Geom::Point>();
158     ddc->hatch_last_nearest = Geom::Point(0,0);
159     ddc->hatch_last_pointer = Geom::Point(0,0);
160     ddc->hatch_escaped = false;
161     ddc->hatch_area = NULL;
162     ddc->hatch_item = NULL;
163     ddc->hatch_livarot_path = NULL;
165     ddc->trace_bg = false;
166     ddc->just_started_drawing = false;
169 static void
170 sp_dyna_draw_context_dispose(GObject *object)
172     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
174     if (ddc->hatch_area) {
175         gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
176         ddc->hatch_area = NULL;
177     }
180     G_OBJECT_CLASS(dd_parent_class)->dispose(object);
182     ddc->hatch_pointer_past.~list();
183     ddc->hatch_nearest_past.~list();
184     ddc->inertia_vectors.~list();
185     ddc->hatch_vectors.~list();
188 static void
189 sp_dyna_draw_context_setup(SPEventContext *ec)
191     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
193     if (((SPEventContextClass *) dd_parent_class)->setup)
194         ((SPEventContextClass *) dd_parent_class)->setup(ec);
196     ddc->accumulated = new SPCurve();
197     ddc->currentcurve = new SPCurve();
199     ddc->cal1 = new SPCurve();
200     ddc->cal2 = new SPCurve();
202     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
203     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
204     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
205     /* fixme: Cannot we cascade it to root more clearly? */
206     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
208     {
209         /* 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) */
210         SPCurve *c = new SPCurve();
211         const double C1 = 0.552;
212         c->moveto(-1,0);
213         c->curveto(-1, C1, -C1, 1, 0, 1 );
214         c->curveto(C1, 1, 1, C1, 1, 0 );
215         c->curveto(1, -C1, C1, -1, 0, -1 );
216         c->curveto(-C1, -1, -1, -C1, -1, 0 );
217         c->closepath();
218         ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
219         c->unref();
220         sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
221         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
222         sp_canvas_item_hide(ddc->hatch_area);
223     }
225     sp_event_context_read(ec, "mass");
226     sp_event_context_read(ec, "wiggle");
227     sp_event_context_read(ec, "angle");
228     sp_event_context_read(ec, "width");
229     sp_event_context_read(ec, "thinning");
230     sp_event_context_read(ec, "tremor");
231     sp_event_context_read(ec, "flatness");
232     sp_event_context_read(ec, "tracebackground");
233     sp_event_context_read(ec, "usepressure");
234     sp_event_context_read(ec, "usetilt");
235     sp_event_context_read(ec, "abs_width");
236     sp_event_context_read(ec, "keep_selected");
237     sp_event_context_read(ec, "cap_rounding");
239     ddc->is_drawing = false;
240     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
242     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
243     if (prefs->getBool("/tools/calligraphic/selcue")) {
244         ec->enableSelectionCue();
245     }
248 static void
249 sp_dyna_draw_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val)
251     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
252     Glib::ustring path = val->getEntryName();
254     if (path == "tracebackground") {
255         ddc->trace_bg = val->getBool();
256     } else if (path == "keep_selected") {
257         ddc->keep_selected = val->getBool();
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, 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 Geom::Point
276 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, Geom::Point v)
278     Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
279     double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
280     return Geom::Point(( v[Geom::X] - drect.min()[Geom::X] ) / max,  ( v[Geom::Y] - drect.min()[Geom::Y] ) / max);
283 /* Get view point */
284 static Geom::Point
285 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, Geom::Point n)
287     Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
288     double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
289     return Geom::Point(n[Geom::X] * max + drect.min()[Geom::X], n[Geom::Y] * max + drect.min()[Geom::Y]);
292 static void
293 sp_dyna_draw_reset(SPDynaDrawContext *dc, Geom::Point p)
295     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
296     dc->vel = Geom::Point(0,0);
297     dc->vel_max = 0;
298     dc->acc = Geom::Point(0,0);
299     dc->ang = Geom::Point(0,0);
300     dc->del = Geom::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, Geom::Point p)
326     Geom::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     Geom::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 ( Geom::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && Geom::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 (Geom::L2(dc->vel) > dc->vel_max)
352         dc->vel_max = Geom::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             Geom::Point ang1 = Geom::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         Geom::Point ang1 = Geom::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 = Geom::L2(dc->vel);
377     if ( mag_vel < DYNA_EPSILON ) {
378         return FALSE;
379     }
380     Geom::Point ang2 = Geom::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 = Geom::L2(Geom::Point (cos (new_ang), sin (new_ang)) - dc->ang);
403     if ( angle_delta / Geom::L2(dc->vel) > 4000 ) {
404         return FALSE;
405     }
407     // convert to point
408     dc->ang = Geom::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", Geom::L2(force), Geom::L2(dc->acc), dc->vel_max, Geom::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     Geom::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
436     Geom::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[Geom::X]);
443         int y = (int) floor(brush_w[Geom::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 * Geom::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*Geom::L2(dc->vel));
479         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::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     Geom::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
492     Geom::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                 dc->accumulated->reset();
549                 if (dc->repr) {
550                     dc->repr = NULL;
551                 }
553                 /* initialize first point */
554                 dc->npoints = 0;
556                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
557                                     ( GDK_KEY_PRESS_MASK |
558                                       GDK_BUTTON_RELEASE_MASK |
559                                       GDK_POINTER_MOTION_MASK |
560                                       GDK_BUTTON_PRESS_MASK ),
561                                     NULL,
562                                     event->button.time);
564                 ret = TRUE;
566                 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
567                 dc->is_drawing = true;
568                 dc->just_started_drawing = true;
569             }
570             break;
571         case GDK_MOTION_NOTIFY:
572         {
573             Geom::Point const motion_w(event->motion.x,
574                                      event->motion.y);
575             Geom::Point motion_dt(desktop->w2d(motion_w));
576             sp_dyna_draw_extinput(dc, event);
578             dc->_message_context->clear();
580             // for hatching:
581             double hatch_dist = 0;
582             Geom::Point hatch_unit_vector(0,0);
583             Geom::Point nearest(0,0);
584             Geom::Point pointer(0,0);
585             Geom::Matrix motion_to_curve(Geom::identity());
587             if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
589                 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
590                 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
591                     // One item selected, and it's a path;
592                     // let's try to track it as a guide
594                     if (selected != dc->hatch_item) {
595                         dc->hatch_item = selected;
596                         if (dc->hatch_livarot_path)
597                             delete dc->hatch_livarot_path;
598                         dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
599                         dc->hatch_livarot_path->ConvertWithBackData(0.01);
600                     }
602                     // calculate pointer point in the guide item's coords
603                     motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
604                     pointer = motion_dt * motion_to_curve;
606                     // calculate the nearest point on the guide path
607                     boost::optional<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
608                     nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
611                     // distance from pointer to nearest
612                     hatch_dist = Geom::L2(pointer - nearest);
613                     // unit-length vector
614                     hatch_unit_vector = (pointer - nearest)/hatch_dist;
616                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
617                 } else {
618                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
619                 }
620             }
622             if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
623                 dc->dragging = TRUE;
625                 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
627 #define HATCH_VECTOR_ELEMENTS 12
628 #define INERTIA_ELEMENTS 24
629 #define SPEED_ELEMENTS 12
630 #define SPEED_MIN 0.3
631 #define SPEED_NORMAL 0.35
632 #define INERTIA_FORCE 0.5
634                     // speed is the movement of the nearest point along the guide path, divided by
635                     // the movement of the pointer at the same period; it is averaged for the last
636                     // SPEED_ELEMENTS motion events.  Normally, as you track the guide path, speed
637                     // is about 1, i.e. the nearest point on the path is moved by about the same
638                     // distance as the pointer. If the speed starts to decrease, we are losing
639                     // contact with the guide; if it drops below SPEED_MIN, we are on our own and
640                     // not attracted to guide anymore. Most often this happens when you have
641                     // tracked to the end of a guide calligraphic stroke and keep moving
642                     // further. We try to handle this situation gracefully: not stick with the
643                     // guide forever but let go of it smoothly and without sharp jerks (non-zero
644                     // mass recommended; with zero mass, jerks are still quite noticeable).
646                     double speed = 1;
647                     if (Geom::L2(dc->hatch_last_nearest) != 0) {
648                         // the distance nearest moved since the last motion event
649                         double nearest_moved = Geom::L2(nearest - dc->hatch_last_nearest);
650                         // the distance pointer moved since the last motion event
651                         double pointer_moved = Geom::L2(pointer - dc->hatch_last_pointer);
652                         // store them in stacks limited to SPEED_ELEMENTS
653                         dc->hatch_nearest_past.push_front(nearest_moved);
654                         if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
655                             dc->hatch_nearest_past.pop_back();
656                         dc->hatch_pointer_past.push_front(pointer_moved);
657                         if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
658                             dc->hatch_pointer_past.pop_back();
660                         // If the stacks are full,
661                         if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
662                             // calculate the sums of all stored movements
663                             double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
664                             double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
665                             // and divide to get the speed
666                             speed = nearest_sum/pointer_sum;
667                             //g_print ("nearest sum %g  pointer_sum %g  speed %g\n", nearest_sum, pointer_sum, speed);
668                         }
669                     }
671                     if (   dc->hatch_escaped  // already escaped, do not reattach
672                         || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
673                         || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
674                         ) {
675                         // We are NOT attracted to the guide!
677                         //g_print ("\nlast_nearest %g %g   nearest %g %g  pointer %g %g  pos %d %g\n", dc->last_nearest[Geom::X], dc->last_nearest[Geom::Y], nearest[Geom::X], nearest[Geom::Y], pointer[Geom::X], pointer[Geom::Y], position->piece, position->t);
679                         // Remember hatch_escaped so we don't get
680                         // attracted again until the end of this stroke
681                         dc->hatch_escaped = true;
683                         if (dc->inertia_vectors.size() >= INERTIA_ELEMENTS/2) { // move by inertia
684                             Geom::Point moved_past_escape = motion_dt - dc->inertia_vectors.front();
685                             Geom::Point inertia = 
686                                 dc->inertia_vectors.front() - dc->inertia_vectors.back();
688                             double dot = Geom::dot (moved_past_escape, inertia);
689                             dot /= Geom::L2(moved_past_escape) * Geom::L2(inertia);
691                             if (dot > 0) { // mouse is still moving in approx the same direction
692                                 Geom::Point should_have_moved = 
693                                     (inertia) * (1/Geom::L2(inertia)) * Geom::L2(moved_past_escape);
694                                 motion_dt = dc->inertia_vectors.front() + 
695                                     (INERTIA_FORCE * should_have_moved + (1 - INERTIA_FORCE) * moved_past_escape);
696                             }
697                         }
699                     } else {
701                         // Calculate angle cosine of this vector-to-guide and all past vectors
702                         // summed, to detect if we accidentally flipped to the other side of the
703                         // guide
704                         Geom::Point hatch_vector_accumulated = std::accumulate 
705                             (dc->hatch_vectors.begin(), dc->hatch_vectors.end(), Geom::Point(0,0));
706                         double dot = Geom::dot (pointer - nearest, hatch_vector_accumulated);
707                         dot /= Geom::L2(pointer - nearest) * Geom::L2(hatch_vector_accumulated);
709                         if (dc->hatch_spacing != 0) { // spacing was already set
710                             double target;
711                             if (speed > SPEED_NORMAL) {
712                                 // all ok, strictly obey the spacing
713                                 target = dc->hatch_spacing;
714                             } else {
715                                 // looks like we're starting to lose speed,
716                                 // so _gradually_ let go attraction to prevent jerks
717                                 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;
718                             }
719                             if (!IS_NAN(dot) && dot < -0.5) {// flip
720                                 target = -target;
721                             }
723                             // This is the track pointer that we will use instead of the real one
724                             Geom::Point new_pointer = nearest + target * hatch_unit_vector;
726                             // some limited feedback: allow persistent pulling to slightly change
727                             // the spacing
728                             dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
730                             // return it to the desktop coords
731                             motion_dt = new_pointer * motion_to_curve.inverse();
733                             if (speed >= SPEED_NORMAL) {
734                                 dc->inertia_vectors.push_front(motion_dt);
735                                 if (dc->inertia_vectors.size() > INERTIA_ELEMENTS)
736                                     dc->inertia_vectors.pop_back();
737                             }
739                         } else {
740                             // this is the first motion event, set the dist
741                             dc->hatch_spacing = hatch_dist;
742                         }
744                         // remember last points
745                         dc->hatch_last_pointer = pointer;
746                         dc->hatch_last_nearest = nearest;
748                         dc->hatch_vectors.push_front(pointer - nearest);
749                         if (dc->hatch_vectors.size() > HATCH_VECTOR_ELEMENTS)
750                             dc->hatch_vectors.pop_back();
751                     }
753                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
755                 } else {
756                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
757                 }
759                 if (dc->just_started_drawing) {
760                     dc->just_started_drawing = false;
761                     sp_dyna_draw_reset(dc, motion_dt);
762                 }
764                 if (!sp_dyna_draw_apply(dc, motion_dt)) {
765                     ret = TRUE;
766                     break;
767                 }
769                 if ( dc->cur != dc->last ) {
770                     sp_dyna_draw_brush(dc);
771                     g_assert( dc->npoints > 0 );
772                     fit_and_split(dc, FALSE);
773                 }
774                 ret = TRUE;
775             }
777             // Draw the hatching circle if necessary
778             if (event->motion.state & GDK_CONTROL_MASK) {
779                 if (dc->hatch_spacing == 0 && hatch_dist != 0) {
780                     // Haven't set spacing yet: gray, center free, update radius live
781                     Geom::Point c = desktop->w2d(motion_w);
782                     Geom::Matrix const sm (Geom::Scale(hatch_dist, hatch_dist) * Geom::Translate(c));
783                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
784                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
785                     sp_canvas_item_show(dc->hatch_area);
786                 } else if (dc->dragging && !dc->hatch_escaped) {
787                     // Tracking: green, center snapped, fixed radius
788                     Geom::Point c = motion_dt;
789                     Geom::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
790                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
791                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
792                     sp_canvas_item_show(dc->hatch_area);
793                 } else if (dc->dragging && dc->hatch_escaped) {
794                     // Tracking escaped: red, center free, fixed radius
795                     Geom::Point c = motion_dt;
796                     Geom::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
798                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
799                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
800                     sp_canvas_item_show(dc->hatch_area);
801                 } else {
802                     // Not drawing but spacing set: gray, center snapped, fixed radius
803                     Geom::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
804                     if (!IS_NAN(c[Geom::X]) && !IS_NAN(c[Geom::Y])) {
805                         Geom::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
806                         sp_canvas_item_affine_absolute(dc->hatch_area, sm);
807                         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
808                         sp_canvas_item_show(dc->hatch_area);
809                     }
810                 }
811             } else {
812                 sp_canvas_item_hide(dc->hatch_area);
813             }
814         }
815         break;
818     case GDK_BUTTON_RELEASE:
819     {
820         Geom::Point const motion_w(event->button.x, event->button.y);
821         Geom::Point const motion_dt(desktop->w2d(motion_w));
823         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
824         sp_canvas_end_forced_full_redraws(desktop->canvas);
825         dc->is_drawing = false;
827         if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
828             dc->dragging = FALSE;
830             sp_dyna_draw_apply(dc, motion_dt);
832             /* Remove all temporary line segments */
833             while (dc->segments) {
834                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
835                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
836             }
838             /* Create object */
839             fit_and_split(dc, TRUE);
840             if (accumulate_calligraphic(dc))
841                 set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK, event->button.state & GDK_MOD1_MASK); // performs document_done
842             else
843                 g_warning ("Failed to create path: invalid data in dc->cal1 or dc->cal2");
845             /* reset accumulated curve */
846             dc->accumulated->reset();
848             clear_current(dc);
849             if (dc->repr) {
850                 dc->repr = NULL;
851             }
853             if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
854             if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
855             if (!dc->inertia_vectors.empty()) dc->inertia_vectors.clear();
856             if (!dc->hatch_vectors.empty()) dc->hatch_vectors.clear();
857             dc->hatch_last_nearest = Geom::Point(0,0);
858             dc->hatch_last_pointer = Geom::Point(0,0);
859             dc->hatch_escaped = false;
860             dc->hatch_item = NULL;
861             dc->hatch_livarot_path = NULL;
862             dc->just_started_drawing = false;
864             if (dc->hatch_spacing != 0 && !dc->keep_selected) {
865                 // we do not select the newly drawn path, so increase spacing by step
866                 if (dc->hatch_spacing_step == 0) {
867                     dc->hatch_spacing_step = dc->hatch_spacing;
868                 }
869                 dc->hatch_spacing += dc->hatch_spacing_step;
870             }
872             dc->_message_context->clear();
873             ret = TRUE;
874         }
875         break;
876     }
878     case GDK_KEY_PRESS:
879         switch (get_group0_keyval (&event->key)) {
880         case GDK_Up:
881         case GDK_KP_Up:
882             if (!MOD__CTRL_ONLY) {
883                 dc->angle += 5.0;
884                 if (dc->angle > 90.0)
885                     dc->angle = 90.0;
886                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
887                 ret = TRUE;
888             }
889             break;
890         case GDK_Down:
891         case GDK_KP_Down:
892             if (!MOD__CTRL_ONLY) {
893                 dc->angle -= 5.0;
894                 if (dc->angle < -90.0)
895                     dc->angle = -90.0;
896                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
897                 ret = TRUE;
898             }
899             break;
900         case GDK_Right:
901         case GDK_KP_Right:
902             if (!MOD__CTRL_ONLY) {
903                 dc->width += 0.01;
904                 if (dc->width > 1.0)
905                     dc->width = 1.0;
906                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
907                 ret = TRUE;
908             }
909             break;
910         case GDK_Left:
911         case GDK_KP_Left:
912             if (!MOD__CTRL_ONLY) {
913                 dc->width -= 0.01;
914                 if (dc->width < 0.01)
915                     dc->width = 0.01;
916                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
917                 ret = TRUE;
918             }
919             break;
920         case GDK_Home:
921         case GDK_KP_Home:
922             dc->width = 0.01;
923             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
924             ret = TRUE;
925             break;
926         case GDK_End:
927         case GDK_KP_End:
928             dc->width = 1.0;
929             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
930             ret = TRUE;
931             break;
932         case GDK_x:
933         case GDK_X:
934             if (MOD__ALT_ONLY) {
935                 desktop->setToolboxFocusTo ("altx-calligraphy");
936                 ret = TRUE;
937             }
938             break;
939         case GDK_Escape:
940             if (dc->is_drawing) {
941                 // if drawing, cancel, otherwise pass it up for deselecting
942                 calligraphic_cancel (dc);
943                 ret = TRUE;
944             }
945             break;
946         case GDK_z:
947         case GDK_Z:
948             if (MOD__CTRL_ONLY && dc->is_drawing) {
949                 // if drawing, cancel, otherwise pass it up for undo
950                 calligraphic_cancel (dc);
951                 ret = TRUE;
952             }
953             break;
954         default:
955             break;
956         }
957         break;
959     case GDK_KEY_RELEASE:
960         switch (get_group0_keyval(&event->key)) {
961             case GDK_Control_L:
962             case GDK_Control_R:
963                 dc->_message_context->clear();
964                 dc->hatch_spacing = 0;
965                 dc->hatch_spacing_step = 0;
966                 break;
967             default:
968                 break;
969         }
971     default:
972         break;
973     }
975     if (!ret) {
976         if (((SPEventContextClass *) dd_parent_class)->root_handler) {
977             ret = ((SPEventContextClass *) dd_parent_class)->root_handler(event_context, event);
978         }
979     }
981     return ret;
985 static void
986 clear_current(SPDynaDrawContext *dc)
988     /* reset bpath */
989     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
990     /* reset curve */
991     dc->currentcurve->reset();
992     dc->cal1->reset();
993     dc->cal2->reset();
994     /* reset points */
995     dc->npoints = 0;
998 static void
999 set_to_accumulated(SPDynaDrawContext *dc, bool unionize, bool subtract)
1001     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1003     if (!dc->accumulated->is_empty()) {
1004         if (!dc->repr) {
1005             /* Create object */
1006             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1007             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1009             /* Set style */
1010             sp_desktop_apply_style_tool (desktop, repr, "/tools/calligraphic", false);
1012             dc->repr = repr;
1014             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
1015             Inkscape::GC::release(dc->repr);
1016             item->transform = sp_item_i2doc_affine(SP_ITEM(desktop->currentLayer())).inverse();
1017             item->updateRepr();
1018         }
1019         Geom::PathVector pathv = dc->accumulated->get_pathvector() * sp_desktop_dt2doc_affine(desktop);
1020         gchar *str = sp_svg_write_path(pathv);
1021         g_assert( str != NULL );
1022         dc->repr->setAttribute("d", str);
1023         g_free(str);
1025         if (unionize) {
1026             sp_desktop_selection(desktop)->add(dc->repr);
1027             sp_selected_path_union_skip_undo(desktop);
1028         } else if (subtract) {
1029             sp_desktop_selection(desktop)->add(dc->repr);
1030             sp_selected_path_diff_skip_undo(desktop);
1031         } else {
1032             if (dc->keep_selected) {
1033                 sp_desktop_selection(desktop)->set(dc->repr);
1034             }
1035         }
1037     } else {
1038         if (dc->repr) {
1039             sp_repr_unparent(dc->repr);
1040         }
1041         dc->repr = NULL;
1042     }
1044     sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC,
1045                      _("Draw calligraphic stroke"));
1048 static void
1049 add_cap(SPCurve *curve,
1050         Geom::Point const &from,
1051         Geom::Point const &to,
1052         double rounding)
1054     if (Geom::L2( to - from ) > DYNA_EPSILON) {
1055         Geom::Point vel = rounding * Geom::rot90( to - from ) / sqrt(2.0);
1056         double mag = Geom::L2(vel);
1058         Geom::Point v = mag * Geom::rot90( to - from ) / Geom::L2( to - from );
1059         curve->curveto(from + v, to + v, to);
1060     }
1063 static bool
1064 accumulate_calligraphic(SPDynaDrawContext *dc)
1066         if (
1067             dc->cal1->is_empty() ||
1068             dc->cal2->is_empty() ||
1069             (dc->cal1->get_segment_count() <= 0) ||
1070             dc->cal1->first_path()->closed()
1071             ) {
1072             dc->cal1->reset();
1073             dc->cal2->reset();
1074             return false; // failure
1075         }
1077         SPCurve *rev_cal2 = dc->cal2->create_reverse();
1078         if (
1079             (rev_cal2->get_segment_count() <= 0) ||
1080             rev_cal2->first_path()->closed()
1081             ) {
1082             rev_cal2->unref();
1083             dc->cal1->reset();
1084             dc->cal2->reset();
1085             return false; // failure
1086         }
1088         Geom::CubicBezier const * dc_cal1_firstseg  = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->first_segment() );
1089         Geom::CubicBezier const * rev_cal2_firstseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->first_segment() );
1090         Geom::CubicBezier const * dc_cal1_lastseg   = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->last_segment() );
1091         Geom::CubicBezier const * rev_cal2_lastseg  = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->last_segment() );
1093         if (
1094             !dc_cal1_firstseg ||
1095             !rev_cal2_firstseg ||
1096             !dc_cal1_lastseg ||
1097             !rev_cal2_lastseg
1098             ) {
1099             rev_cal2->unref();
1100             dc->cal1->reset();
1101             dc->cal2->reset();
1102             return false; // failure
1103         }
1105         dc->accumulated->reset(); /*  Is this required ?? */
1107         dc->accumulated->append(dc->cal1, false);
1109         add_cap(dc->accumulated, (*dc_cal1_lastseg)[3], (*rev_cal2_firstseg)[0], dc->cap_rounding);
1111         dc->accumulated->append(rev_cal2, true);
1113         add_cap(dc->accumulated, (*rev_cal2_lastseg)[3], (*dc_cal1_firstseg)[0], dc->cap_rounding);
1115         dc->accumulated->closepath();
1117         rev_cal2->unref();
1119         dc->cal1->reset();
1120         dc->cal2->reset();
1122         return true; // success
1125 static double square(double const x)
1127     return x * x;
1130 static void
1131 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1133     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1135     double const tolerance_sq = square( desktop->w2d().descrim() * TOLERANCE_CALLIGRAPHIC );
1137 #ifdef DYNA_DRAW_VERBOSE
1138     g_print("[F&S:R=%c]", release?'T':'F');
1139 #endif
1141     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1142         return; // just clicked
1144     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1145 #define BEZIER_SIZE       4
1146 #define BEZIER_MAX_BEZIERS  8
1147 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1149 #ifdef DYNA_DRAW_VERBOSE
1150         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1151                 dc->npoints, release ? "TRUE" : "FALSE");
1152 #endif
1154         /* Current calligraphic */
1155         if ( dc->cal1->is_empty() || dc->cal2->is_empty() ) {
1156             /* dc->npoints > 0 */
1157             /* g_print("calligraphics(1|2) reset\n"); */
1158             dc->cal1->reset();
1159             dc->cal2->reset();
1161             dc->cal1->moveto(dc->point1[0]);
1162             dc->cal2->moveto(dc->point2[0]);
1163         }
1165         Geom::Point b1[BEZIER_MAX_LENGTH];
1166         gint const nb1 = Geom::bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1167                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1168         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1170         Geom::Point b2[BEZIER_MAX_LENGTH];
1171         gint const nb2 = Geom::bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1172                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1173         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1175         if ( nb1 != -1 && nb2 != -1 ) {
1176             /* Fit and draw and reset state */
1177 #ifdef DYNA_DRAW_VERBOSE
1178             g_print("nb1:%d nb2:%d\n", nb1, nb2);
1179 #endif
1180             /* CanvasShape */
1181             if (! release) {
1182                 dc->currentcurve->reset();
1183                 dc->currentcurve->moveto(b1[0]);
1184                 for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1185                     dc->currentcurve->curveto(bp1[1], bp1[2], bp1[3]);
1186                 }
1187                 dc->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]);
1188                 for (Geom::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1189                     dc->currentcurve->curveto(bp2[2], bp2[1], bp2[0]);
1190                 }
1191                 // FIXME: dc->segments is always NULL at this point??
1192                 if (!dc->segments) { // first segment
1193                     add_cap(dc->currentcurve, b2[0], b1[0], dc->cap_rounding);
1194                 }
1195                 dc->currentcurve->closepath();
1196                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1197             }
1199             /* Current calligraphic */
1200             for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1201                 dc->cal1->curveto(bp1[1], bp1[2], bp1[3]);
1202             }
1203             for (Geom::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1204                 dc->cal2->curveto(bp2[1], bp2[2], bp2[3]);
1205             }
1206         } else {
1207             /* fixme: ??? */
1208 #ifdef DYNA_DRAW_VERBOSE
1209             g_print("[fit_and_split] failed to fit-cubic.\n");
1210 #endif
1211             draw_temporary_box(dc);
1213             for (gint i = 1; i < dc->npoints; i++) {
1214                 dc->cal1->lineto(dc->point1[i]);
1215             }
1216             for (gint i = 1; i < dc->npoints; i++) {
1217                 dc->cal2->lineto(dc->point2[i]);
1218             }
1219         }
1221         /* Fit and draw and copy last point */
1222 #ifdef DYNA_DRAW_VERBOSE
1223         g_print("[%d]Yup\n", dc->npoints);
1224 #endif
1225         if (!release) {
1226             g_assert(!dc->currentcurve->is_empty());
1228             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(desktop),
1229                                                    SP_TYPE_CANVAS_BPATH,
1230                                                    NULL);
1231             SPCurve *curve = dc->currentcurve->copy();
1232             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1233             curve->unref();
1235             guint32 fillColor = sp_desktop_get_color_tool (desktop, "/tools/calligraphic", true);
1236             //guint32 strokeColor = sp_desktop_get_color_tool (desktop, "/tools/calligraphic", false);
1237             double opacity = sp_desktop_get_master_opacity_tool (desktop, "/tools/calligraphic");
1238             double fillOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/calligraphic", true);
1239             //double strokeOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/calligraphic", false);
1240             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1241             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1242             //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);
1243             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1244             /* fixme: Cannot we cascade it to root more clearly? */
1245             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), desktop);
1247             dc->segments = g_slist_prepend(dc->segments, cbp);
1248         }
1250         dc->point1[0] = dc->point1[dc->npoints - 1];
1251         dc->point2[0] = dc->point2[dc->npoints - 1];
1252         dc->npoints = 1;
1253     } else {
1254         draw_temporary_box(dc);
1255     }
1258 static void
1259 draw_temporary_box(SPDynaDrawContext *dc)
1261     dc->currentcurve->reset();
1263     dc->currentcurve->moveto(dc->point2[dc->npoints-1]);
1264     for (gint i = dc->npoints-2; i >= 0; i--) {
1265         dc->currentcurve->lineto(dc->point2[i]);
1266     }
1267     for (gint i = 0; i < dc->npoints; i++) {
1268         dc->currentcurve->lineto(dc->point1[i]);
1269     }
1271     if (dc->npoints >= 2) {
1272         add_cap(dc->currentcurve, dc->point1[dc->npoints-1], dc->point2[dc->npoints-1], dc->cap_rounding);
1273     }
1275     dc->currentcurve->closepath();
1276     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1279 /*
1280   Local Variables:
1281   mode:c++
1282   c-file-style:"stroustrup"
1283   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1284   indent-tabs-mode:nil
1285   fill-column:99
1286   End:
1287 */
1288 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :