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 <2geom/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 "preferences.h"
50 #include "pixmaps/cursor-eraser.xpm"
51 #include "xml/repr.h"
52 #include "context-fns.h"
53 #include "sp-item.h"
54 #include "color.h"
55 #include "rubberband.h"
56 #include "splivarot.h"
57 #include "sp-item-group.h"
58 #include "sp-shape.h"
59 #include "sp-path.h"
60 #include "sp-text.h"
61 #include "display/canvas-bpath.h"
62 #include "display/canvas-arena.h"
63 #include "livarot/Shape.h"
64 #include <2geom/isnan.h>
65 #include <2geom/pathvector.h>
67 #include "eraser-context.h"
69 #define ERC_RED_RGBA 0xff0000ff
71 #define TOLERANCE_ERASER 0.1
73 #define ERASER_EPSILON 0.5e-6
74 #define ERASER_EPSILON_START 0.5e-2
75 #define ERASER_VEL_START 1e-5
77 #define DRAG_MIN 0.0
78 #define DRAG_DEFAULT 1.0
79 #define DRAG_MAX 1.0
82 static void sp_eraser_context_class_init(SPEraserContextClass *klass);
83 static void sp_eraser_context_init(SPEraserContext *erc);
84 static void sp_eraser_context_dispose(GObject *object);
86 static void sp_eraser_context_setup(SPEventContext *ec);
87 static void sp_eraser_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val);
88 static gint sp_eraser_context_root_handler(SPEventContext *ec, GdkEvent *event);
90 static void clear_current(SPEraserContext *dc);
91 static void set_to_accumulated(SPEraserContext *dc);
92 static void add_cap(SPCurve *curve, Geom::Point const &pre, Geom::Point const &from, Geom::Point const &to, Geom::Point const &post, double rounding);
93 static void accumulate_eraser(SPEraserContext *dc);
95 static void fit_and_split(SPEraserContext *erc, gboolean release);
97 static void sp_eraser_reset(SPEraserContext *erc, Geom::Point p);
98 static Geom::Point sp_eraser_get_npoint(SPEraserContext const *erc, Geom::Point v);
99 static Geom::Point sp_eraser_get_vpoint(SPEraserContext const *erc, Geom::Point n);
100 static void draw_temporary_box(SPEraserContext *dc);
103 static SPEventContextClass *eraser_parent_class = 0;
105 GType sp_eraser_context_get_type(void)
106 {
107 static GType type = 0;
108 if (!type) {
109 GTypeInfo info = {
110 sizeof(SPEraserContextClass),
111 0, // base_init
112 0, // base_finalize
113 (GClassInitFunc)sp_eraser_context_class_init,
114 0, // class_finalize
115 0, // class_data
116 sizeof(SPEraserContext),
117 0, // n_preallocs
118 (GInstanceInitFunc)sp_eraser_context_init,
119 0 // value_table
120 };
121 type = g_type_register_static(SP_TYPE_COMMON_CONTEXT, "SPEraserContext", &info, static_cast<GTypeFlags>(0));
122 }
123 return type;
124 }
126 static void
127 sp_eraser_context_class_init(SPEraserContextClass *klass)
128 {
129 GObjectClass *object_class = (GObjectClass *) klass;
130 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
132 eraser_parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
134 object_class->dispose = sp_eraser_context_dispose;
136 event_context_class->setup = sp_eraser_context_setup;
137 event_context_class->set = sp_eraser_context_set;
138 event_context_class->root_handler = sp_eraser_context_root_handler;
139 }
141 static void
142 sp_eraser_context_init(SPEraserContext *erc)
143 {
144 erc->cursor_shape = cursor_eraser_xpm;
145 erc->hot_x = 4;
146 erc->hot_y = 4;
147 }
149 static void
150 sp_eraser_context_dispose(GObject *object)
151 {
152 //SPEraserContext *erc = SP_ERASER_CONTEXT(object);
154 G_OBJECT_CLASS(eraser_parent_class)->dispose(object);
155 }
157 static void
158 sp_eraser_context_setup(SPEventContext *ec)
159 {
160 SPEraserContext *erc = SP_ERASER_CONTEXT(ec);
161 SPDesktop *desktop = ec->desktop;
163 if (((SPEventContextClass *) eraser_parent_class)->setup)
164 ((SPEventContextClass *) eraser_parent_class)->setup(ec);
166 erc->accumulated = new SPCurve();
167 erc->currentcurve = new SPCurve();
169 erc->cal1 = new SPCurve();
170 erc->cal2 = new SPCurve();
172 erc->currentshape = sp_canvas_item_new(sp_desktop_sketch(desktop), SP_TYPE_CANVAS_BPATH, NULL);
173 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(erc->currentshape), ERC_RED_RGBA, SP_WIND_RULE_EVENODD);
174 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(erc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
175 /* fixme: Cannot we cascade it to root more clearly? */
176 g_signal_connect(G_OBJECT(erc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), desktop);
178 /*
179 static ProfileFloatElement f_profile[PROFILE_FLOAT_SIZE] = {
180 {"mass",0.02, 0.0, 1.0},
181 {"wiggle",0.0, 0.0, 1.0},
182 {"angle",30.0, -90.0, 90.0},
183 {"thinning",0.1, -1.0, 1.0},
184 {"tremor",0.0, 0.0, 1.0},
185 {"flatness",0.9, 0.0, 1.0},
186 {"cap_rounding",0.0, 0.0, 5.0}
187 };
188 */
190 sp_event_context_read(ec, "mass");
191 sp_event_context_read(ec, "wiggle");
192 sp_event_context_read(ec, "angle");
193 sp_event_context_read(ec, "width");
194 sp_event_context_read(ec, "thinning");
195 sp_event_context_read(ec, "tremor");
196 sp_event_context_read(ec, "flatness");
197 sp_event_context_read(ec, "tracebackground");
198 sp_event_context_read(ec, "usepressure");
199 sp_event_context_read(ec, "usetilt");
200 sp_event_context_read(ec, "abs_width");
201 sp_event_context_read(ec, "cap_rounding");
203 erc->is_drawing = false;
205 erc->_message_context = new Inkscape::MessageContext(desktop->messageStack());
207 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
208 if (prefs->getBool("/tools/eraser/selcue", 0) != 0) {
209 ec->enableSelectionCue();
210 }
211 // TODO temp force:
212 ec->enableSelectionCue();
214 }
216 static void
217 sp_eraser_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val)
218 {
219 //pass on up to parent class to handle common attributes.
220 if ( eraser_parent_class->set ) {
221 eraser_parent_class->set(ec, val);
222 }
223 }
225 static double
226 flerp(double f0, double f1, double p)
227 {
228 return f0 + ( f1 - f0 ) * p;
229 }
231 /* Get normalized point */
232 static Geom::Point
233 sp_eraser_get_npoint(SPEraserContext const *dc, Geom::Point v)
234 {
235 Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
236 double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
237 return Geom::Point(( v[Geom::X] - drect.min()[Geom::X] ) / max, ( v[Geom::Y] - drect.min()[Geom::Y] ) / max);
238 }
240 /* Get view point */
241 static Geom::Point
242 sp_eraser_get_vpoint(SPEraserContext const *dc, Geom::Point n)
243 {
244 Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
245 double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
246 return Geom::Point(n[Geom::X] * max + drect.min()[Geom::X], n[Geom::Y] * max + drect.min()[Geom::Y]);
247 }
249 static void
250 sp_eraser_reset(SPEraserContext *dc, Geom::Point p)
251 {
252 dc->last = dc->cur = sp_eraser_get_npoint(dc, p);
253 dc->vel = Geom::Point(0,0);
254 dc->vel_max = 0;
255 dc->acc = Geom::Point(0,0);
256 dc->ang = Geom::Point(0,0);
257 dc->del = Geom::Point(0,0);
258 }
260 static void
261 sp_eraser_extinput(SPEraserContext *dc, GdkEvent *event)
262 {
263 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
264 dc->pressure = CLAMP (dc->pressure, ERC_MIN_PRESSURE, ERC_MAX_PRESSURE);
265 else
266 dc->pressure = ERC_DEFAULT_PRESSURE;
268 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
269 dc->xtilt = CLAMP (dc->xtilt, ERC_MIN_TILT, ERC_MAX_TILT);
270 else
271 dc->xtilt = ERC_DEFAULT_TILT;
273 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
274 dc->ytilt = CLAMP (dc->ytilt, ERC_MIN_TILT, ERC_MAX_TILT);
275 else
276 dc->ytilt = ERC_DEFAULT_TILT;
277 }
280 static gboolean
281 sp_eraser_apply(SPEraserContext *dc, Geom::Point p)
282 {
283 Geom::Point n = sp_eraser_get_npoint(dc, p);
285 /* Calculate mass and drag */
286 double const mass = flerp(1.0, 160.0, dc->mass);
287 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
289 /* Calculate force and acceleration */
290 Geom::Point force = n - dc->cur;
292 // If force is below the absolute threshold ERASER_EPSILON,
293 // or we haven't yet reached ERASER_VEL_START (i.e. at the beginning of stroke)
294 // _and_ the force is below the (higher) ERASER_EPSILON_START threshold,
295 // discard this move.
296 // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
297 // especially bothersome at the start of the stroke where we don't yet have the inertia to
298 // smooth them out.
299 if ( Geom::L2(force) < ERASER_EPSILON || (dc->vel_max < ERASER_VEL_START && Geom::L2(force) < ERASER_EPSILON_START)) {
300 return FALSE;
301 }
303 dc->acc = force / mass;
305 /* Calculate new velocity */
306 dc->vel += dc->acc;
308 if (Geom::L2(dc->vel) > dc->vel_max)
309 dc->vel_max = Geom::L2(dc->vel);
311 /* Calculate angle of drawing tool */
313 double a1;
314 if (dc->usetilt) {
315 // 1a. calculate nib angle from input device tilt:
316 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
318 if (length > 0) {
319 Geom::Point ang1 = Geom::Point(dc->ytilt/length, dc->xtilt/length);
320 a1 = atan2(ang1);
321 }
322 else
323 a1 = 0.0;
324 }
325 else {
326 // 1b. fixed dc->angle (absolutely flat nib):
327 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
328 Geom::Point ang1 = Geom::Point(-sin(radians), cos(radians));
329 a1 = atan2(ang1);
330 }
332 // 2. perpendicular to dc->vel (absolutely non-flat nib):
333 gdouble const mag_vel = Geom::L2(dc->vel);
334 if ( mag_vel < ERASER_EPSILON ) {
335 return FALSE;
336 }
337 Geom::Point ang2 = Geom::rot90(dc->vel) / mag_vel;
339 // 3. Average them using flatness parameter:
340 // calculate angles
341 double a2 = atan2(ang2);
342 // flip a2 to force it to be in the same half-circle as a1
343 bool flipped = false;
344 if (fabs (a2-a1) > 0.5*M_PI) {
345 a2 += M_PI;
346 flipped = true;
347 }
348 // normalize a2
349 if (a2 > M_PI)
350 a2 -= 2*M_PI;
351 if (a2 < -M_PI)
352 a2 += 2*M_PI;
353 // find the flatness-weighted bisector angle, unflip if a2 was flipped
354 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
355 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
357 // Try to detect a sudden flip when the new angle differs too much from the previous for the
358 // current velocity; in that case discard this move
359 double angle_delta = Geom::L2(Geom::Point (cos (new_ang), sin (new_ang)) - dc->ang);
360 if ( angle_delta / Geom::L2(dc->vel) > 4000 ) {
361 return FALSE;
362 }
364 // convert to point
365 dc->ang = Geom::Point (cos (new_ang), sin (new_ang));
367 // g_print ("force %g acc %g vel_max %g vel %g a1 %g a2 %g new_ang %g\n", Geom::L2(force), Geom::L2(dc->acc), dc->vel_max, Geom::L2(dc->vel), a1, a2, new_ang);
369 /* Apply drag */
370 dc->vel *= 1.0 - drag;
372 /* Update position */
373 dc->last = dc->cur;
374 dc->cur += dc->vel;
376 return TRUE;
377 }
379 static void
380 sp_eraser_brush(SPEraserContext *dc)
381 {
382 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
384 // How much velocity thins strokestyle
385 double vel_thin = flerp (0, 160, dc->vel_thin);
387 // Influence of pressure on thickness
388 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
390 // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
391 // drag)
392 Geom::Point brush = sp_eraser_get_vpoint(dc, dc->cur);
393 Geom::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush);
395 double trace_thick = 1;
397 double width = (pressure_thick * trace_thick - vel_thin * Geom::L2(dc->vel)) * dc->width;
399 double tremble_left = 0, tremble_right = 0;
400 if (dc->tremor > 0) {
401 // obtain two normally distributed random variables, using polar Box-Muller transform
402 double x1, x2, w, y1, y2;
403 do {
404 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
405 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
406 w = x1 * x1 + x2 * x2;
407 } while ( w >= 1.0 );
408 w = sqrt( (-2.0 * log( w ) ) / w );
409 y1 = x1 * w;
410 y2 = x2 * w;
412 // deflect both left and right edges randomly and independently, so that:
413 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
414 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
415 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
416 // comparatively smooth and slow ones excessively jittery
417 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
418 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
419 }
421 if ( width < 0.02 * dc->width ) {
422 width = 0.02 * dc->width;
423 }
425 double dezoomify_factor = 0.05 * 1000;
426 if (!dc->abs_width) {
427 dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
428 }
430 Geom::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
431 Geom::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
433 dc->point1[dc->npoints] = brush + del_left;
434 dc->point2[dc->npoints] = brush - del_right;
436 dc->del = 0.5*(del_left + del_right);
438 dc->npoints++;
439 }
441 void
442 sp_erc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
443 {
444 desktop->setToolboxAdjustmentValue (id, value);
445 }
447 static void
448 eraser_cancel(SPEraserContext *dc)
449 {
450 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
451 dc->dragging = FALSE;
452 dc->is_drawing = false;
453 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
454 /* Remove all temporary line segments */
455 while (dc->segments) {
456 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
457 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
458 }
459 /* reset accumulated curve */
460 dc->accumulated->reset();
461 clear_current(dc);
462 if (dc->repr) {
463 dc->repr = NULL;
464 }
465 }
468 gint
469 sp_eraser_context_root_handler(SPEventContext *event_context,
470 GdkEvent *event)
471 {
472 SPEraserContext *dc = SP_ERASER_CONTEXT(event_context);
473 SPDesktop *desktop = event_context->desktop;
475 gint ret = FALSE;
477 switch (event->type) {
478 case GDK_BUTTON_PRESS:
479 if (event->button.button == 1 && !event_context->space_panning) {
481 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
482 return TRUE;
483 }
485 Geom::Point const button_w(event->button.x,
486 event->button.y);
487 Geom::Point const button_dt(desktop->w2d(button_w));
488 sp_eraser_reset(dc, button_dt);
489 sp_eraser_extinput(dc, event);
490 sp_eraser_apply(dc, button_dt);
491 dc->accumulated->reset();
492 if (dc->repr) {
493 dc->repr = NULL;
494 }
496 Inkscape::Rubberband::get(desktop)->start(desktop, button_dt);
497 Inkscape::Rubberband::get(desktop)->setMode(RUBBERBAND_MODE_TOUCHPATH);
499 /* initialize first point */
500 dc->npoints = 0;
502 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
503 ( GDK_KEY_PRESS_MASK |
504 GDK_BUTTON_RELEASE_MASK |
505 GDK_POINTER_MOTION_MASK |
506 GDK_BUTTON_PRESS_MASK ),
507 NULL,
508 event->button.time);
510 ret = TRUE;
512 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
513 dc->is_drawing = true;
514 }
515 break;
516 case GDK_MOTION_NOTIFY:
517 {
518 Geom::Point const motion_w(event->motion.x,
519 event->motion.y);
520 Geom::Point motion_dt(desktop->w2d(motion_w));
521 sp_eraser_extinput(dc, event);
523 dc->_message_context->clear();
525 if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
526 dc->dragging = TRUE;
528 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> an eraser stroke"));
530 if (!sp_eraser_apply(dc, motion_dt)) {
531 ret = TRUE;
532 break;
533 }
535 if ( dc->cur != dc->last ) {
536 sp_eraser_brush(dc);
537 g_assert( dc->npoints > 0 );
538 fit_and_split(dc, FALSE);
539 }
540 ret = TRUE;
541 }
542 Inkscape::Rubberband::get(desktop)->move(motion_dt);
543 }
544 break;
547 case GDK_BUTTON_RELEASE:
548 {
549 Geom::Point const motion_w(event->button.x, event->button.y);
550 Geom::Point const motion_dt(desktop->w2d(motion_w));
552 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
553 sp_canvas_end_forced_full_redraws(desktop->canvas);
554 dc->is_drawing = false;
556 if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
557 dc->dragging = FALSE;
559 sp_eraser_apply(dc, motion_dt);
561 /* Remove all temporary line segments */
562 while (dc->segments) {
563 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
564 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
565 }
567 /* Create object */
568 fit_and_split(dc, TRUE);
569 accumulate_eraser(dc);
570 set_to_accumulated(dc); // performs document_done
572 /* reset accumulated curve */
573 dc->accumulated->reset();
575 clear_current(dc);
576 if (dc->repr) {
577 dc->repr = NULL;
578 }
580 Inkscape::Rubberband::get(desktop)->stop();
581 dc->_message_context->clear();
582 ret = TRUE;
583 }
584 break;
585 }
587 case GDK_KEY_PRESS:
588 switch (get_group0_keyval (&event->key)) {
589 case GDK_Up:
590 case GDK_KP_Up:
591 if (!MOD__CTRL_ONLY) {
592 dc->angle += 5.0;
593 if (dc->angle > 90.0)
594 dc->angle = 90.0;
595 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
596 ret = TRUE;
597 }
598 break;
599 case GDK_Down:
600 case GDK_KP_Down:
601 if (!MOD__CTRL_ONLY) {
602 dc->angle -= 5.0;
603 if (dc->angle < -90.0)
604 dc->angle = -90.0;
605 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
606 ret = TRUE;
607 }
608 break;
609 case GDK_Right:
610 case GDK_KP_Right:
611 if (!MOD__CTRL_ONLY) {
612 dc->width += 0.01;
613 if (dc->width > 1.0)
614 dc->width = 1.0;
615 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100); // the same spinbutton is for alt+x
616 ret = TRUE;
617 }
618 break;
619 case GDK_Left:
620 case GDK_KP_Left:
621 if (!MOD__CTRL_ONLY) {
622 dc->width -= 0.01;
623 if (dc->width < 0.01)
624 dc->width = 0.01;
625 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
626 ret = TRUE;
627 }
628 break;
629 case GDK_Home:
630 case GDK_KP_Home:
631 dc->width = 0.01;
632 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
633 ret = TRUE;
634 break;
635 case GDK_End:
636 case GDK_KP_End:
637 dc->width = 1.0;
638 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
639 ret = TRUE;
640 break;
641 case GDK_x:
642 case GDK_X:
643 if (MOD__ALT_ONLY) {
644 desktop->setToolboxFocusTo ("altx-eraser");
645 ret = TRUE;
646 }
647 break;
648 case GDK_Escape:
649 Inkscape::Rubberband::get(desktop)->stop();
650 if (dc->is_drawing) {
651 // if drawing, cancel, otherwise pass it up for deselecting
652 eraser_cancel (dc);
653 ret = TRUE;
654 }
655 break;
656 case GDK_z:
657 case GDK_Z:
658 if (MOD__CTRL_ONLY && dc->is_drawing) {
659 // if drawing, cancel, otherwise pass it up for undo
660 eraser_cancel (dc);
661 ret = TRUE;
662 }
663 break;
664 default:
665 break;
666 }
667 break;
669 case GDK_KEY_RELEASE:
670 switch (get_group0_keyval(&event->key)) {
671 case GDK_Control_L:
672 case GDK_Control_R:
673 dc->_message_context->clear();
674 break;
675 default:
676 break;
677 }
679 default:
680 break;
681 }
683 if (!ret) {
684 if (((SPEventContextClass *) eraser_parent_class)->root_handler) {
685 ret = ((SPEventContextClass *) eraser_parent_class)->root_handler(event_context, event);
686 }
687 }
689 return ret;
690 }
693 static void
694 clear_current(SPEraserContext *dc)
695 {
696 // reset bpath
697 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
699 // reset curve
700 dc->currentcurve->reset();
701 dc->cal1->reset();
702 dc->cal2->reset();
704 // reset points
705 dc->npoints = 0;
706 }
708 static void
709 set_to_accumulated(SPEraserContext *dc)
710 {
711 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
712 bool workDone = false;
714 if (!dc->accumulated->is_empty()) {
715 if (!dc->repr) {
716 /* Create object */
717 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
718 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
720 /* Set style */
721 sp_desktop_apply_style_tool (desktop, repr, "/tools/eraser", false);
723 dc->repr = repr;
725 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
726 Inkscape::GC::release(dc->repr);
727 item->transform = sp_item_i2doc_affine(SP_ITEM(desktop->currentLayer())).inverse();
728 item->updateRepr();
729 }
730 Geom::PathVector pathv = dc->accumulated->get_pathvector() * sp_desktop_dt2doc_affine(desktop);
731 gchar *str = sp_svg_write_path(pathv);
732 g_assert( str != NULL );
733 dc->repr->setAttribute("d", str);
734 g_free(str);
736 if ( dc->repr ) {
737 bool wasSelection = false;
738 Inkscape::Selection *selection = sp_desktop_selection(desktop);
739 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
741 gint eraserMode = prefs->getBool("/tools/eraser/mode") ? 1 : 0;
742 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
744 SPItem* acid = SP_ITEM(desktop->doc()->getObjectByRepr(dc->repr));
745 Geom::OptRect eraserBbox = acid->getBounds(Geom::identity());
746 Geom::Rect bounds = (*eraserBbox) * desktop->doc2dt();
747 std::vector<SPItem*> remainingItems;
748 GSList* toWorkOn = 0;
749 if (selection->isEmpty()) {
750 if ( eraserMode ) {
751 toWorkOn = sp_document_partial_items_in_box(sp_desktop_document(desktop), desktop->dkey, bounds);
752 } else {
753 Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get(desktop);
754 toWorkOn = sp_document_items_at_points(sp_desktop_document(desktop), desktop->dkey, r->getPoints());
755 }
756 toWorkOn = g_slist_remove( toWorkOn, acid );
757 } else {
758 toWorkOn = g_slist_copy(const_cast<GSList*>(selection->itemList()));
759 wasSelection = true;
760 }
762 if ( g_slist_length(toWorkOn) > 0 ) {
763 if ( eraserMode ) {
764 for (GSList *i = toWorkOn ; i ; i = i->next ) {
765 SPItem *item = SP_ITEM(i->data);
766 if ( eraserMode ) {
767 Geom::OptRect bbox = item->getBounds(Geom::identity());
768 if (bbox && bbox->intersects(*eraserBbox)) {
769 Inkscape::XML::Node* dup = dc->repr->duplicate(xml_doc);
770 dc->repr->parent()->appendChild(dup);
771 Inkscape::GC::release(dup); // parent takes over
773 selection->set(item);
774 selection->add(dup);
775 sp_selected_path_diff_skip_undo(desktop);
776 workDone = true; // TODO set this only if something was cut.
777 if ( !selection->isEmpty() ) {
778 // If the item was not completely erased, track the new remainder.
779 GSList *nowSel = g_slist_copy(const_cast<GSList *>(selection->itemList()));
780 for (GSList const *i2 = nowSel ; i2 ; i2 = i2->next ) {
781 remainingItems.push_back(SP_ITEM(i2->data));
782 }
783 g_slist_free(nowSel);
784 }
785 } else {
786 remainingItems.push_back(item);
787 }
788 }
789 }
790 } else {
791 for (GSList *i = toWorkOn ; i ; i = i->next ) {
792 sp_object_ref( SP_ITEM(i->data), 0 );
793 }
794 for (GSList *i = toWorkOn ; i ; i = i->next ) {
795 SPItem *item = SP_ITEM(i->data);
796 item->deleteObject(true);
797 sp_object_unref(item);
798 workDone = true;
799 }
800 }
802 g_slist_free(toWorkOn);
804 if ( !eraserMode ) {
805 //sp_selection_delete(desktop);
806 remainingItems.clear();
807 }
809 selection->clear();
810 if ( wasSelection ) {
811 if ( !remainingItems.empty() ) {
812 selection->add(remainingItems.begin(), remainingItems.end());
813 }
814 }
815 }
817 // Remove the eraser stroke itself:
818 sp_repr_unparent( dc->repr );
819 dc->repr = 0;
820 }
821 } else {
822 if (dc->repr) {
823 sp_repr_unparent(dc->repr);
824 dc->repr = 0;
825 }
826 }
829 if ( workDone ) {
830 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_ERASER,
831 _("Draw eraser stroke"));
832 } else {
833 sp_document_cancel(sp_desktop_document(desktop));
834 }
835 }
837 static void
838 add_cap(SPCurve *curve,
839 Geom::Point const &pre, Geom::Point const &from,
840 Geom::Point const &to, Geom::Point const &post,
841 double rounding)
842 {
843 Geom::Point vel = rounding * Geom::rot90( to - from ) / sqrt(2.0);
844 double mag = Geom::L2(vel);
846 Geom::Point v_in = from - pre;
847 double mag_in = Geom::L2(v_in);
848 if ( mag_in > ERASER_EPSILON ) {
849 v_in = mag * v_in / mag_in;
850 } else {
851 v_in = Geom::Point(0, 0);
852 }
854 Geom::Point v_out = to - post;
855 double mag_out = Geom::L2(v_out);
856 if ( mag_out > ERASER_EPSILON ) {
857 v_out = mag * v_out / mag_out;
858 } else {
859 v_out = Geom::Point(0, 0);
860 }
862 if ( Geom::L2(v_in) > ERASER_EPSILON || Geom::L2(v_out) > ERASER_EPSILON ) {
863 curve->curveto(from + v_in, to + v_out, to);
864 }
865 }
867 static void
868 accumulate_eraser(SPEraserContext *dc)
869 {
870 if ( !dc->cal1->is_empty() && !dc->cal2->is_empty() ) {
871 dc->accumulated->reset(); /* Is this required ?? */
872 SPCurve *rev_cal2 = dc->cal2->create_reverse();
874 g_assert(dc->cal1->get_segment_count() > 0);
875 g_assert(rev_cal2->get_segment_count() > 0);
876 g_assert( ! dc->cal1->first_path()->closed() );
877 g_assert( ! rev_cal2->first_path()->closed() );
879 Geom::CubicBezier const * dc_cal1_firstseg = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->first_segment() );
880 Geom::CubicBezier const * rev_cal2_firstseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->first_segment() );
881 Geom::CubicBezier const * dc_cal1_lastseg = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->last_segment() );
882 Geom::CubicBezier const * rev_cal2_lastseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->last_segment() );
883 g_assert( dc_cal1_firstseg );
884 g_assert( rev_cal2_firstseg );
885 g_assert( dc_cal1_lastseg );
886 g_assert( rev_cal2_lastseg );
888 dc->accumulated->append(dc->cal1, FALSE);
890 add_cap(dc->accumulated, (*dc_cal1_lastseg)[2], (*dc_cal1_lastseg)[3], (*rev_cal2_firstseg)[0], (*rev_cal2_firstseg)[1], dc->cap_rounding);
892 dc->accumulated->append(rev_cal2, TRUE);
894 add_cap(dc->accumulated, (*rev_cal2_lastseg)[2], (*rev_cal2_lastseg)[3], (*dc_cal1_firstseg)[0], (*dc_cal1_firstseg)[1], dc->cap_rounding);
896 dc->accumulated->closepath();
898 rev_cal2->unref();
900 dc->cal1->reset();
901 dc->cal2->reset();
902 }
903 }
905 static double square(double const x)
906 {
907 return x * x;
908 }
910 static void
911 fit_and_split(SPEraserContext *dc, gboolean release)
912 {
913 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
915 double const tolerance_sq = square( desktop->w2d().descrim() * TOLERANCE_ERASER );
917 #ifdef ERASER_VERBOSE
918 g_print("[F&S:R=%c]", release?'T':'F');
919 #endif
921 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
922 return; // just clicked
924 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
925 #define BEZIER_SIZE 4
926 #define BEZIER_MAX_BEZIERS 8
927 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
929 #ifdef ERASER_VERBOSE
930 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
931 dc->npoints, release ? "TRUE" : "FALSE");
932 #endif
934 /* Current eraser */
935 if ( dc->cal1->is_empty() || dc->cal2->is_empty() ) {
936 /* dc->npoints > 0 */
937 /* g_print("erasers(1|2) reset\n"); */
938 dc->cal1->reset();
939 dc->cal2->reset();
941 dc->cal1->moveto(dc->point1[0]);
942 dc->cal2->moveto(dc->point2[0]);
943 }
945 Geom::Point b1[BEZIER_MAX_LENGTH];
946 gint const nb1 = Geom::bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
947 tolerance_sq, BEZIER_MAX_BEZIERS);
948 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
950 Geom::Point b2[BEZIER_MAX_LENGTH];
951 gint const nb2 = Geom::bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
952 tolerance_sq, BEZIER_MAX_BEZIERS);
953 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
955 if ( nb1 != -1 && nb2 != -1 ) {
956 /* Fit and draw and reset state */
957 #ifdef ERASER_VERBOSE
958 g_print("nb1:%d nb2:%d\n", nb1, nb2);
959 #endif
960 /* CanvasShape */
961 if (! release) {
962 dc->currentcurve->reset();
963 dc->currentcurve->moveto(b1[0]);
964 for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
965 dc->currentcurve->curveto(bp1[1],
966 bp1[2], bp1[3]);
967 }
968 dc->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]);
969 for (Geom::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
970 dc->currentcurve->curveto(bp2[2], bp2[1], bp2[0]);
971 }
972 // FIXME: dc->segments is always NULL at this point??
973 if (!dc->segments) { // first segment
974 add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
975 }
976 dc->currentcurve->closepath();
977 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
978 }
980 /* Current eraser */
981 for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
982 dc->cal1->curveto(bp1[1], bp1[2], bp1[3]);
983 }
984 for (Geom::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
985 dc->cal2->curveto(bp2[1], bp2[2], bp2[3]);
986 }
987 } else {
988 /* fixme: ??? */
989 #ifdef ERASER_VERBOSE
990 g_print("[fit_and_split] failed to fit-cubic.\n");
991 #endif
992 draw_temporary_box(dc);
994 for (gint i = 1; i < dc->npoints; i++) {
995 dc->cal1->lineto(dc->point1[i]);
996 }
997 for (gint i = 1; i < dc->npoints; i++) {
998 dc->cal2->lineto(dc->point2[i]);
999 }
1000 }
1002 /* Fit and draw and copy last point */
1003 #ifdef ERASER_VERBOSE
1004 g_print("[%d]Yup\n", dc->npoints);
1005 #endif
1006 if (!release) {
1007 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1008 gint eraserMode = prefs->getBool("/tools/eraser/mode") ? 1 : 0;
1009 g_assert(!dc->currentcurve->is_empty());
1011 SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(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 (desktop, "/tools/eraser", true);
1019 //guint32 strokeColor = sp_desktop_get_color_tool (desktop, "/tools/eraser", false);
1020 double opacity = sp_desktop_get_master_opacity_tool (desktop, "/tools/eraser");
1021 double fillOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/eraser", true);
1022 //double strokeOpacity = sp_desktop_get_opacity_tool (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), 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 :