Code

f8748558d0bea7cab9170344cce6c9697594711e
[inkscape.git] / src / eraser-context.cpp
1 /*
2  * Eraser drawing mode
3  *
4  * Authors:
5  *   Mitsuru Oka <oka326@parkcity.ne.jp>
6  *   Lauris Kaplinski <lauris@kaplinski.com>
7  *   bulia byak <buliabyak@users.sf.net>
8  *   MenTaLguY <mental@rydia.net>
9  *   Jon A. Cruz <jon@joncruz.org>
10  *
11  * The original dynadraw code:
12  *   Paul Haeberli <paul@sgi.com>
13  *
14  * Copyright (C) 1998 The Free Software Foundation
15  * Copyright (C) 1999-2005 authors
16  * Copyright (C) 2001-2002 Ximian, Inc.
17  * Copyright (C) 2005-2007 bulia byak
18  * Copyright (C) 2006 MenTaLguY
19  * Copyright (C) 2008 Jon A. Cruz
20  *
21  * Released under GNU GPL, read the file 'COPYING' for more information
22  */
24 #define noERASER_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"
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-eraser.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 "xml/repr.h"
56 #include "context-fns.h"
57 #include "sp-item.h"
58 #include "inkscape.h"
59 #include "color.h"
60 #include "splivarot.h"
61 #include "sp-item-group.h"
62 #include "sp-shape.h"
63 #include "sp-path.h"
64 #include "sp-text.h"
65 #include "display/canvas-bpath.h"
66 #include "display/canvas-arena.h"
67 #include "livarot/Shape.h"
68 #include "isnan.h"
70 #include "eraser-context.h"
72 #define ERC_RED_RGBA 0xff0000ff
74 #define TOLERANCE_ERASER 0.1
76 #define ERASER_EPSILON 0.5e-6
77 #define ERASER_EPSILON_START 0.5e-2
78 #define ERASER_VEL_START 1e-5
80 #define DRAG_MIN 0.0
81 #define DRAG_DEFAULT 1.0
82 #define DRAG_MAX 1.0
85 static void sp_eraser_context_class_init(SPEraserContextClass *klass);
86 static void sp_eraser_context_init(SPEraserContext *erc);
87 static void sp_eraser_context_dispose(GObject *object);
89 static void sp_eraser_context_setup(SPEventContext *ec);
90 static void sp_eraser_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
91 static gint sp_eraser_context_root_handler(SPEventContext *ec, GdkEvent *event);
93 static void clear_current(SPEraserContext *dc);
94 static void set_to_accumulated(SPEraserContext *dc);
95 static void add_cap(SPCurve *curve, NR::Point const &pre, NR::Point const &from, NR::Point const &to, NR::Point const &post, double rounding);
96 static void accumulate_eraser(SPEraserContext *dc);
98 static void fit_and_split(SPEraserContext *erc, gboolean release);
100 static void sp_eraser_reset(SPEraserContext *erc, NR::Point p);
101 static NR::Point sp_eraser_get_npoint(SPEraserContext const *erc, NR::Point v);
102 static NR::Point sp_eraser_get_vpoint(SPEraserContext const *erc, NR::Point n);
103 static void draw_temporary_box(SPEraserContext *dc);
106 static SPEventContextClass *parent_class;
108 GtkType
109 sp_eraser_context_get_type(void)
111     static GType type = 0;
112     if (!type) {
113         GTypeInfo info = {
114             sizeof(SPEraserContextClass),
115             NULL, NULL,
116             (GClassInitFunc) sp_eraser_context_class_init,
117             NULL, NULL,
118             sizeof(SPEraserContext),
119             4,
120             (GInstanceInitFunc) sp_eraser_context_init,
121             NULL,   /* value_table */
122         };
123         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPEraserContext", &info, (GTypeFlags)0);
124     }
125     return type;
128 static void
129 sp_eraser_context_class_init(SPEraserContextClass *klass)
131     GObjectClass *object_class = (GObjectClass *) klass;
132     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
134     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
136     object_class->dispose = sp_eraser_context_dispose;
138     event_context_class->setup = sp_eraser_context_setup;
139     event_context_class->set = sp_eraser_context_set;
140     event_context_class->root_handler = sp_eraser_context_root_handler;
143 static void
144 sp_eraser_context_init(SPEraserContext *erc)
146     SPEventContext *event_context = SP_EVENT_CONTEXT(erc);
148     event_context->cursor_shape = cursor_eraser_xpm;
149     event_context->hot_x = 4;
150     event_context->hot_y = 4;
152     erc->accumulated = NULL;
153     erc->segments = NULL;
154     erc->currentcurve = NULL;
155     erc->currentshape = NULL;
156     erc->npoints = 0;
157     erc->cal1 = NULL;
158     erc->cal2 = NULL;
159     erc->repr = NULL;
161     /* Eraser values */
162     erc->cur = NR::Point(0,0);
163     erc->last = NR::Point(0,0);
164     erc->vel = NR::Point(0,0);
165     erc->vel_max = 0;
166     erc->acc = NR::Point(0,0);
167     erc->ang = NR::Point(0,0);
168     erc->del = NR::Point(0,0);
170     /* attributes */
171     erc->dragging = FALSE;
173     erc->mass = 0.3;
174     erc->drag = DRAG_DEFAULT;
175     erc->angle = 30.0;
176     erc->width = 0.2;
177     erc->pressure = ERC_DEFAULT_PRESSURE;
179     erc->vel_thin = 0.1;
180     erc->flatness = 0.9;
181     erc->cap_rounding = 0.0;
183     erc->abs_width = false;
186 static void
187 sp_eraser_context_dispose(GObject *object)
189     SPEraserContext *erc = SP_ERASER_CONTEXT(object);
191     if (erc->accumulated) {
192         erc->accumulated = sp_curve_unref(erc->accumulated);
193     }
195     while (erc->segments) {
196         gtk_object_destroy(GTK_OBJECT(erc->segments->data));
197         erc->segments = g_slist_remove(erc->segments, erc->segments->data);
198     }
200     if (erc->currentcurve) erc->currentcurve = sp_curve_unref(erc->currentcurve);
201     if (erc->cal1) erc->cal1 = sp_curve_unref(erc->cal1);
202     if (erc->cal2) erc->cal2 = sp_curve_unref(erc->cal2);
204     if (erc->currentshape) {
205         gtk_object_destroy(GTK_OBJECT(erc->currentshape));
206         erc->currentshape = NULL;
207     }
209     if (erc->_message_context) {
210         delete erc->_message_context;
211     }
213     G_OBJECT_CLASS(parent_class)->dispose(object);
216 static void
217 sp_eraser_context_setup(SPEventContext *ec)
219     SPEraserContext *erc = SP_ERASER_CONTEXT(ec);
221     if (((SPEventContextClass *) parent_class)->setup)
222         ((SPEventContextClass *) parent_class)->setup(ec);
224     erc->accumulated = sp_curve_new_sized(32);
225     erc->currentcurve = sp_curve_new_sized(4);
227     erc->cal1 = sp_curve_new_sized(32);
228     erc->cal2 = sp_curve_new_sized(32);
230     erc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
231     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(erc->currentshape), ERC_RED_RGBA, SP_WIND_RULE_EVENODD);
232     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(erc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
233     /* fixme: Cannot we cascade it to root more clearly? */
234     g_signal_connect(G_OBJECT(erc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
236 /*
237 static ProfileFloatElement f_profile[PROFILE_FLOAT_SIZE] = {
238     {"mass",0.02, 0.0, 1.0},
239     {"wiggle",0.0, 0.0, 1.0},
240     {"angle",30.0, -90.0, 90.0},
241     {"thinning",0.1, -1.0, 1.0},
242     {"tremor",0.0, 0.0, 1.0},
243     {"flatness",0.9, 0.0, 1.0},
244     {"cap_rounding",0.0, 0.0, 5.0}
245 };
246 */
248     sp_event_context_read(ec, "mass");
249     sp_event_context_read(ec, "wiggle");
250     sp_event_context_read(ec, "angle");
251     sp_event_context_read(ec, "width");
252     sp_event_context_read(ec, "thinning");
253     sp_event_context_read(ec, "tremor");
254     sp_event_context_read(ec, "flatness");
255     sp_event_context_read(ec, "tracebackground");
256     sp_event_context_read(ec, "usepressure");
257     sp_event_context_read(ec, "usetilt");
258     sp_event_context_read(ec, "abs_width");
259     sp_event_context_read(ec, "cap_rounding");
261     erc->is_drawing = false;
263     erc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
265     if (prefs_get_int_attribute("tools.eraser", "selcue", 0) != 0) {
266         ec->enableSelectionCue();
267     }
268 // TODO temp force:
269     ec->enableSelectionCue();
273 static void
274 sp_eraser_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
276     SPEraserContext *erc = SP_ERASER_CONTEXT(ec);
278     if (!strcmp(key, "mass")) {
279         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
280         erc->mass = CLAMP(dval, -1000.0, 1000.0);
281     } else if (!strcmp(key, "wiggle")) {
282         double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
283         erc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
284     } else if (!strcmp(key, "angle")) {
285         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
286         erc->angle = CLAMP (dval, -90, 90);
287     } else if (!strcmp(key, "width")) {
288         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
289         erc->width = CLAMP(dval, -1000.0, 1000.0);
290     } else if (!strcmp(key, "thinning")) {
291         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
292         erc->vel_thin = CLAMP(dval, -1.0, 1.0);
293     } else if (!strcmp(key, "tremor")) {
294         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
295         erc->tremor = CLAMP(dval, 0.0, 1.0);
296     } else if (!strcmp(key, "flatness")) {
297         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
298         erc->flatness = CLAMP(dval, 0, 1.0);
299     } else if (!strcmp(key, "usepressure")) {
300         erc->usepressure = (val && strcmp(val, "0"));
301     } else if (!strcmp(key, "usetilt")) {
302         erc->usetilt = (val && strcmp(val, "0"));
303     } else if (!strcmp(key, "abs_width")) {
304         erc->abs_width = (val && strcmp(val, "0"));
305     } else if (!strcmp(key, "cap_rounding")) {
306         erc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
307     }
309     //g_print("ERC: %g %g %g %g\n", erc->mass, erc->drag, erc->angle, erc->width);
312 static double
313 flerp(double f0, double f1, double p)
315     return f0 + ( f1 - f0 ) * p;
318 /* Get normalized point */
319 static NR::Point
320 sp_eraser_get_npoint(SPEraserContext const *dc, NR::Point v)
322     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
323     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
324     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
327 /* Get view point */
328 static NR::Point
329 sp_eraser_get_vpoint(SPEraserContext const *dc, NR::Point n)
331     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
332     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
333     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
336 static void
337 sp_eraser_reset(SPEraserContext *dc, NR::Point p)
339     dc->last = dc->cur = sp_eraser_get_npoint(dc, p);
340     dc->vel = NR::Point(0,0);
341     dc->vel_max = 0;
342     dc->acc = NR::Point(0,0);
343     dc->ang = NR::Point(0,0);
344     dc->del = NR::Point(0,0);
347 static void
348 sp_eraser_extinput(SPEraserContext *dc, GdkEvent *event)
350     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
351         dc->pressure = CLAMP (dc->pressure, ERC_MIN_PRESSURE, ERC_MAX_PRESSURE);
352     else
353         dc->pressure = ERC_DEFAULT_PRESSURE;
355     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
356         dc->xtilt = CLAMP (dc->xtilt, ERC_MIN_TILT, ERC_MAX_TILT);
357     else
358         dc->xtilt = ERC_DEFAULT_TILT;
360     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
361         dc->ytilt = CLAMP (dc->ytilt, ERC_MIN_TILT, ERC_MAX_TILT);
362     else
363         dc->ytilt = ERC_DEFAULT_TILT;
367 static gboolean
368 sp_eraser_apply(SPEraserContext *dc, NR::Point p)
370     NR::Point n = sp_eraser_get_npoint(dc, p);
372     /* Calculate mass and drag */
373     double const mass = flerp(1.0, 160.0, dc->mass);
374     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
376     /* Calculate force and acceleration */
377     NR::Point force = n - dc->cur;
379     // If force is below the absolute threshold ERASER_EPSILON,
380     // or we haven't yet reached ERASER_VEL_START (i.e. at the beginning of stroke)
381     // _and_ the force is below the (higher) ERASER_EPSILON_START threshold,
382     // discard this move. 
383     // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
384     // especially bothersome at the start of the stroke where we don't yet have the inertia to
385     // smooth them out.
386     if ( NR::L2(force) < ERASER_EPSILON || (dc->vel_max < ERASER_VEL_START && NR::L2(force) < ERASER_EPSILON_START)) {
387         return FALSE;
388     }
390     dc->acc = force / mass;
392     /* Calculate new velocity */
393     dc->vel += dc->acc;
395     if (NR::L2(dc->vel) > dc->vel_max)
396         dc->vel_max = NR::L2(dc->vel);
398     /* Calculate angle of drawing tool */
400     double a1;
401     if (dc->usetilt) {
402         // 1a. calculate nib angle from input device tilt:
403         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
405         if (length > 0) {
406             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
407             a1 = atan2(ang1);
408         }
409         else
410             a1 = 0.0;
411     }
412     else {
413         // 1b. fixed dc->angle (absolutely flat nib):
414         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
415         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
416         a1 = atan2(ang1);
417     }
419     // 2. perpendicular to dc->vel (absolutely non-flat nib):
420     gdouble const mag_vel = NR::L2(dc->vel);
421     if ( mag_vel < ERASER_EPSILON ) {
422         return FALSE;
423     }
424     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
426     // 3. Average them using flatness parameter:
427     // calculate angles
428     double a2 = atan2(ang2);
429     // flip a2 to force it to be in the same half-circle as a1
430     bool flipped = false;
431     if (fabs (a2-a1) > 0.5*M_PI) {
432         a2 += M_PI;
433         flipped = true;
434     }
435     // normalize a2
436     if (a2 > M_PI)
437         a2 -= 2*M_PI;
438     if (a2 < -M_PI)
439         a2 += 2*M_PI;
440     // find the flatness-weighted bisector angle, unflip if a2 was flipped
441     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
442     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
444     // Try to detect a sudden flip when the new angle differs too much from the previous for the
445     // current velocity; in that case discard this move
446     double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
447     if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
448         return FALSE;
449     }
451     // convert to point
452     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
454 //    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);
456     /* Apply drag */
457     dc->vel *= 1.0 - drag;
459     /* Update position */
460     dc->last = dc->cur;
461     dc->cur += dc->vel;
463     return TRUE;
466 static void
467 sp_eraser_brush(SPEraserContext *dc)
469     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
471     // How much velocity thins strokestyle
472     double vel_thin = flerp (0, 160, dc->vel_thin);
474     // Influence of pressure on thickness
475     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
477     // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
478     // drag)
479     NR::Point brush = sp_eraser_get_vpoint(dc, dc->cur);
480     NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush); 
482     double trace_thick = 1;
484     double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
486     double tremble_left = 0, tremble_right = 0;
487     if (dc->tremor > 0) {
488         // obtain two normally distributed random variables, using polar Box-Muller transform
489         double x1, x2, w, y1, y2;
490         do {
491             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
492             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
493             w = x1 * x1 + x2 * x2;
494         } while ( w >= 1.0 );
495         w = sqrt( (-2.0 * log( w ) ) / w );
496         y1 = x1 * w;
497         y2 = x2 * w;
499         // deflect both left and right edges randomly and independently, so that:
500         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
501         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
502         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
503         // comparatively smooth and slow ones excessively jittery
504         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
505         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
506     }
508     if ( width < 0.02 * dc->width ) {
509         width = 0.02 * dc->width;
510     }
512     double dezoomify_factor = 0.05 * 1000;
513     if (!dc->abs_width) {
514         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
515     }
517     NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
518     NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
520     dc->point1[dc->npoints] = brush + del_left;
521     dc->point2[dc->npoints] = brush - del_right;
523     dc->del = 0.5*(del_left + del_right);
525     dc->npoints++;
528 void
529 sp_erc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
531     desktop->setToolboxAdjustmentValue (id, value);
534 static void
535 eraser_cancel(SPEraserContext *dc)
537     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
538     dc->dragging = FALSE;
539     dc->is_drawing = false;
540     sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
541             /* Remove all temporary line segments */
542             while (dc->segments) {
543                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
544                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
545             }
546             /* reset accumulated curve */
547             sp_curve_reset(dc->accumulated);
548             clear_current(dc);
549             if (dc->repr) {
550                 dc->repr = NULL;
551             }
555 gint
556 sp_eraser_context_root_handler(SPEventContext *event_context,
557                                   GdkEvent *event)
559     SPEraserContext *dc = SP_ERASER_CONTEXT(event_context);
560     SPDesktop *desktop = event_context->desktop;
562     gint ret = FALSE;
564     switch (event->type) {
565         case GDK_BUTTON_PRESS:
566             if (event->button.button == 1 && !event_context->space_panning) {
568                 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
570                 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
571                     return TRUE;
572                 }
574                 NR::Point const button_w(event->button.x,
575                                          event->button.y);
576                 NR::Point const button_dt(desktop->w2d(button_w));
577                 sp_eraser_reset(dc, button_dt);
578                 sp_eraser_extinput(dc, event);
579                 sp_eraser_apply(dc, button_dt);
580                 sp_curve_reset(dc->accumulated);
581                 if (dc->repr) {
582                     dc->repr = NULL;
583                 }
585                 /* initialize first point */
586                 dc->npoints = 0;
588                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
589                                     ( GDK_KEY_PRESS_MASK |
590                                       GDK_BUTTON_RELEASE_MASK |
591                                       GDK_POINTER_MOTION_MASK |
592                                       GDK_BUTTON_PRESS_MASK ),
593                                     NULL,
594                                     event->button.time);
596                 ret = TRUE;
598                 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
599                 dc->is_drawing = true;
600             }
601             break;
602         case GDK_MOTION_NOTIFY:
603         {
604             NR::Point const motion_w(event->motion.x,
605                                      event->motion.y);
606             NR::Point motion_dt(desktop->w2d(motion_w));
607             sp_eraser_extinput(dc, event);
609             dc->_message_context->clear();
611             if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
612                 dc->dragging = TRUE;
614                 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a eraser stroke"));
616                 if (!sp_eraser_apply(dc, motion_dt)) {
617                     ret = TRUE;
618                     break;
619                 }
621                 if ( dc->cur != dc->last ) {
622                     sp_eraser_brush(dc);
623                     g_assert( dc->npoints > 0 );
624                     fit_and_split(dc, FALSE);
625                 }
626                 ret = TRUE;
627             }
628         }
629         break;
632     case GDK_BUTTON_RELEASE:
633     {
634         NR::Point const motion_w(event->button.x, event->button.y);
635         NR::Point const motion_dt(desktop->w2d(motion_w));
637         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
638         sp_canvas_end_forced_full_redraws(desktop->canvas);
639         dc->is_drawing = false;
641         if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
642             dc->dragging = FALSE;
644             sp_eraser_apply(dc, motion_dt);
646             /* Remove all temporary line segments */
647             while (dc->segments) {
648                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
649                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
650             }
652             /* Create object */
653             fit_and_split(dc, TRUE);
654             accumulate_eraser(dc);
655             set_to_accumulated(dc); // performs document_done
657             /* reset accumulated curve */
658             sp_curve_reset(dc->accumulated);
660             clear_current(dc);
661             if (dc->repr) {
662                 dc->repr = NULL;
663             }
665             dc->_message_context->clear();
666             ret = TRUE;
667         }
668         break;
669     }
671     case GDK_KEY_PRESS:
672         switch (get_group0_keyval (&event->key)) {
673         case GDK_Up:
674         case GDK_KP_Up:
675             if (!MOD__CTRL_ONLY) {
676                 dc->angle += 5.0;
677                 if (dc->angle > 90.0)
678                     dc->angle = 90.0;
679                 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
680                 ret = TRUE;
681             }
682             break;
683         case GDK_Down:
684         case GDK_KP_Down:
685             if (!MOD__CTRL_ONLY) {
686                 dc->angle -= 5.0;
687                 if (dc->angle < -90.0)
688                     dc->angle = -90.0;
689                 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
690                 ret = TRUE;
691             }
692             break;
693         case GDK_Right:
694         case GDK_KP_Right:
695             if (!MOD__CTRL_ONLY) {
696                 dc->width += 0.01;
697                 if (dc->width > 1.0)
698                     dc->width = 1.0;
699                 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100); // the same spinbutton is for alt+x
700                 ret = TRUE;
701             }
702             break;
703         case GDK_Left:
704         case GDK_KP_Left:
705             if (!MOD__CTRL_ONLY) {
706                 dc->width -= 0.01;
707                 if (dc->width < 0.01)
708                     dc->width = 0.01;
709                 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
710                 ret = TRUE;
711             }
712             break;
713         case GDK_Home:
714         case GDK_KP_Home:
715             dc->width = 0.01;
716             sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
717             ret = TRUE;
718             break;
719         case GDK_End:
720         case GDK_KP_End:
721             dc->width = 1.0;
722             sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
723             ret = TRUE;
724             break;
725         case GDK_x:
726         case GDK_X:
727             if (MOD__ALT_ONLY) {
728                 desktop->setToolboxFocusTo ("altx-eraser");
729                 ret = TRUE;
730             }
731             break;
732         case GDK_Escape:
733             if (dc->is_drawing) {
734                 // if drawing, cancel, otherwise pass it up for deselecting
735                 eraser_cancel (dc);
736                 ret = TRUE;
737             }
738             break;
739         case GDK_z:
740         case GDK_Z:
741             if (MOD__CTRL_ONLY && dc->is_drawing) {
742                 // if drawing, cancel, otherwise pass it up for undo
743                 eraser_cancel (dc);
744                 ret = TRUE;
745             }
746             break;
747         default:
748             break;
749         }
750         break;
752     case GDK_KEY_RELEASE:
753         switch (get_group0_keyval(&event->key)) {
754             case GDK_Control_L:
755             case GDK_Control_R:
756                 dc->_message_context->clear();
757                 break;
758             default:
759                 break;
760         }
762     default:
763         break;
764     }
766     if (!ret) {
767         if (((SPEventContextClass *) parent_class)->root_handler) {
768             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
769         }
770     }
772     return ret;
776 static void
777 clear_current(SPEraserContext *dc)
779     /* reset bpath */
780     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
781     /* reset curve */
782     sp_curve_reset(dc->currentcurve);
783     sp_curve_reset(dc->cal1);
784     sp_curve_reset(dc->cal2);
785     /* reset points */
786     dc->npoints = 0;
789 static void
790 set_to_accumulated(SPEraserContext *dc)
792     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
794     if (!sp_curve_empty(dc->accumulated)) {
795         NArtBpath *abp;
796         gchar *str;
798         if (!dc->repr) {
799             /* Create object */
800             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
801             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
803             /* Set style */
804             sp_desktop_apply_style_tool (desktop, repr, "tools.eraser", false);
806             dc->repr = repr;
808             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
809             Inkscape::GC::release(dc->repr);
810             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
811             item->updateRepr();
812         }
813         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
814         str = sp_svg_write_path(abp);
815         g_assert( str != NULL );
816         g_free(abp);
817         dc->repr->setAttribute("d", str);
818         g_free(str);
820         if ( dc->repr ) {
821             Inkscape::Selection *selection = sp_desktop_selection(desktop);
822             gint eraserMode = (prefs_get_int_attribute("tools.eraser", "mode", 0) != 0) ? 1 : 0;
823             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
824             if (!selection->isEmpty()) {
825                 // Do selection-limited
826                 if ( eraserMode == 0 ) {
827                     // Nuke
828                 } else {
829                     // Cut-out
830                     std::vector<SPItem*> putBacks;
831                     GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
832                     for (GSList const *i = selected ; i ; i = i->next ) {
833                         SPItem *item = SP_ITEM(i->data);
834                         Inkscape::XML::Node* dup = dc->repr->duplicate(xml_doc);
835                         dc->repr->parent()->appendChild(dup);
836                         Inkscape::GC::release(dup);
838                         selection->set(item);
839                         selection->add(dup);
840                         sp_selected_path_diff();
841                         if ( !selection->isEmpty() ) {
842                             // If the item was not completely erased, add it back to the selection.
843                             GSList const *selected2 = g_slist_copy(const_cast<GSList *>(selection->itemList()));
844                             for (GSList const *i2 = selected2 ; i2 ; i2 = i2->next ) {
845                                 putBacks.push_back(SP_ITEM(i2->data));
846                             }
847                         }
848                     }
849                     g_slist_free ((GSList *) selected);
851                     selection->clear();
852                     selection->add(putBacks.begin(), putBacks.end());
853                 }
854             } else {
855                 // TODO finish
856             }
859             // Remove the eraser stroke itself:
860             sp_repr_unparent( dc->repr );
861             dc->repr = 0;
862         }
863 //         SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
864 //         sp_object_unref((SPObject *)item, NULL);
865     } else {
866         if (dc->repr) {
867             sp_repr_unparent(dc->repr);
868             dc->repr = 0;
869         }
870     }
872     sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_ERASER, 
873                      _("Draw eraser stroke"));
876 static void
877 add_cap(SPCurve *curve,
878         NR::Point const &pre, NR::Point const &from,
879         NR::Point const &to, NR::Point const &post,
880         double rounding)
882     NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
883     double mag = NR::L2(vel);
885     NR::Point v_in = from - pre;
886     double mag_in = NR::L2(v_in);
887     if ( mag_in > ERASER_EPSILON ) {
888         v_in = mag * v_in / mag_in;
889     } else {
890         v_in = NR::Point(0, 0);
891     }
893     NR::Point v_out = to - post;
894     double mag_out = NR::L2(v_out);
895     if ( mag_out > ERASER_EPSILON ) {
896         v_out = mag * v_out / mag_out;
897     } else {
898         v_out = NR::Point(0, 0);
899     }
901     if ( NR::L2(v_in) > ERASER_EPSILON || NR::L2(v_out) > ERASER_EPSILON ) {
902         sp_curve_curveto(curve, from + v_in, to + v_out, to);
903     }
906 static void
907 accumulate_eraser(SPEraserContext *dc)
909     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
910         sp_curve_reset(dc->accumulated); /*  Is this required ?? */
911         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
913         g_assert(dc->cal1->end > 1);
914         g_assert(rev_cal2->end > 1);
915         g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
916         g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
917         g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
918         g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
919         g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
920         g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
922         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
924         add_cap(dc->accumulated, SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->c(2), SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->c(3), SP_CURVE_SEGMENT(rev_cal2, 0)->c(3), SP_CURVE_SEGMENT(rev_cal2, 1)->c(1), dc->cap_rounding);
926         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
928         add_cap(dc->accumulated, SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->c(2), SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->c(3), SP_CURVE_SEGMENT(dc->cal1, 0)->c(3), SP_CURVE_SEGMENT(dc->cal1, 1)->c(1), dc->cap_rounding);
930         sp_curve_closepath(dc->accumulated);
932         sp_curve_unref(rev_cal2);
934         sp_curve_reset(dc->cal1);
935         sp_curve_reset(dc->cal2);
936     }
939 static double square(double const x)
941     return x * x;
944 static void
945 fit_and_split(SPEraserContext *dc, gboolean release)
947     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_ERASER );
949 #ifdef ERASER_VERBOSE
950     g_print("[F&S:R=%c]", release?'T':'F');
951 #endif
953     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
954         return; // just clicked
956     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
957 #define BEZIER_SIZE       4
958 #define BEZIER_MAX_BEZIERS  8
959 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
961 #ifdef ERASER_VERBOSE
962         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
963                 dc->npoints, release ? "TRUE" : "FALSE");
964 #endif
966         /* Current eraser */
967         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
968             /* dc->npoints > 0 */
969             /* g_print("erasers(1|2) reset\n"); */
970             sp_curve_reset(dc->cal1);
971             sp_curve_reset(dc->cal2);
973             sp_curve_moveto(dc->cal1, dc->point1[0]);
974             sp_curve_moveto(dc->cal2, dc->point2[0]);
975         }
977         NR::Point b1[BEZIER_MAX_LENGTH];
978         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
979                                                tolerance_sq, BEZIER_MAX_BEZIERS);
980         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
982         NR::Point b2[BEZIER_MAX_LENGTH];
983         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
984                                                tolerance_sq, BEZIER_MAX_BEZIERS);
985         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
987         if ( nb1 != -1 && nb2 != -1 ) {
988             /* Fit and draw and reset state */
989 #ifdef ERASER_VERBOSE
990             g_print("nb1:%d nb2:%d\n", nb1, nb2);
991 #endif
992             /* CanvasShape */
993             if (! release) {
994                 sp_curve_reset(dc->currentcurve);
995                 sp_curve_moveto(dc->currentcurve, b1[0]);
996                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
997                     sp_curve_curveto(dc->currentcurve, bp1[1],
998                                      bp1[2], bp1[3]);
999                 }
1000                 sp_curve_lineto(dc->currentcurve,
1001                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
1002                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1003                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
1004                 }
1005                 // FIXME: dc->segments is always NULL at this point??
1006                 if (!dc->segments) { // first segment
1007                     add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
1008                 }
1009                 sp_curve_closepath(dc->currentcurve);
1010                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1011             }
1013             /* Current eraser */
1014             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1015                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
1016             }
1017             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1018                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
1019             }
1020         } else {
1021             /* fixme: ??? */
1022 #ifdef ERASER_VERBOSE
1023             g_print("[fit_and_split] failed to fit-cubic.\n");
1024 #endif
1025             draw_temporary_box(dc);
1027             for (gint i = 1; i < dc->npoints; i++) {
1028                 sp_curve_lineto(dc->cal1, dc->point1[i]);
1029             }
1030             for (gint i = 1; i < dc->npoints; i++) {
1031                 sp_curve_lineto(dc->cal2, dc->point2[i]);
1032             }
1033         }
1035         /* Fit and draw and copy last point */
1036 #ifdef ERASER_VERBOSE
1037         g_print("[%d]Yup\n", dc->npoints);
1038 #endif
1039         if (!release) {
1040             g_assert(!sp_curve_empty(dc->currentcurve));
1042             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1043                                                    SP_TYPE_CANVAS_BPATH,
1044                                                    NULL);
1045             SPCurve *curve = sp_curve_copy(dc->currentcurve);
1046             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1047             sp_curve_unref(curve);
1049             guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.eraser", true);
1050             //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.eraser", false);
1051             double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser");
1052             double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser", true);
1053             //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser", false);
1054             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1055             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1056             //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);
1057             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1058             /* fixme: Cannot we cascade it to root more clearly? */
1059             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1061             dc->segments = g_slist_prepend(dc->segments, cbp);
1062         }
1064         dc->point1[0] = dc->point1[dc->npoints - 1];
1065         dc->point2[0] = dc->point2[dc->npoints - 1];
1066         dc->npoints = 1;
1067     } else {
1068         draw_temporary_box(dc);
1069     }
1072 static void
1073 draw_temporary_box(SPEraserContext *dc)
1075     sp_curve_reset(dc->currentcurve);
1077     sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
1078     for (gint i = dc->npoints-2; i >= 0; i--) {
1079         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
1080     }
1081     for (gint i = 0; i < dc->npoints; i++) {
1082         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
1083     }
1084     if (dc->npoints >= 2) {
1085         add_cap(dc->currentcurve, dc->point2[dc->npoints-2], dc->point2[dc->npoints-1], dc->point1[dc->npoints-1], dc->point1[dc->npoints-2], dc->cap_rounding);
1086     }
1088     sp_curve_closepath(dc->currentcurve);
1089     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1092 /*
1093   Local Variables:
1094   mode:c++
1095   c-file-style:"stroustrup"
1096   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1097   indent-tabs-mode:nil
1098   fill-column:99
1099   End:
1100 */
1101 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :