Code

Reduce undo history items when nothing is selected
[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;
793     bool workDone = false;
795     if (!sp_curve_empty(dc->accumulated)) {
796         NArtBpath *abp;
797         gchar *str;
799         if (!dc->repr) {
800             /* Create object */
801             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
802             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
804             /* Set style */
805             sp_desktop_apply_style_tool (desktop, repr, "tools.eraser", false);
807             dc->repr = repr;
809             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
810             Inkscape::GC::release(dc->repr);
811             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
812             item->updateRepr();
813         }
814         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
815         str = sp_svg_write_path(abp);
816         g_assert( str != NULL );
817         g_free(abp);
818         dc->repr->setAttribute("d", str);
819         g_free(str);
821         if ( dc->repr ) {
822             Inkscape::Selection *selection = sp_desktop_selection(desktop);
823             gint eraserMode = (prefs_get_int_attribute("tools.eraser", "mode", 0) != 0) ? 1 : 0;
824             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
825             if (!selection->isEmpty()) {
826                 // Do selection-limited
827                 if ( eraserMode == 0 ) {
828                     // Nuke
829                 } else {
830                     // Cut-out
831                     std::vector<SPItem*> putBacks;
832                     GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
833                     for (GSList const *i = selected ; i ; i = i->next ) {
834                         SPItem *item = SP_ITEM(i->data);
835                         Inkscape::XML::Node* dup = dc->repr->duplicate(xml_doc);
836                         dc->repr->parent()->appendChild(dup);
837                         Inkscape::GC::release(dup);
839                         selection->set(item);
840                         selection->add(dup);
841                         sp_selected_path_diff_skip_undo();
842                         workDone = true; // TODO set this only if something was cut.
843                         if ( !selection->isEmpty() ) {
844                             // If the item was not completely erased, add it back to the selection.
845                             GSList const *selected2 = g_slist_copy(const_cast<GSList *>(selection->itemList()));
846                             for (GSList const *i2 = selected2 ; i2 ; i2 = i2->next ) {
847                                 putBacks.push_back(SP_ITEM(i2->data));
848                             }
849                         }
850                     }
851                     g_slist_free ((GSList *) selected);
853                     selection->clear();
854                     selection->add(putBacks.begin(), putBacks.end());
855                 }
856             } else {
857                 // TODO finish
858             }
861             // Remove the eraser stroke itself:
862             sp_repr_unparent( dc->repr );
863             dc->repr = 0;
864         }
865 //         SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
866 //         sp_object_unref((SPObject *)item, NULL);
867     } else {
868         if (dc->repr) {
869             sp_repr_unparent(dc->repr);
870             dc->repr = 0;
871         }
872     }
875     if ( workDone ) {
876         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_ERASER, 
877                          _("Draw eraser stroke"));
878     } else {
879         sp_document_cancel(sp_desktop_document(desktop));
880     }
883 static void
884 add_cap(SPCurve *curve,
885         NR::Point const &pre, NR::Point const &from,
886         NR::Point const &to, NR::Point const &post,
887         double rounding)
889     NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
890     double mag = NR::L2(vel);
892     NR::Point v_in = from - pre;
893     double mag_in = NR::L2(v_in);
894     if ( mag_in > ERASER_EPSILON ) {
895         v_in = mag * v_in / mag_in;
896     } else {
897         v_in = NR::Point(0, 0);
898     }
900     NR::Point v_out = to - post;
901     double mag_out = NR::L2(v_out);
902     if ( mag_out > ERASER_EPSILON ) {
903         v_out = mag * v_out / mag_out;
904     } else {
905         v_out = NR::Point(0, 0);
906     }
908     if ( NR::L2(v_in) > ERASER_EPSILON || NR::L2(v_out) > ERASER_EPSILON ) {
909         sp_curve_curveto(curve, from + v_in, to + v_out, to);
910     }
913 static void
914 accumulate_eraser(SPEraserContext *dc)
916     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
917         sp_curve_reset(dc->accumulated); /*  Is this required ?? */
918         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
920         g_assert(dc->cal1->end > 1);
921         g_assert(rev_cal2->end > 1);
922         g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
923         g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
924         g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
925         g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
926         g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
927         g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
929         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
931         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);
933         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
935         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);
937         sp_curve_closepath(dc->accumulated);
939         sp_curve_unref(rev_cal2);
941         sp_curve_reset(dc->cal1);
942         sp_curve_reset(dc->cal2);
943     }
946 static double square(double const x)
948     return x * x;
951 static void
952 fit_and_split(SPEraserContext *dc, gboolean release)
954     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_ERASER );
956 #ifdef ERASER_VERBOSE
957     g_print("[F&S:R=%c]", release?'T':'F');
958 #endif
960     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
961         return; // just clicked
963     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
964 #define BEZIER_SIZE       4
965 #define BEZIER_MAX_BEZIERS  8
966 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
968 #ifdef ERASER_VERBOSE
969         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
970                 dc->npoints, release ? "TRUE" : "FALSE");
971 #endif
973         /* Current eraser */
974         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
975             /* dc->npoints > 0 */
976             /* g_print("erasers(1|2) reset\n"); */
977             sp_curve_reset(dc->cal1);
978             sp_curve_reset(dc->cal2);
980             sp_curve_moveto(dc->cal1, dc->point1[0]);
981             sp_curve_moveto(dc->cal2, dc->point2[0]);
982         }
984         NR::Point b1[BEZIER_MAX_LENGTH];
985         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
986                                                tolerance_sq, BEZIER_MAX_BEZIERS);
987         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
989         NR::Point b2[BEZIER_MAX_LENGTH];
990         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
991                                                tolerance_sq, BEZIER_MAX_BEZIERS);
992         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
994         if ( nb1 != -1 && nb2 != -1 ) {
995             /* Fit and draw and reset state */
996 #ifdef ERASER_VERBOSE
997             g_print("nb1:%d nb2:%d\n", nb1, nb2);
998 #endif
999             /* CanvasShape */
1000             if (! release) {
1001                 sp_curve_reset(dc->currentcurve);
1002                 sp_curve_moveto(dc->currentcurve, b1[0]);
1003                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1004                     sp_curve_curveto(dc->currentcurve, bp1[1],
1005                                      bp1[2], bp1[3]);
1006                 }
1007                 sp_curve_lineto(dc->currentcurve,
1008                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
1009                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1010                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
1011                 }
1012                 // FIXME: dc->segments is always NULL at this point??
1013                 if (!dc->segments) { // first segment
1014                     add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
1015                 }
1016                 sp_curve_closepath(dc->currentcurve);
1017                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1018             }
1020             /* Current eraser */
1021             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1022                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
1023             }
1024             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1025                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
1026             }
1027         } else {
1028             /* fixme: ??? */
1029 #ifdef ERASER_VERBOSE
1030             g_print("[fit_and_split] failed to fit-cubic.\n");
1031 #endif
1032             draw_temporary_box(dc);
1034             for (gint i = 1; i < dc->npoints; i++) {
1035                 sp_curve_lineto(dc->cal1, dc->point1[i]);
1036             }
1037             for (gint i = 1; i < dc->npoints; i++) {
1038                 sp_curve_lineto(dc->cal2, dc->point2[i]);
1039             }
1040         }
1042         /* Fit and draw and copy last point */
1043 #ifdef ERASER_VERBOSE
1044         g_print("[%d]Yup\n", dc->npoints);
1045 #endif
1046         if (!release) {
1047             g_assert(!sp_curve_empty(dc->currentcurve));
1049             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1050                                                    SP_TYPE_CANVAS_BPATH,
1051                                                    NULL);
1052             SPCurve *curve = sp_curve_copy(dc->currentcurve);
1053             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1054             sp_curve_unref(curve);
1056             guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.eraser", true);
1057             //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.eraser", false);
1058             double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser");
1059             double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser", true);
1060             //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser", false);
1061             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1062             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1063             //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);
1064             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1065             /* fixme: Cannot we cascade it to root more clearly? */
1066             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1068             dc->segments = g_slist_prepend(dc->segments, cbp);
1069         }
1071         dc->point1[0] = dc->point1[dc->npoints - 1];
1072         dc->point2[0] = dc->point2[dc->npoints - 1];
1073         dc->npoints = 1;
1074     } else {
1075         draw_temporary_box(dc);
1076     }
1079 static void
1080 draw_temporary_box(SPEraserContext *dc)
1082     sp_curve_reset(dc->currentcurve);
1084     sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
1085     for (gint i = dc->npoints-2; i >= 0; i--) {
1086         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
1087     }
1088     for (gint i = 0; i < dc->npoints; i++) {
1089         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
1090     }
1091     if (dc->npoints >= 2) {
1092         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);
1093     }
1095     sp_curve_closepath(dc->currentcurve);
1096     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1099 /*
1100   Local Variables:
1101   mode:c++
1102   c-file-style:"stroustrup"
1103   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1104   indent-tabs-mode:nil
1105   fill-column:99
1106   End:
1107 */
1108 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :