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 "2geom/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 *eraser_parent_class = 0;
109 GType sp_eraser_context_get_type(void)
110 {
111 static GType type = 0;
112 if (!type) {
113 GTypeInfo info = {
114 sizeof(SPEraserContextClass),
115 0, // base_init
116 0, // base_finalize
117 (GClassInitFunc)sp_eraser_context_class_init,
118 0, // class_finalize
119 0, // class_data
120 sizeof(SPEraserContext),
121 0, // n_preallocs
122 (GInstanceInitFunc)sp_eraser_context_init,
123 0 // value_table
124 };
125 type = g_type_register_static(SP_TYPE_COMMON_CONTEXT, "SPEraserContext", &info, static_cast<GTypeFlags>(0));
126 }
127 return type;
128 }
130 static void
131 sp_eraser_context_class_init(SPEraserContextClass *klass)
132 {
133 GObjectClass *object_class = (GObjectClass *) klass;
134 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
136 eraser_parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
138 object_class->dispose = sp_eraser_context_dispose;
140 event_context_class->setup = sp_eraser_context_setup;
141 event_context_class->set = sp_eraser_context_set;
142 event_context_class->root_handler = sp_eraser_context_root_handler;
143 }
145 static void
146 sp_eraser_context_init(SPEraserContext *erc)
147 {
148 erc->cursor_shape = cursor_eraser_xpm;
149 erc->hot_x = 4;
150 erc->hot_y = 4;
151 }
153 static void
154 sp_eraser_context_dispose(GObject *object)
155 {
156 //SPEraserContext *erc = SP_ERASER_CONTEXT(object);
158 G_OBJECT_CLASS(eraser_parent_class)->dispose(object);
159 }
161 static void
162 sp_eraser_context_setup(SPEventContext *ec)
163 {
164 SPEraserContext *erc = SP_ERASER_CONTEXT(ec);
166 if (((SPEventContextClass *) eraser_parent_class)->setup)
167 ((SPEventContextClass *) eraser_parent_class)->setup(ec);
169 erc->accumulated = new SPCurve(32);
170 erc->currentcurve = new SPCurve(4);
172 erc->cal1 = new SPCurve(32);
173 erc->cal2 = new SPCurve(32);
175 erc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
176 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(erc->currentshape), ERC_RED_RGBA, SP_WIND_RULE_EVENODD);
177 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(erc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
178 /* fixme: Cannot we cascade it to root more clearly? */
179 g_signal_connect(G_OBJECT(erc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
181 /*
182 static ProfileFloatElement f_profile[PROFILE_FLOAT_SIZE] = {
183 {"mass",0.02, 0.0, 1.0},
184 {"wiggle",0.0, 0.0, 1.0},
185 {"angle",30.0, -90.0, 90.0},
186 {"thinning",0.1, -1.0, 1.0},
187 {"tremor",0.0, 0.0, 1.0},
188 {"flatness",0.9, 0.0, 1.0},
189 {"cap_rounding",0.0, 0.0, 5.0}
190 };
191 */
193 sp_event_context_read(ec, "mass");
194 sp_event_context_read(ec, "wiggle");
195 sp_event_context_read(ec, "angle");
196 sp_event_context_read(ec, "width");
197 sp_event_context_read(ec, "thinning");
198 sp_event_context_read(ec, "tremor");
199 sp_event_context_read(ec, "flatness");
200 sp_event_context_read(ec, "tracebackground");
201 sp_event_context_read(ec, "usepressure");
202 sp_event_context_read(ec, "usetilt");
203 sp_event_context_read(ec, "abs_width");
204 sp_event_context_read(ec, "cap_rounding");
206 erc->is_drawing = false;
208 erc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
210 if (prefs_get_int_attribute("tools.eraser", "selcue", 0) != 0) {
211 ec->enableSelectionCue();
212 }
213 // TODO temp force:
214 ec->enableSelectionCue();
216 }
218 static void
219 sp_eraser_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
220 {
221 //pass on up to parent class to handle common attributes.
222 if ( eraser_parent_class->set ) {
223 eraser_parent_class->set(ec, key, val);
224 }
225 }
227 static double
228 flerp(double f0, double f1, double p)
229 {
230 return f0 + ( f1 - f0 ) * p;
231 }
233 /* Get normalized point */
234 static NR::Point
235 sp_eraser_get_npoint(SPEraserContext const *dc, NR::Point v)
236 {
237 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
238 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
239 return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max, ( v[NR::Y] - drect.min()[NR::Y] ) / max);
240 }
242 /* Get view point */
243 static NR::Point
244 sp_eraser_get_vpoint(SPEraserContext const *dc, NR::Point n)
245 {
246 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
247 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
248 return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
249 }
251 static void
252 sp_eraser_reset(SPEraserContext *dc, NR::Point p)
253 {
254 dc->last = dc->cur = sp_eraser_get_npoint(dc, p);
255 dc->vel = NR::Point(0,0);
256 dc->vel_max = 0;
257 dc->acc = NR::Point(0,0);
258 dc->ang = NR::Point(0,0);
259 dc->del = NR::Point(0,0);
260 }
262 static void
263 sp_eraser_extinput(SPEraserContext *dc, GdkEvent *event)
264 {
265 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
266 dc->pressure = CLAMP (dc->pressure, ERC_MIN_PRESSURE, ERC_MAX_PRESSURE);
267 else
268 dc->pressure = ERC_DEFAULT_PRESSURE;
270 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
271 dc->xtilt = CLAMP (dc->xtilt, ERC_MIN_TILT, ERC_MAX_TILT);
272 else
273 dc->xtilt = ERC_DEFAULT_TILT;
275 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
276 dc->ytilt = CLAMP (dc->ytilt, ERC_MIN_TILT, ERC_MAX_TILT);
277 else
278 dc->ytilt = ERC_DEFAULT_TILT;
279 }
282 static gboolean
283 sp_eraser_apply(SPEraserContext *dc, NR::Point p)
284 {
285 NR::Point n = sp_eraser_get_npoint(dc, p);
287 /* Calculate mass and drag */
288 double const mass = flerp(1.0, 160.0, dc->mass);
289 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
291 /* Calculate force and acceleration */
292 NR::Point force = n - dc->cur;
294 // If force is below the absolute threshold ERASER_EPSILON,
295 // or we haven't yet reached ERASER_VEL_START (i.e. at the beginning of stroke)
296 // _and_ the force is below the (higher) ERASER_EPSILON_START threshold,
297 // discard this move.
298 // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
299 // especially bothersome at the start of the stroke where we don't yet have the inertia to
300 // smooth them out.
301 if ( NR::L2(force) < ERASER_EPSILON || (dc->vel_max < ERASER_VEL_START && NR::L2(force) < ERASER_EPSILON_START)) {
302 return FALSE;
303 }
305 dc->acc = force / mass;
307 /* Calculate new velocity */
308 dc->vel += dc->acc;
310 if (NR::L2(dc->vel) > dc->vel_max)
311 dc->vel_max = NR::L2(dc->vel);
313 /* Calculate angle of drawing tool */
315 double a1;
316 if (dc->usetilt) {
317 // 1a. calculate nib angle from input device tilt:
318 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
320 if (length > 0) {
321 NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
322 a1 = atan2(ang1);
323 }
324 else
325 a1 = 0.0;
326 }
327 else {
328 // 1b. fixed dc->angle (absolutely flat nib):
329 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
330 NR::Point ang1 = NR::Point(-sin(radians), cos(radians));
331 a1 = atan2(ang1);
332 }
334 // 2. perpendicular to dc->vel (absolutely non-flat nib):
335 gdouble const mag_vel = NR::L2(dc->vel);
336 if ( mag_vel < ERASER_EPSILON ) {
337 return FALSE;
338 }
339 NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
341 // 3. Average them using flatness parameter:
342 // calculate angles
343 double a2 = atan2(ang2);
344 // flip a2 to force it to be in the same half-circle as a1
345 bool flipped = false;
346 if (fabs (a2-a1) > 0.5*M_PI) {
347 a2 += M_PI;
348 flipped = true;
349 }
350 // normalize a2
351 if (a2 > M_PI)
352 a2 -= 2*M_PI;
353 if (a2 < -M_PI)
354 a2 += 2*M_PI;
355 // find the flatness-weighted bisector angle, unflip if a2 was flipped
356 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
357 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
359 // Try to detect a sudden flip when the new angle differs too much from the previous for the
360 // current velocity; in that case discard this move
361 double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
362 if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
363 return FALSE;
364 }
366 // convert to point
367 dc->ang = NR::Point (cos (new_ang), sin (new_ang));
369 // 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);
371 /* Apply drag */
372 dc->vel *= 1.0 - drag;
374 /* Update position */
375 dc->last = dc->cur;
376 dc->cur += dc->vel;
378 return TRUE;
379 }
381 static void
382 sp_eraser_brush(SPEraserContext *dc)
383 {
384 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
386 // How much velocity thins strokestyle
387 double vel_thin = flerp (0, 160, dc->vel_thin);
389 // Influence of pressure on thickness
390 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
392 // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
393 // drag)
394 NR::Point brush = sp_eraser_get_vpoint(dc, dc->cur);
395 NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush);
397 double trace_thick = 1;
399 double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
401 double tremble_left = 0, tremble_right = 0;
402 if (dc->tremor > 0) {
403 // obtain two normally distributed random variables, using polar Box-Muller transform
404 double x1, x2, w, y1, y2;
405 do {
406 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
407 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
408 w = x1 * x1 + x2 * x2;
409 } while ( w >= 1.0 );
410 w = sqrt( (-2.0 * log( w ) ) / w );
411 y1 = x1 * w;
412 y2 = x2 * w;
414 // deflect both left and right edges randomly and independently, so that:
415 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
416 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
417 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
418 // comparatively smooth and slow ones excessively jittery
419 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
420 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
421 }
423 if ( width < 0.02 * dc->width ) {
424 width = 0.02 * dc->width;
425 }
427 double dezoomify_factor = 0.05 * 1000;
428 if (!dc->abs_width) {
429 dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
430 }
432 NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
433 NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
435 dc->point1[dc->npoints] = brush + del_left;
436 dc->point2[dc->npoints] = brush - del_right;
438 dc->del = 0.5*(del_left + del_right);
440 dc->npoints++;
441 }
443 void
444 sp_erc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
445 {
446 desktop->setToolboxAdjustmentValue (id, value);
447 }
449 static void
450 eraser_cancel(SPEraserContext *dc)
451 {
452 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
453 dc->dragging = FALSE;
454 dc->is_drawing = false;
455 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
456 /* Remove all temporary line segments */
457 while (dc->segments) {
458 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
459 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
460 }
461 /* reset accumulated curve */
462 dc->accumulated->reset();
463 clear_current(dc);
464 if (dc->repr) {
465 dc->repr = NULL;
466 }
467 }
470 gint
471 sp_eraser_context_root_handler(SPEventContext *event_context,
472 GdkEvent *event)
473 {
474 SPEraserContext *dc = SP_ERASER_CONTEXT(event_context);
475 SPDesktop *desktop = event_context->desktop;
477 gint ret = FALSE;
479 switch (event->type) {
480 case GDK_BUTTON_PRESS:
481 if (event->button.button == 1 && !event_context->space_panning) {
483 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
485 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
486 return TRUE;
487 }
489 NR::Point const button_w(event->button.x,
490 event->button.y);
491 NR::Point const button_dt(desktop->w2d(button_w));
492 sp_eraser_reset(dc, button_dt);
493 sp_eraser_extinput(dc, event);
494 sp_eraser_apply(dc, button_dt);
495 dc->accumulated->reset();
496 if (dc->repr) {
497 dc->repr = NULL;
498 }
500 Inkscape::Rubberband::get()->start(desktop, button_dt);
501 Inkscape::Rubberband::get()->setMode(RUBBERBAND_MODE_TOUCHPATH);
503 /* initialize first point */
504 dc->npoints = 0;
506 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
507 ( GDK_KEY_PRESS_MASK |
508 GDK_BUTTON_RELEASE_MASK |
509 GDK_POINTER_MOTION_MASK |
510 GDK_BUTTON_PRESS_MASK ),
511 NULL,
512 event->button.time);
514 ret = TRUE;
516 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
517 dc->is_drawing = true;
518 }
519 break;
520 case GDK_MOTION_NOTIFY:
521 {
522 NR::Point const motion_w(event->motion.x,
523 event->motion.y);
524 NR::Point motion_dt(desktop->w2d(motion_w));
525 sp_eraser_extinput(dc, event);
527 dc->_message_context->clear();
529 if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
530 dc->dragging = TRUE;
532 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> an eraser stroke"));
534 if (!sp_eraser_apply(dc, motion_dt)) {
535 ret = TRUE;
536 break;
537 }
539 if ( dc->cur != dc->last ) {
540 sp_eraser_brush(dc);
541 g_assert( dc->npoints > 0 );
542 fit_and_split(dc, FALSE);
543 }
544 ret = TRUE;
545 }
546 Inkscape::Rubberband::get()->move(motion_dt);
547 }
548 break;
551 case GDK_BUTTON_RELEASE:
552 {
553 NR::Point const motion_w(event->button.x, event->button.y);
554 NR::Point const motion_dt(desktop->w2d(motion_w));
556 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
557 sp_canvas_end_forced_full_redraws(desktop->canvas);
558 dc->is_drawing = false;
560 if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
561 dc->dragging = FALSE;
563 NR::Maybe<NR::Rect> const b = Inkscape::Rubberband::get()->getRectangle();
565 sp_eraser_apply(dc, motion_dt);
567 /* Remove all temporary line segments */
568 while (dc->segments) {
569 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
570 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
571 }
573 /* Create object */
574 fit_and_split(dc, TRUE);
575 accumulate_eraser(dc);
576 set_to_accumulated(dc); // performs document_done
578 /* reset accumulated curve */
579 dc->accumulated->reset();
581 clear_current(dc);
582 if (dc->repr) {
583 dc->repr = NULL;
584 }
586 Inkscape::Rubberband::get()->stop();
587 dc->_message_context->clear();
588 ret = TRUE;
589 }
590 break;
591 }
593 case GDK_KEY_PRESS:
594 switch (get_group0_keyval (&event->key)) {
595 case GDK_Up:
596 case GDK_KP_Up:
597 if (!MOD__CTRL_ONLY) {
598 dc->angle += 5.0;
599 if (dc->angle > 90.0)
600 dc->angle = 90.0;
601 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
602 ret = TRUE;
603 }
604 break;
605 case GDK_Down:
606 case GDK_KP_Down:
607 if (!MOD__CTRL_ONLY) {
608 dc->angle -= 5.0;
609 if (dc->angle < -90.0)
610 dc->angle = -90.0;
611 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
612 ret = TRUE;
613 }
614 break;
615 case GDK_Right:
616 case GDK_KP_Right:
617 if (!MOD__CTRL_ONLY) {
618 dc->width += 0.01;
619 if (dc->width > 1.0)
620 dc->width = 1.0;
621 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100); // the same spinbutton is for alt+x
622 ret = TRUE;
623 }
624 break;
625 case GDK_Left:
626 case GDK_KP_Left:
627 if (!MOD__CTRL_ONLY) {
628 dc->width -= 0.01;
629 if (dc->width < 0.01)
630 dc->width = 0.01;
631 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
632 ret = TRUE;
633 }
634 break;
635 case GDK_Home:
636 case GDK_KP_Home:
637 dc->width = 0.01;
638 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
639 ret = TRUE;
640 break;
641 case GDK_End:
642 case GDK_KP_End:
643 dc->width = 1.0;
644 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
645 ret = TRUE;
646 break;
647 case GDK_x:
648 case GDK_X:
649 if (MOD__ALT_ONLY) {
650 desktop->setToolboxFocusTo ("altx-eraser");
651 ret = TRUE;
652 }
653 break;
654 case GDK_Escape:
655 Inkscape::Rubberband::get()->stop();
656 if (dc->is_drawing) {
657 // if drawing, cancel, otherwise pass it up for deselecting
658 eraser_cancel (dc);
659 ret = TRUE;
660 }
661 break;
662 case GDK_z:
663 case GDK_Z:
664 if (MOD__CTRL_ONLY && dc->is_drawing) {
665 // if drawing, cancel, otherwise pass it up for undo
666 eraser_cancel (dc);
667 ret = TRUE;
668 }
669 break;
670 default:
671 break;
672 }
673 break;
675 case GDK_KEY_RELEASE:
676 switch (get_group0_keyval(&event->key)) {
677 case GDK_Control_L:
678 case GDK_Control_R:
679 dc->_message_context->clear();
680 break;
681 default:
682 break;
683 }
685 default:
686 break;
687 }
689 if (!ret) {
690 if (((SPEventContextClass *) eraser_parent_class)->root_handler) {
691 ret = ((SPEventContextClass *) eraser_parent_class)->root_handler(event_context, event);
692 }
693 }
695 return ret;
696 }
699 static void
700 clear_current(SPEraserContext *dc)
701 {
702 // reset bpath
703 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
705 // reset curve
706 dc->currentcurve->reset();
707 dc->cal1->reset();
708 dc->cal2->reset();
710 // reset points
711 dc->npoints = 0;
712 }
714 static void
715 set_to_accumulated(SPEraserContext *dc)
716 {
717 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
718 bool workDone = false;
720 if (!dc->accumulated->is_empty()) {
721 NArtBpath *abp;
722 gchar *str;
724 if (!dc->repr) {
725 /* Create object */
726 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
727 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
729 /* Set style */
730 sp_desktop_apply_style_tool (desktop, repr, "tools.eraser", false);
732 dc->repr = repr;
734 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
735 Inkscape::GC::release(dc->repr);
736 item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
737 item->updateRepr();
738 }
739 abp = nr_artpath_affine(dc->accumulated->get_bpath(), sp_desktop_dt2root_affine(desktop));
740 str = sp_svg_write_path(abp);
741 g_assert( str != NULL );
742 g_free(abp);
743 dc->repr->setAttribute("d", str);
744 g_free(str);
746 if ( dc->repr ) {
747 bool wasSelection = false;
748 Inkscape::Selection *selection = sp_desktop_selection(desktop);
749 gint eraserMode = (prefs_get_int_attribute("tools.eraser", "mode", 0) != 0) ? 1 : 0;
750 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
752 SPItem* acid = SP_ITEM(desktop->doc()->getObjectByRepr(dc->repr));
753 NR::Maybe<NR::Rect> eraserBbox = acid->getBounds(NR::identity());
754 NR::Rect bounds = (*eraserBbox) * desktop->doc2dt();
755 std::vector<SPItem*> remainingItems;
756 GSList* toWorkOn = 0;
757 if (selection->isEmpty()) {
758 if ( eraserMode ) {
759 toWorkOn = sp_document_partial_items_in_box(sp_desktop_document(desktop), desktop->dkey, bounds);
760 } else {
761 Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
762 toWorkOn = sp_document_items_at_points(sp_desktop_document(desktop), desktop->dkey, r->getPoints());
763 }
764 toWorkOn = g_slist_remove( toWorkOn, acid );
765 } else {
766 toWorkOn = g_slist_copy(const_cast<GSList*>(selection->itemList()));
767 wasSelection = true;
768 }
770 if ( g_slist_length(toWorkOn) > 0 ) {
771 if ( eraserMode ) {
772 for (GSList *i = toWorkOn ; i ; i = i->next ) {
773 SPItem *item = SP_ITEM(i->data);
774 if ( eraserMode ) {
775 NR::Maybe<NR::Rect> bbox = item->getBounds(NR::identity());
776 if (bbox && bbox->intersects(*eraserBbox)) {
777 Inkscape::XML::Node* dup = dc->repr->duplicate(xml_doc);
778 dc->repr->parent()->appendChild(dup);
779 Inkscape::GC::release(dup); // parent takes over
781 selection->set(item);
782 selection->add(dup);
783 sp_selected_path_diff_skip_undo();
784 workDone = true; // TODO set this only if something was cut.
785 if ( !selection->isEmpty() ) {
786 // If the item was not completely erased, track the new remainder.
787 GSList *nowSel = g_slist_copy(const_cast<GSList *>(selection->itemList()));
788 for (GSList const *i2 = nowSel ; i2 ; i2 = i2->next ) {
789 remainingItems.push_back(SP_ITEM(i2->data));
790 }
791 g_slist_free(nowSel);
792 }
793 } else {
794 remainingItems.push_back(item);
795 }
796 }
797 }
798 } else {
799 for (GSList *i = toWorkOn ; i ; i = i->next ) {
800 sp_object_ref( SP_ITEM(i->data), 0 );
801 }
802 for (GSList *i = toWorkOn ; i ; i = i->next ) {
803 SPItem *item = SP_ITEM(i->data);
804 item->deleteObject(true);
805 sp_object_unref(item);
806 workDone = true;
807 }
808 }
810 g_slist_free(toWorkOn);
812 if ( !eraserMode ) {
813 //sp_selection_delete();
814 remainingItems.clear();
815 }
817 selection->clear();
818 if ( wasSelection ) {
819 if ( !remainingItems.empty() ) {
820 selection->add(remainingItems.begin(), remainingItems.end());
821 }
822 }
823 }
825 // Remove the eraser stroke itself:
826 sp_repr_unparent( dc->repr );
827 dc->repr = 0;
828 }
829 } else {
830 if (dc->repr) {
831 sp_repr_unparent(dc->repr);
832 dc->repr = 0;
833 }
834 }
837 if ( workDone ) {
838 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_ERASER,
839 _("Draw eraser stroke"));
840 } else {
841 sp_document_cancel(sp_desktop_document(desktop));
842 }
843 }
845 static void
846 add_cap(SPCurve *curve,
847 NR::Point const &pre, NR::Point const &from,
848 NR::Point const &to, NR::Point const &post,
849 double rounding)
850 {
851 NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
852 double mag = NR::L2(vel);
854 NR::Point v_in = from - pre;
855 double mag_in = NR::L2(v_in);
856 if ( mag_in > ERASER_EPSILON ) {
857 v_in = mag * v_in / mag_in;
858 } else {
859 v_in = NR::Point(0, 0);
860 }
862 NR::Point v_out = to - post;
863 double mag_out = NR::L2(v_out);
864 if ( mag_out > ERASER_EPSILON ) {
865 v_out = mag * v_out / mag_out;
866 } else {
867 v_out = NR::Point(0, 0);
868 }
870 if ( NR::L2(v_in) > ERASER_EPSILON || NR::L2(v_out) > ERASER_EPSILON ) {
871 curve->curveto(from + v_in, to + v_out, to);
872 }
873 }
875 static void
876 accumulate_eraser(SPEraserContext *dc)
877 {
878 if ( !dc->cal1->is_empty() && !dc->cal2->is_empty() ) {
879 dc->accumulated->reset(); /* Is this required ?? */
880 SPCurve *rev_cal2 = dc->cal2->create_reverse();
882 g_assert(dc->cal1->get_length() > 1);
883 g_assert(rev_cal2->get_length() > 1);
884 g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
885 g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
886 g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
887 g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
888 g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->get_length()-1)->code == NR_CURVETO);
889 g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->get_length()-1)->code == NR_CURVETO);
891 dc->accumulated->append(dc->cal1, FALSE);
893 add_cap(dc->accumulated, SP_CURVE_SEGMENT(dc->cal1, dc->cal1->get_length()-1)->c(2), SP_CURVE_SEGMENT(dc->cal1, dc->cal1->get_length()-1)->c(3), SP_CURVE_SEGMENT(rev_cal2, 0)->c(3), SP_CURVE_SEGMENT(rev_cal2, 1)->c(1), dc->cap_rounding);
895 dc->accumulated->append(rev_cal2, TRUE);
897 add_cap(dc->accumulated, SP_CURVE_SEGMENT(rev_cal2, rev_cal2->get_length()-1)->c(2), SP_CURVE_SEGMENT(rev_cal2, rev_cal2->get_length()-1)->c(3), SP_CURVE_SEGMENT(dc->cal1, 0)->c(3), SP_CURVE_SEGMENT(dc->cal1, 1)->c(1), dc->cap_rounding);
899 dc->accumulated->closepath();
901 rev_cal2->unref();
903 dc->cal1->reset();
904 dc->cal2->reset();
905 }
906 }
908 static double square(double const x)
909 {
910 return x * x;
911 }
913 static void
914 fit_and_split(SPEraserContext *dc, gboolean release)
915 {
916 double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_ERASER );
918 #ifdef ERASER_VERBOSE
919 g_print("[F&S:R=%c]", release?'T':'F');
920 #endif
922 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
923 return; // just clicked
925 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
926 #define BEZIER_SIZE 4
927 #define BEZIER_MAX_BEZIERS 8
928 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
930 #ifdef ERASER_VERBOSE
931 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
932 dc->npoints, release ? "TRUE" : "FALSE");
933 #endif
935 /* Current eraser */
936 if ( dc->cal1->get_length() == 0 || dc->cal2->get_length() == 0 ) {
937 /* dc->npoints > 0 */
938 /* g_print("erasers(1|2) reset\n"); */
939 dc->cal1->reset();
940 dc->cal2->reset();
942 dc->cal1->moveto(dc->point1[0]);
943 dc->cal2->moveto(dc->point2[0]);
944 }
946 NR::Point b1[BEZIER_MAX_LENGTH];
947 gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
948 tolerance_sq, BEZIER_MAX_BEZIERS);
949 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
951 NR::Point b2[BEZIER_MAX_LENGTH];
952 gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
953 tolerance_sq, BEZIER_MAX_BEZIERS);
954 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
956 if ( nb1 != -1 && nb2 != -1 ) {
957 /* Fit and draw and reset state */
958 #ifdef ERASER_VERBOSE
959 g_print("nb1:%d nb2:%d\n", nb1, nb2);
960 #endif
961 /* CanvasShape */
962 if (! release) {
963 dc->currentcurve->reset();
964 dc->currentcurve->moveto(b1[0]);
965 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
966 dc->currentcurve->curveto(bp1[1],
967 bp1[2], bp1[3]);
968 }
969 dc->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]);
970 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
971 dc->currentcurve->curveto(bp2[2], bp2[1], bp2[0]);
972 }
973 // FIXME: dc->segments is always NULL at this point??
974 if (!dc->segments) { // first segment
975 add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
976 }
977 dc->currentcurve->closepath();
978 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
979 }
981 /* Current eraser */
982 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
983 dc->cal1->curveto(bp1[1], bp1[2], bp1[3]);
984 }
985 for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
986 dc->cal2->curveto(bp2[1], bp2[2], bp2[3]);
987 }
988 } else {
989 /* fixme: ??? */
990 #ifdef ERASER_VERBOSE
991 g_print("[fit_and_split] failed to fit-cubic.\n");
992 #endif
993 draw_temporary_box(dc);
995 for (gint i = 1; i < dc->npoints; i++) {
996 dc->cal1->lineto(dc->point1[i]);
997 }
998 for (gint i = 1; i < dc->npoints; i++) {
999 dc->cal2->lineto(dc->point2[i]);
1000 }
1001 }
1003 /* Fit and draw and copy last point */
1004 #ifdef ERASER_VERBOSE
1005 g_print("[%d]Yup\n", dc->npoints);
1006 #endif
1007 if (!release) {
1008 gint eraserMode = (prefs_get_int_attribute("tools.eraser", "mode", 0) != 0) ? 1 : 0;
1009 g_assert(!dc->currentcurve->is_empty());
1011 SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1012 SP_TYPE_CANVAS_BPATH,
1013 NULL);
1014 SPCurve *curve = dc->currentcurve->copy();
1015 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1016 curve->unref();
1018 guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.eraser", true);
1019 //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.eraser", false);
1020 double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser");
1021 double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser", true);
1022 //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser", false);
1023 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1024 //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1025 //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);
1026 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1027 /* fixme: Cannot we cascade it to root more clearly? */
1028 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1030 dc->segments = g_slist_prepend(dc->segments, cbp);
1032 if ( !eraserMode ) {
1033 sp_canvas_item_hide(cbp);
1034 sp_canvas_item_hide(dc->currentshape);
1035 }
1036 }
1038 dc->point1[0] = dc->point1[dc->npoints - 1];
1039 dc->point2[0] = dc->point2[dc->npoints - 1];
1040 dc->npoints = 1;
1041 } else {
1042 draw_temporary_box(dc);
1043 }
1044 }
1046 static void
1047 draw_temporary_box(SPEraserContext *dc)
1048 {
1049 dc->currentcurve->reset();
1051 dc->currentcurve->moveto(dc->point1[dc->npoints-1]);
1052 for (gint i = dc->npoints-2; i >= 0; i--) {
1053 dc->currentcurve->lineto(dc->point1[i]);
1054 }
1055 for (gint i = 0; i < dc->npoints; i++) {
1056 dc->currentcurve->lineto(dc->point2[i]);
1057 }
1058 if (dc->npoints >= 2) {
1059 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);
1060 }
1062 dc->currentcurve->closepath();
1063 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1064 }
1066 /*
1067 Local Variables:
1068 mode:c++
1069 c-file-style:"stroustrup"
1070 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1071 indent-tabs-mode:nil
1072 fill-column:99
1073 End:
1074 */
1075 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :