Code

Initial cut of touch-delete mode
[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 "rubberband.h"
61 #include "splivarot.h"
62 #include "sp-item-group.h"
63 #include "sp-shape.h"
64 #include "sp-path.h"
65 #include "sp-text.h"
66 #include "display/canvas-bpath.h"
67 #include "display/canvas-arena.h"
68 #include "livarot/Shape.h"
69 #include "isnan.h"
71 #include "eraser-context.h"
73 #define ERC_RED_RGBA 0xff0000ff
75 #define TOLERANCE_ERASER 0.1
77 #define ERASER_EPSILON 0.5e-6
78 #define ERASER_EPSILON_START 0.5e-2
79 #define ERASER_VEL_START 1e-5
81 #define DRAG_MIN 0.0
82 #define DRAG_DEFAULT 1.0
83 #define DRAG_MAX 1.0
86 static void sp_eraser_context_class_init(SPEraserContextClass *klass);
87 static void sp_eraser_context_init(SPEraserContext *erc);
88 static void sp_eraser_context_dispose(GObject *object);
90 static void sp_eraser_context_setup(SPEventContext *ec);
91 static void sp_eraser_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
92 static gint sp_eraser_context_root_handler(SPEventContext *ec, GdkEvent *event);
94 static void clear_current(SPEraserContext *dc);
95 static void set_to_accumulated(SPEraserContext *dc);
96 static void add_cap(SPCurve *curve, NR::Point const &pre, NR::Point const &from, NR::Point const &to, NR::Point const &post, double rounding);
97 static void accumulate_eraser(SPEraserContext *dc);
99 static void fit_and_split(SPEraserContext *erc, gboolean release);
101 static void sp_eraser_reset(SPEraserContext *erc, NR::Point p);
102 static NR::Point sp_eraser_get_npoint(SPEraserContext const *erc, NR::Point v);
103 static NR::Point sp_eraser_get_vpoint(SPEraserContext const *erc, NR::Point n);
104 static void draw_temporary_box(SPEraserContext *dc);
107 static SPEventContextClass *parent_class;
109 GtkType
110 sp_eraser_context_get_type(void)
112     static GType type = 0;
113     if (!type) {
114         GTypeInfo info = {
115             sizeof(SPEraserContextClass),
116             NULL, NULL,
117             (GClassInitFunc) sp_eraser_context_class_init,
118             NULL, NULL,
119             sizeof(SPEraserContext),
120             4,
121             (GInstanceInitFunc) sp_eraser_context_init,
122             NULL,   /* value_table */
123         };
124         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPEraserContext", &info, (GTypeFlags)0);
125     }
126     return type;
129 static void
130 sp_eraser_context_class_init(SPEraserContextClass *klass)
132     GObjectClass *object_class = (GObjectClass *) klass;
133     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
135     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
137     object_class->dispose = sp_eraser_context_dispose;
139     event_context_class->setup = sp_eraser_context_setup;
140     event_context_class->set = sp_eraser_context_set;
141     event_context_class->root_handler = sp_eraser_context_root_handler;
144 static void
145 sp_eraser_context_init(SPEraserContext *erc)
147     SPEventContext *event_context = SP_EVENT_CONTEXT(erc);
149     event_context->cursor_shape = cursor_eraser_xpm;
150     event_context->hot_x = 4;
151     event_context->hot_y = 4;
153     erc->accumulated = NULL;
154     erc->segments = NULL;
155     erc->currentcurve = NULL;
156     erc->currentshape = NULL;
157     erc->npoints = 0;
158     erc->cal1 = NULL;
159     erc->cal2 = NULL;
160     erc->repr = NULL;
162     /* Eraser values */
163     erc->cur = NR::Point(0,0);
164     erc->last = NR::Point(0,0);
165     erc->vel = NR::Point(0,0);
166     erc->vel_max = 0;
167     erc->acc = NR::Point(0,0);
168     erc->ang = NR::Point(0,0);
169     erc->del = NR::Point(0,0);
171     /* attributes */
172     erc->dragging = FALSE;
174     erc->mass = 0.3;
175     erc->drag = DRAG_DEFAULT;
176     erc->angle = 30.0;
177     erc->width = 0.2;
178     erc->pressure = ERC_DEFAULT_PRESSURE;
180     erc->vel_thin = 0.1;
181     erc->flatness = 0.9;
182     erc->cap_rounding = 0.0;
184     erc->abs_width = false;
187 static void
188 sp_eraser_context_dispose(GObject *object)
190     SPEraserContext *erc = SP_ERASER_CONTEXT(object);
192     if (erc->accumulated) {
193         erc->accumulated = sp_curve_unref(erc->accumulated);
194     }
196     while (erc->segments) {
197         gtk_object_destroy(GTK_OBJECT(erc->segments->data));
198         erc->segments = g_slist_remove(erc->segments, erc->segments->data);
199     }
201     if (erc->currentcurve) erc->currentcurve = sp_curve_unref(erc->currentcurve);
202     if (erc->cal1) erc->cal1 = sp_curve_unref(erc->cal1);
203     if (erc->cal2) erc->cal2 = sp_curve_unref(erc->cal2);
205     if (erc->currentshape) {
206         gtk_object_destroy(GTK_OBJECT(erc->currentshape));
207         erc->currentshape = 0;
208     }
210     if (erc->_message_context) {
211         delete erc->_message_context;
212         erc->_message_context = 0;
213     }
215     G_OBJECT_CLASS(parent_class)->dispose(object);
218 static void
219 sp_eraser_context_setup(SPEventContext *ec)
221     SPEraserContext *erc = SP_ERASER_CONTEXT(ec);
223     if (((SPEventContextClass *) parent_class)->setup)
224         ((SPEventContextClass *) parent_class)->setup(ec);
226     erc->accumulated = sp_curve_new_sized(32);
227     erc->currentcurve = sp_curve_new_sized(4);
229     erc->cal1 = sp_curve_new_sized(32);
230     erc->cal2 = sp_curve_new_sized(32);
232     erc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
233     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(erc->currentshape), ERC_RED_RGBA, SP_WIND_RULE_EVENODD);
234     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(erc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
235     /* fixme: Cannot we cascade it to root more clearly? */
236     g_signal_connect(G_OBJECT(erc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
238 /*
239 static ProfileFloatElement f_profile[PROFILE_FLOAT_SIZE] = {
240     {"mass",0.02, 0.0, 1.0},
241     {"wiggle",0.0, 0.0, 1.0},
242     {"angle",30.0, -90.0, 90.0},
243     {"thinning",0.1, -1.0, 1.0},
244     {"tremor",0.0, 0.0, 1.0},
245     {"flatness",0.9, 0.0, 1.0},
246     {"cap_rounding",0.0, 0.0, 5.0}
247 };
248 */
250     sp_event_context_read(ec, "mass");
251     sp_event_context_read(ec, "wiggle");
252     sp_event_context_read(ec, "angle");
253     sp_event_context_read(ec, "width");
254     sp_event_context_read(ec, "thinning");
255     sp_event_context_read(ec, "tremor");
256     sp_event_context_read(ec, "flatness");
257     sp_event_context_read(ec, "tracebackground");
258     sp_event_context_read(ec, "usepressure");
259     sp_event_context_read(ec, "usetilt");
260     sp_event_context_read(ec, "abs_width");
261     sp_event_context_read(ec, "cap_rounding");
263     erc->is_drawing = false;
265     erc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
267     if (prefs_get_int_attribute("tools.eraser", "selcue", 0) != 0) {
268         ec->enableSelectionCue();
269     }
270 // TODO temp force:
271     ec->enableSelectionCue();
275 static void
276 sp_eraser_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
278     SPEraserContext *erc = SP_ERASER_CONTEXT(ec);
280     if (!strcmp(key, "mass")) {
281         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
282         erc->mass = CLAMP(dval, -1000.0, 1000.0);
283     } else if (!strcmp(key, "wiggle")) {
284         double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
285         erc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
286     } else if (!strcmp(key, "angle")) {
287         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
288         erc->angle = CLAMP (dval, -90, 90);
289     } else if (!strcmp(key, "width")) {
290         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
291         erc->width = CLAMP(dval, -1000.0, 1000.0);
292     } else if (!strcmp(key, "thinning")) {
293         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
294         erc->vel_thin = CLAMP(dval, -1.0, 1.0);
295     } else if (!strcmp(key, "tremor")) {
296         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
297         erc->tremor = CLAMP(dval, 0.0, 1.0);
298     } else if (!strcmp(key, "flatness")) {
299         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
300         erc->flatness = CLAMP(dval, 0, 1.0);
301     } else if (!strcmp(key, "usepressure")) {
302         erc->usepressure = (val && strcmp(val, "0"));
303     } else if (!strcmp(key, "usetilt")) {
304         erc->usetilt = (val && strcmp(val, "0"));
305     } else if (!strcmp(key, "abs_width")) {
306         erc->abs_width = (val && strcmp(val, "0"));
307     } else if (!strcmp(key, "cap_rounding")) {
308         erc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
309     }
311     //g_print("ERC: %g %g %g %g\n", erc->mass, erc->drag, erc->angle, erc->width);
314 static double
315 flerp(double f0, double f1, double p)
317     return f0 + ( f1 - f0 ) * p;
320 /* Get normalized point */
321 static NR::Point
322 sp_eraser_get_npoint(SPEraserContext const *dc, NR::Point v)
324     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
325     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
326     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
329 /* Get view point */
330 static NR::Point
331 sp_eraser_get_vpoint(SPEraserContext const *dc, NR::Point n)
333     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
334     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
335     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
338 static void
339 sp_eraser_reset(SPEraserContext *dc, NR::Point p)
341     dc->last = dc->cur = sp_eraser_get_npoint(dc, p);
342     dc->vel = NR::Point(0,0);
343     dc->vel_max = 0;
344     dc->acc = NR::Point(0,0);
345     dc->ang = NR::Point(0,0);
346     dc->del = NR::Point(0,0);
349 static void
350 sp_eraser_extinput(SPEraserContext *dc, GdkEvent *event)
352     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
353         dc->pressure = CLAMP (dc->pressure, ERC_MIN_PRESSURE, ERC_MAX_PRESSURE);
354     else
355         dc->pressure = ERC_DEFAULT_PRESSURE;
357     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
358         dc->xtilt = CLAMP (dc->xtilt, ERC_MIN_TILT, ERC_MAX_TILT);
359     else
360         dc->xtilt = ERC_DEFAULT_TILT;
362     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
363         dc->ytilt = CLAMP (dc->ytilt, ERC_MIN_TILT, ERC_MAX_TILT);
364     else
365         dc->ytilt = ERC_DEFAULT_TILT;
369 static gboolean
370 sp_eraser_apply(SPEraserContext *dc, NR::Point p)
372     NR::Point n = sp_eraser_get_npoint(dc, p);
374     /* Calculate mass and drag */
375     double const mass = flerp(1.0, 160.0, dc->mass);
376     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
378     /* Calculate force and acceleration */
379     NR::Point force = n - dc->cur;
381     // If force is below the absolute threshold ERASER_EPSILON,
382     // or we haven't yet reached ERASER_VEL_START (i.e. at the beginning of stroke)
383     // _and_ the force is below the (higher) ERASER_EPSILON_START threshold,
384     // discard this move. 
385     // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
386     // especially bothersome at the start of the stroke where we don't yet have the inertia to
387     // smooth them out.
388     if ( NR::L2(force) < ERASER_EPSILON || (dc->vel_max < ERASER_VEL_START && NR::L2(force) < ERASER_EPSILON_START)) {
389         return FALSE;
390     }
392     dc->acc = force / mass;
394     /* Calculate new velocity */
395     dc->vel += dc->acc;
397     if (NR::L2(dc->vel) > dc->vel_max)
398         dc->vel_max = NR::L2(dc->vel);
400     /* Calculate angle of drawing tool */
402     double a1;
403     if (dc->usetilt) {
404         // 1a. calculate nib angle from input device tilt:
405         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
407         if (length > 0) {
408             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
409             a1 = atan2(ang1);
410         }
411         else
412             a1 = 0.0;
413     }
414     else {
415         // 1b. fixed dc->angle (absolutely flat nib):
416         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
417         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
418         a1 = atan2(ang1);
419     }
421     // 2. perpendicular to dc->vel (absolutely non-flat nib):
422     gdouble const mag_vel = NR::L2(dc->vel);
423     if ( mag_vel < ERASER_EPSILON ) {
424         return FALSE;
425     }
426     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
428     // 3. Average them using flatness parameter:
429     // calculate angles
430     double a2 = atan2(ang2);
431     // flip a2 to force it to be in the same half-circle as a1
432     bool flipped = false;
433     if (fabs (a2-a1) > 0.5*M_PI) {
434         a2 += M_PI;
435         flipped = true;
436     }
437     // normalize a2
438     if (a2 > M_PI)
439         a2 -= 2*M_PI;
440     if (a2 < -M_PI)
441         a2 += 2*M_PI;
442     // find the flatness-weighted bisector angle, unflip if a2 was flipped
443     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
444     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
446     // Try to detect a sudden flip when the new angle differs too much from the previous for the
447     // current velocity; in that case discard this move
448     double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
449     if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
450         return FALSE;
451     }
453     // convert to point
454     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
456 //    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);
458     /* Apply drag */
459     dc->vel *= 1.0 - drag;
461     /* Update position */
462     dc->last = dc->cur;
463     dc->cur += dc->vel;
465     return TRUE;
468 static void
469 sp_eraser_brush(SPEraserContext *dc)
471     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
473     // How much velocity thins strokestyle
474     double vel_thin = flerp (0, 160, dc->vel_thin);
476     // Influence of pressure on thickness
477     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
479     // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
480     // drag)
481     NR::Point brush = sp_eraser_get_vpoint(dc, dc->cur);
482     NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush); 
484     double trace_thick = 1;
486     double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
488     double tremble_left = 0, tremble_right = 0;
489     if (dc->tremor > 0) {
490         // obtain two normally distributed random variables, using polar Box-Muller transform
491         double x1, x2, w, y1, y2;
492         do {
493             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
494             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
495             w = x1 * x1 + x2 * x2;
496         } while ( w >= 1.0 );
497         w = sqrt( (-2.0 * log( w ) ) / w );
498         y1 = x1 * w;
499         y2 = x2 * w;
501         // deflect both left and right edges randomly and independently, so that:
502         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
503         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
504         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
505         // comparatively smooth and slow ones excessively jittery
506         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
507         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
508     }
510     if ( width < 0.02 * dc->width ) {
511         width = 0.02 * dc->width;
512     }
514     double dezoomify_factor = 0.05 * 1000;
515     if (!dc->abs_width) {
516         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
517     }
519     NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
520     NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
522     dc->point1[dc->npoints] = brush + del_left;
523     dc->point2[dc->npoints] = brush - del_right;
525     dc->del = 0.5*(del_left + del_right);
527     dc->npoints++;
530 void
531 sp_erc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
533     desktop->setToolboxAdjustmentValue (id, value);
536 static void
537 eraser_cancel(SPEraserContext *dc)
539     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
540     dc->dragging = FALSE;
541     dc->is_drawing = false;
542     sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
543             /* Remove all temporary line segments */
544             while (dc->segments) {
545                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
546                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
547             }
548             /* reset accumulated curve */
549             sp_curve_reset(dc->accumulated);
550             clear_current(dc);
551             if (dc->repr) {
552                 dc->repr = NULL;
553             }
557 gint
558 sp_eraser_context_root_handler(SPEventContext *event_context,
559                                   GdkEvent *event)
561     SPEraserContext *dc = SP_ERASER_CONTEXT(event_context);
562     SPDesktop *desktop = event_context->desktop;
564     gint ret = FALSE;
566     switch (event->type) {
567         case GDK_BUTTON_PRESS:
568             if (event->button.button == 1 && !event_context->space_panning) {
570                 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
572                 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
573                     return TRUE;
574                 }
576                 NR::Point const button_w(event->button.x,
577                                          event->button.y);
578                 NR::Point const button_dt(desktop->w2d(button_w));
579                 sp_eraser_reset(dc, button_dt);
580                 sp_eraser_extinput(dc, event);
581                 sp_eraser_apply(dc, button_dt);
582                 sp_curve_reset(dc->accumulated);
583                 if (dc->repr) {
584                     dc->repr = NULL;
585                 }
587                 Inkscape::Rubberband::get()->start(desktop, button_dt);
588                 Inkscape::Rubberband::get()->setMode(RUBBERBAND_MODE_TOUCHPATH);
590                 /* initialize first point */
591                 dc->npoints = 0;
593                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
594                                     ( GDK_KEY_PRESS_MASK |
595                                       GDK_BUTTON_RELEASE_MASK |
596                                       GDK_POINTER_MOTION_MASK |
597                                       GDK_BUTTON_PRESS_MASK ),
598                                     NULL,
599                                     event->button.time);
601                 ret = TRUE;
603                 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
604                 dc->is_drawing = true;
605             }
606             break;
607         case GDK_MOTION_NOTIFY:
608         {
609             NR::Point const motion_w(event->motion.x,
610                                      event->motion.y);
611             NR::Point motion_dt(desktop->w2d(motion_w));
612             sp_eraser_extinput(dc, event);
614             dc->_message_context->clear();
616             if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
617                 dc->dragging = TRUE;
619                 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> an eraser stroke"));
621                 if (!sp_eraser_apply(dc, motion_dt)) {
622                     ret = TRUE;
623                     break;
624                 }
626                 if ( dc->cur != dc->last ) {
627                     sp_eraser_brush(dc);
628                     g_assert( dc->npoints > 0 );
629                     fit_and_split(dc, FALSE);
630                 }
631                 ret = TRUE;
632             }
633             Inkscape::Rubberband::get()->move(motion_dt);
634         }
635         break;
638     case GDK_BUTTON_RELEASE:
639     {
640         NR::Point const motion_w(event->button.x, event->button.y);
641         NR::Point const motion_dt(desktop->w2d(motion_w));
643         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
644         sp_canvas_end_forced_full_redraws(desktop->canvas);
645         dc->is_drawing = false;
647         if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
648             dc->dragging = FALSE;
650             NR::Maybe<NR::Rect> const b = Inkscape::Rubberband::get()->getRectangle();
652             sp_eraser_apply(dc, motion_dt);
654             /* Remove all temporary line segments */
655             while (dc->segments) {
656                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
657                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
658             }
660             /* Create object */
661             fit_and_split(dc, TRUE);
662             accumulate_eraser(dc);
663             set_to_accumulated(dc); // performs document_done
665             /* reset accumulated curve */
666             sp_curve_reset(dc->accumulated);
668             clear_current(dc);
669             if (dc->repr) {
670                 dc->repr = NULL;
671             }
673             Inkscape::Rubberband::get()->stop();
674             dc->_message_context->clear();
675             ret = TRUE;
676         }
677         break;
678     }
680     case GDK_KEY_PRESS:
681         switch (get_group0_keyval (&event->key)) {
682         case GDK_Up:
683         case GDK_KP_Up:
684             if (!MOD__CTRL_ONLY) {
685                 dc->angle += 5.0;
686                 if (dc->angle > 90.0)
687                     dc->angle = 90.0;
688                 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
689                 ret = TRUE;
690             }
691             break;
692         case GDK_Down:
693         case GDK_KP_Down:
694             if (!MOD__CTRL_ONLY) {
695                 dc->angle -= 5.0;
696                 if (dc->angle < -90.0)
697                     dc->angle = -90.0;
698                 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
699                 ret = TRUE;
700             }
701             break;
702         case GDK_Right:
703         case GDK_KP_Right:
704             if (!MOD__CTRL_ONLY) {
705                 dc->width += 0.01;
706                 if (dc->width > 1.0)
707                     dc->width = 1.0;
708                 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100); // the same spinbutton is for alt+x
709                 ret = TRUE;
710             }
711             break;
712         case GDK_Left:
713         case GDK_KP_Left:
714             if (!MOD__CTRL_ONLY) {
715                 dc->width -= 0.01;
716                 if (dc->width < 0.01)
717                     dc->width = 0.01;
718                 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
719                 ret = TRUE;
720             }
721             break;
722         case GDK_Home:
723         case GDK_KP_Home:
724             dc->width = 0.01;
725             sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
726             ret = TRUE;
727             break;
728         case GDK_End:
729         case GDK_KP_End:
730             dc->width = 1.0;
731             sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
732             ret = TRUE;
733             break;
734         case GDK_x:
735         case GDK_X:
736             if (MOD__ALT_ONLY) {
737                 desktop->setToolboxFocusTo ("altx-eraser");
738                 ret = TRUE;
739             }
740             break;
741         case GDK_Escape:
742             Inkscape::Rubberband::get()->stop();
743             if (dc->is_drawing) {
744                 // if drawing, cancel, otherwise pass it up for deselecting
745                 eraser_cancel (dc);
746                 ret = TRUE;
747             }
748             break;
749         case GDK_z:
750         case GDK_Z:
751             if (MOD__CTRL_ONLY && dc->is_drawing) {
752                 // if drawing, cancel, otherwise pass it up for undo
753                 eraser_cancel (dc);
754                 ret = TRUE;
755             }
756             break;
757         default:
758             break;
759         }
760         break;
762     case GDK_KEY_RELEASE:
763         switch (get_group0_keyval(&event->key)) {
764             case GDK_Control_L:
765             case GDK_Control_R:
766                 dc->_message_context->clear();
767                 break;
768             default:
769                 break;
770         }
772     default:
773         break;
774     }
776     if (!ret) {
777         if (((SPEventContextClass *) parent_class)->root_handler) {
778             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
779         }
780     }
782     return ret;
786 static void
787 clear_current(SPEraserContext *dc)
789     // reset bpath
790     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
792     // reset curve
793     sp_curve_reset(dc->currentcurve);
794     sp_curve_reset(dc->cal1);
795     sp_curve_reset(dc->cal2);
797     // reset points
798     dc->npoints = 0;
801 static void
802 set_to_accumulated(SPEraserContext *dc)
804     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
805     bool workDone = false;
807     if (!sp_curve_empty(dc->accumulated)) {
808         NArtBpath *abp;
809         gchar *str;
811         if (!dc->repr) {
812             /* Create object */
813             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
814             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
816             /* Set style */
817             sp_desktop_apply_style_tool (desktop, repr, "tools.eraser", false);
819             dc->repr = repr;
821             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
822             Inkscape::GC::release(dc->repr);
823             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
824             item->updateRepr();
825         }
826         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
827         str = sp_svg_write_path(abp);
828         g_assert( str != NULL );
829         g_free(abp);
830         dc->repr->setAttribute("d", str);
831         g_free(str);
833         if ( dc->repr ) {
834             bool wasSelection = false;
835             Inkscape::Selection *selection = sp_desktop_selection(desktop);
836             gint eraserMode = (prefs_get_int_attribute("tools.eraser", "mode", 0) != 0) ? 1 : 0;
837             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
839             SPItem* acid = SP_ITEM(desktop->doc()->getObjectByRepr(dc->repr));
840             NR::Maybe<NR::Rect> eraserBbox = acid->getBounds(NR::identity());
841             NR::Rect bounds = (*eraserBbox) * desktop->doc2dt();
842             std::vector<SPItem*> remainingItems;
843             GSList* toWorkOn = 0;
844             if (selection->isEmpty()) {
845                 if ( eraserMode ) {
846                     toWorkOn = sp_document_partial_items_in_box(sp_desktop_document(desktop), desktop->dkey, bounds);
847                 } else {
848                     Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
849                     toWorkOn = sp_document_items_at_points(sp_desktop_document(desktop), desktop->dkey, r->getPoints());
850                 }
851                 toWorkOn = g_slist_remove( toWorkOn, acid );
852             } else {
853                 toWorkOn = g_slist_copy(const_cast<GSList*>(selection->itemList()));
854                 wasSelection = true;
855             }
857             if ( g_slist_length(toWorkOn) > 0 ) {
858                 if ( eraserMode ) {
859                     for (GSList *i = toWorkOn ; i ; i = i->next ) {
860                         SPItem *item = SP_ITEM(i->data);
861                         if ( eraserMode ) {
862                             NR::Maybe<NR::Rect> bbox = item->getBounds(NR::identity());
863                             if (bbox && bbox->intersects(*eraserBbox)) {
864                                 Inkscape::XML::Node* dup = dc->repr->duplicate(xml_doc);
865                                 dc->repr->parent()->appendChild(dup);
866                                 Inkscape::GC::release(dup); // parent takes over
868                                 selection->set(item);
869                                 selection->add(dup);
870                                 sp_selected_path_diff_skip_undo();
871                                 workDone = true; // TODO set this only if something was cut.
872                                 if ( !selection->isEmpty() ) {
873                                     // If the item was not completely erased, track the new remainder.
874                                     GSList *nowSel = g_slist_copy(const_cast<GSList *>(selection->itemList()));
875                                     for (GSList const *i2 = nowSel ; i2 ; i2 = i2->next ) {
876                                         remainingItems.push_back(SP_ITEM(i2->data));
877                                     }
878                                     g_slist_free(nowSel);
879                                 }
880                             } else {
881                                 remainingItems.push_back(item);
882                             }
883                         }
884                     }
885                 } else {
886                     for (GSList *i = toWorkOn ; i ; i = i->next ) {
887                         sp_object_ref( SP_ITEM(i->data), 0 );
888                     }
889                     for (GSList *i = toWorkOn ; i ; i = i->next ) {
890                         SPItem *item = SP_ITEM(i->data);
891                         item->deleteObject(true);
892                         sp_object_unref(item);
893                         workDone = true;
894                     }
895                 }
897                 g_slist_free(toWorkOn);
899                 if ( !eraserMode ) {
900                     //sp_selection_delete();
901                     remainingItems.clear();
902                 }
904                 selection->clear();
905                 if ( wasSelection ) {
906                     if ( !remainingItems.empty() ) {
907                         selection->add(remainingItems.begin(), remainingItems.end());
908                     }
909                 }
910             }
912             // Remove the eraser stroke itself:
913             sp_repr_unparent( dc->repr );
914             dc->repr = 0;
915         }
916     } else {
917         if (dc->repr) {
918             sp_repr_unparent(dc->repr);
919             dc->repr = 0;
920         }
921     }
924     if ( workDone ) {
925         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_ERASER, 
926                          _("Draw eraser stroke"));
927     } else {
928         sp_document_cancel(sp_desktop_document(desktop));
929     }
932 static void
933 add_cap(SPCurve *curve,
934         NR::Point const &pre, NR::Point const &from,
935         NR::Point const &to, NR::Point const &post,
936         double rounding)
938     NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
939     double mag = NR::L2(vel);
941     NR::Point v_in = from - pre;
942     double mag_in = NR::L2(v_in);
943     if ( mag_in > ERASER_EPSILON ) {
944         v_in = mag * v_in / mag_in;
945     } else {
946         v_in = NR::Point(0, 0);
947     }
949     NR::Point v_out = to - post;
950     double mag_out = NR::L2(v_out);
951     if ( mag_out > ERASER_EPSILON ) {
952         v_out = mag * v_out / mag_out;
953     } else {
954         v_out = NR::Point(0, 0);
955     }
957     if ( NR::L2(v_in) > ERASER_EPSILON || NR::L2(v_out) > ERASER_EPSILON ) {
958         sp_curve_curveto(curve, from + v_in, to + v_out, to);
959     }
962 static void
963 accumulate_eraser(SPEraserContext *dc)
965     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
966         sp_curve_reset(dc->accumulated); //  Is this required ??
967         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
969         g_assert(dc->cal1->end > 1);
970         g_assert(rev_cal2->end > 1);
971         g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
972         g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
973         g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
974         g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
975         g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
976         g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
978         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
980         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);
982         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
984         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);
986         sp_curve_closepath(dc->accumulated);
988         sp_curve_unref(rev_cal2);
990         sp_curve_reset(dc->cal1);
991         sp_curve_reset(dc->cal2);
992     }
995 static double square(double const x)
997     return x * x;
1000 static void
1001 fit_and_split(SPEraserContext *dc, gboolean release)
1003     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_ERASER );
1005 #ifdef ERASER_VERBOSE
1006     g_print("[F&S:R=%c]", release?'T':'F');
1007 #endif
1009     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1010         return; // just clicked
1012     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1013 #define BEZIER_SIZE       4
1014 #define BEZIER_MAX_BEZIERS  8
1015 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1017 #ifdef ERASER_VERBOSE
1018         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1019                 dc->npoints, release ? "TRUE" : "FALSE");
1020 #endif
1022         /* Current eraser */
1023         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
1024             /* dc->npoints > 0 */
1025             /* g_print("erasers(1|2) reset\n"); */
1026             sp_curve_reset(dc->cal1);
1027             sp_curve_reset(dc->cal2);
1029             sp_curve_moveto(dc->cal1, dc->point1[0]);
1030             sp_curve_moveto(dc->cal2, dc->point2[0]);
1031         }
1033         NR::Point b1[BEZIER_MAX_LENGTH];
1034         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1035                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1036         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1038         NR::Point b2[BEZIER_MAX_LENGTH];
1039         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1040                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1041         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1043         if ( nb1 != -1 && nb2 != -1 ) {
1044             /* Fit and draw and reset state */
1045 #ifdef ERASER_VERBOSE
1046             g_print("nb1:%d nb2:%d\n", nb1, nb2);
1047 #endif
1048             /* CanvasShape */
1049             if (! release) {
1050                 sp_curve_reset(dc->currentcurve);
1051                 sp_curve_moveto(dc->currentcurve, b1[0]);
1052                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1053                     sp_curve_curveto(dc->currentcurve, bp1[1],
1054                                      bp1[2], bp1[3]);
1055                 }
1056                 sp_curve_lineto(dc->currentcurve,
1057                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
1058                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1059                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
1060                 }
1061                 // FIXME: dc->segments is always NULL at this point??
1062                 if (!dc->segments) { // first segment
1063                     add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
1064                 }
1065                 sp_curve_closepath(dc->currentcurve);
1066                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1067             }
1069             /* Current eraser */
1070             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1071                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
1072             }
1073             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1074                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
1075             }
1076         } else {
1077             /* fixme: ??? */
1078 #ifdef ERASER_VERBOSE
1079             g_print("[fit_and_split] failed to fit-cubic.\n");
1080 #endif
1081             draw_temporary_box(dc);
1083             for (gint i = 1; i < dc->npoints; i++) {
1084                 sp_curve_lineto(dc->cal1, dc->point1[i]);
1085             }
1086             for (gint i = 1; i < dc->npoints; i++) {
1087                 sp_curve_lineto(dc->cal2, dc->point2[i]);
1088             }
1089         }
1091         /* Fit and draw and copy last point */
1092 #ifdef ERASER_VERBOSE
1093         g_print("[%d]Yup\n", dc->npoints);
1094 #endif
1095         if (!release) {
1096             gint eraserMode = (prefs_get_int_attribute("tools.eraser", "mode", 0) != 0) ? 1 : 0;
1097             g_assert(!sp_curve_empty(dc->currentcurve));
1099             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1100                                                    SP_TYPE_CANVAS_BPATH,
1101                                                    NULL);
1102             SPCurve *curve = sp_curve_copy(dc->currentcurve);
1103             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1104             sp_curve_unref(curve);
1106             guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.eraser", true);
1107             //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.eraser", false);
1108             double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser");
1109             double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser", true);
1110             //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser", false);
1111             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1112             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1113             //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);
1114             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1115             /* fixme: Cannot we cascade it to root more clearly? */
1116             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1118             dc->segments = g_slist_prepend(dc->segments, cbp);
1120             if ( !eraserMode ) {
1121                 sp_canvas_item_hide(cbp);
1122                 sp_canvas_item_hide(dc->currentshape);
1123             }
1124         }
1126         dc->point1[0] = dc->point1[dc->npoints - 1];
1127         dc->point2[0] = dc->point2[dc->npoints - 1];
1128         dc->npoints = 1;
1129     } else {
1130         draw_temporary_box(dc);
1131     }
1134 static void
1135 draw_temporary_box(SPEraserContext *dc)
1137     sp_curve_reset(dc->currentcurve);
1139     sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
1140     for (gint i = dc->npoints-2; i >= 0; i--) {
1141         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
1142     }
1143     for (gint i = 0; i < dc->npoints; i++) {
1144         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
1145     }
1146     if (dc->npoints >= 2) {
1147         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);
1148     }
1150     sp_curve_closepath(dc->currentcurve);
1151     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1154 /*
1155   Local Variables:
1156   mode:c++
1157   c-file-style:"stroustrup"
1158   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1159   indent-tabs-mode:nil
1160   fill-column:99
1161   End:
1162 */
1163 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :