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-style.h"
47 #include "message-context.h"
48 #include "preferences.h"
49 #include "pixmaps/cursor-eraser.xpm"
50 #include "xml/repr.h"
51 #include "context-fns.h"
52 #include "sp-item.h"
53 #include "color.h"
54 #include "rubberband.h"
55 #include "splivarot.h"
56 #include "sp-item-group.h"
57 #include "sp-shape.h"
58 #include "sp-path.h"
59 #include "sp-text.h"
60 #include "display/canvas-bpath.h"
61 #include "display/canvas-arena.h"
62 #include "livarot/Shape.h"
63 #include <2geom/isnan.h>
64 #include <2geom/pathvector.h>
66 #include "eraser-context.h"
68 #define ERC_RED_RGBA 0xff0000ff
70 #define TOLERANCE_ERASER 0.1
72 #define ERASER_EPSILON 0.5e-6
73 #define ERASER_EPSILON_START 0.5e-2
74 #define ERASER_VEL_START 1e-5
76 #define DRAG_MIN 0.0
77 #define DRAG_DEFAULT 1.0
78 #define DRAG_MAX 1.0
81 static void sp_eraser_context_class_init(SPEraserContextClass *klass);
82 static void sp_eraser_context_init(SPEraserContext *erc);
83 static void sp_eraser_context_dispose(GObject *object);
85 static void sp_eraser_context_setup(SPEventContext *ec);
86 static void sp_eraser_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val);
87 static gint sp_eraser_context_root_handler(SPEventContext *ec, GdkEvent *event);
89 static void clear_current(SPEraserContext *dc);
90 static void set_to_accumulated(SPEraserContext *dc);
91 static void add_cap(SPCurve *curve, Geom::Point const &pre, Geom::Point const &from, Geom::Point const &to, Geom::Point const &post, double rounding);
92 static void accumulate_eraser(SPEraserContext *dc);
94 static void fit_and_split(SPEraserContext *erc, gboolean release);
96 static void sp_eraser_reset(SPEraserContext *erc, Geom::Point p);
97 static Geom::Point sp_eraser_get_npoint(SPEraserContext const *erc, Geom::Point v);
98 static Geom::Point sp_eraser_get_vpoint(SPEraserContext const *erc, Geom::Point n);
99 static void draw_temporary_box(SPEraserContext *dc);
102 static SPEventContextClass *eraser_parent_class = 0;
104 GType sp_eraser_context_get_type(void)
105 {
106 static GType type = 0;
107 if (!type) {
108 GTypeInfo info = {
109 sizeof(SPEraserContextClass),
110 0, // base_init
111 0, // base_finalize
112 (GClassInitFunc)sp_eraser_context_class_init,
113 0, // class_finalize
114 0, // class_data
115 sizeof(SPEraserContext),
116 0, // n_preallocs
117 (GInstanceInitFunc)sp_eraser_context_init,
118 0 // value_table
119 };
120 type = g_type_register_static(SP_TYPE_COMMON_CONTEXT, "SPEraserContext", &info, static_cast<GTypeFlags>(0));
121 }
122 return type;
123 }
125 static void
126 sp_eraser_context_class_init(SPEraserContextClass *klass)
127 {
128 GObjectClass *object_class = (GObjectClass *) klass;
129 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
131 eraser_parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
133 object_class->dispose = sp_eraser_context_dispose;
135 event_context_class->setup = sp_eraser_context_setup;
136 event_context_class->set = sp_eraser_context_set;
137 event_context_class->root_handler = sp_eraser_context_root_handler;
138 }
140 static void
141 sp_eraser_context_init(SPEraserContext *erc)
142 {
143 erc->cursor_shape = cursor_eraser_xpm;
144 erc->hot_x = 4;
145 erc->hot_y = 4;
146 }
148 static void
149 sp_eraser_context_dispose(GObject *object)
150 {
151 //SPEraserContext *erc = SP_ERASER_CONTEXT(object);
153 G_OBJECT_CLASS(eraser_parent_class)->dispose(object);
154 }
156 static void
157 sp_eraser_context_setup(SPEventContext *ec)
158 {
159 SPEraserContext *erc = SP_ERASER_CONTEXT(ec);
160 SPDesktop *desktop = ec->desktop;
162 if (((SPEventContextClass *) eraser_parent_class)->setup)
163 ((SPEventContextClass *) eraser_parent_class)->setup(ec);
165 erc->accumulated = new SPCurve();
166 erc->currentcurve = new SPCurve();
168 erc->cal1 = new SPCurve();
169 erc->cal2 = new SPCurve();
171 erc->currentshape = sp_canvas_item_new(sp_desktop_sketch(desktop), SP_TYPE_CANVAS_BPATH, NULL);
172 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(erc->currentshape), ERC_RED_RGBA, SP_WIND_RULE_EVENODD);
173 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(erc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
174 /* fixme: Cannot we cascade it to root more clearly? */
175 g_signal_connect(G_OBJECT(erc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), desktop);
177 /*
178 static ProfileFloatElement f_profile[PROFILE_FLOAT_SIZE] = {
179 {"mass",0.02, 0.0, 1.0},
180 {"wiggle",0.0, 0.0, 1.0},
181 {"angle",30.0, -90.0, 90.0},
182 {"thinning",0.1, -1.0, 1.0},
183 {"tremor",0.0, 0.0, 1.0},
184 {"flatness",0.9, 0.0, 1.0},
185 {"cap_rounding",0.0, 0.0, 5.0}
186 };
187 */
189 sp_event_context_read(ec, "mass");
190 sp_event_context_read(ec, "wiggle");
191 sp_event_context_read(ec, "angle");
192 sp_event_context_read(ec, "width");
193 sp_event_context_read(ec, "thinning");
194 sp_event_context_read(ec, "tremor");
195 sp_event_context_read(ec, "flatness");
196 sp_event_context_read(ec, "tracebackground");
197 sp_event_context_read(ec, "usepressure");
198 sp_event_context_read(ec, "usetilt");
199 sp_event_context_read(ec, "abs_width");
200 sp_event_context_read(ec, "cap_rounding");
202 erc->is_drawing = false;
204 erc->_message_context = new Inkscape::MessageContext(desktop->messageStack());
206 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
207 if (prefs->getBool("/tools/eraser/selcue", 0) != 0) {
208 ec->enableSelectionCue();
209 }
210 // TODO temp force:
211 ec->enableSelectionCue();
213 }
215 static void
216 sp_eraser_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val)
217 {
218 //pass on up to parent class to handle common attributes.
219 if ( eraser_parent_class->set ) {
220 eraser_parent_class->set(ec, val);
221 }
222 }
224 static double
225 flerp(double f0, double f1, double p)
226 {
227 return f0 + ( f1 - f0 ) * p;
228 }
230 /* Get normalized point */
231 static Geom::Point
232 sp_eraser_get_npoint(SPEraserContext const *dc, Geom::Point v)
233 {
234 Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
235 double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
236 return Geom::Point(( v[Geom::X] - drect.min()[Geom::X] ) / max, ( v[Geom::Y] - drect.min()[Geom::Y] ) / max);
237 }
239 /* Get view point */
240 static Geom::Point
241 sp_eraser_get_vpoint(SPEraserContext const *dc, Geom::Point n)
242 {
243 Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
244 double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
245 return Geom::Point(n[Geom::X] * max + drect.min()[Geom::X], n[Geom::Y] * max + drect.min()[Geom::Y]);
246 }
248 static void
249 sp_eraser_reset(SPEraserContext *dc, Geom::Point p)
250 {
251 dc->last = dc->cur = sp_eraser_get_npoint(dc, p);
252 dc->vel = Geom::Point(0,0);
253 dc->vel_max = 0;
254 dc->acc = Geom::Point(0,0);
255 dc->ang = Geom::Point(0,0);
256 dc->del = Geom::Point(0,0);
257 }
259 static void
260 sp_eraser_extinput(SPEraserContext *dc, GdkEvent *event)
261 {
262 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
263 dc->pressure = CLAMP (dc->pressure, ERC_MIN_PRESSURE, ERC_MAX_PRESSURE);
264 else
265 dc->pressure = ERC_DEFAULT_PRESSURE;
267 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
268 dc->xtilt = CLAMP (dc->xtilt, ERC_MIN_TILT, ERC_MAX_TILT);
269 else
270 dc->xtilt = ERC_DEFAULT_TILT;
272 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
273 dc->ytilt = CLAMP (dc->ytilt, ERC_MIN_TILT, ERC_MAX_TILT);
274 else
275 dc->ytilt = ERC_DEFAULT_TILT;
276 }
279 static gboolean
280 sp_eraser_apply(SPEraserContext *dc, Geom::Point p)
281 {
282 Geom::Point n = sp_eraser_get_npoint(dc, p);
284 /* Calculate mass and drag */
285 double const mass = flerp(1.0, 160.0, dc->mass);
286 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
288 /* Calculate force and acceleration */
289 Geom::Point force = n - dc->cur;
291 // If force is below the absolute threshold ERASER_EPSILON,
292 // or we haven't yet reached ERASER_VEL_START (i.e. at the beginning of stroke)
293 // _and_ the force is below the (higher) ERASER_EPSILON_START threshold,
294 // discard this move.
295 // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
296 // especially bothersome at the start of the stroke where we don't yet have the inertia to
297 // smooth them out.
298 if ( Geom::L2(force) < ERASER_EPSILON || (dc->vel_max < ERASER_VEL_START && Geom::L2(force) < ERASER_EPSILON_START)) {
299 return FALSE;
300 }
302 dc->acc = force / mass;
304 /* Calculate new velocity */
305 dc->vel += dc->acc;
307 if (Geom::L2(dc->vel) > dc->vel_max)
308 dc->vel_max = Geom::L2(dc->vel);
310 /* Calculate angle of drawing tool */
312 double a1;
313 if (dc->usetilt) {
314 // 1a. calculate nib angle from input device tilt:
315 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
317 if (length > 0) {
318 Geom::Point ang1 = Geom::Point(dc->ytilt/length, dc->xtilt/length);
319 a1 = atan2(ang1);
320 }
321 else
322 a1 = 0.0;
323 }
324 else {
325 // 1b. fixed dc->angle (absolutely flat nib):
326 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
327 Geom::Point ang1 = Geom::Point(-sin(radians), cos(radians));
328 a1 = atan2(ang1);
329 }
331 // 2. perpendicular to dc->vel (absolutely non-flat nib):
332 gdouble const mag_vel = Geom::L2(dc->vel);
333 if ( mag_vel < ERASER_EPSILON ) {
334 return FALSE;
335 }
336 Geom::Point ang2 = Geom::rot90(dc->vel) / mag_vel;
338 // 3. Average them using flatness parameter:
339 // calculate angles
340 double a2 = atan2(ang2);
341 // flip a2 to force it to be in the same half-circle as a1
342 bool flipped = false;
343 if (fabs (a2-a1) > 0.5*M_PI) {
344 a2 += M_PI;
345 flipped = true;
346 }
347 // normalize a2
348 if (a2 > M_PI)
349 a2 -= 2*M_PI;
350 if (a2 < -M_PI)
351 a2 += 2*M_PI;
352 // find the flatness-weighted bisector angle, unflip if a2 was flipped
353 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
354 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
356 // Try to detect a sudden flip when the new angle differs too much from the previous for the
357 // current velocity; in that case discard this move
358 double angle_delta = Geom::L2(Geom::Point (cos (new_ang), sin (new_ang)) - dc->ang);
359 if ( angle_delta / Geom::L2(dc->vel) > 4000 ) {
360 return FALSE;
361 }
363 // convert to point
364 dc->ang = Geom::Point (cos (new_ang), sin (new_ang));
366 // 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);
368 /* Apply drag */
369 dc->vel *= 1.0 - drag;
371 /* Update position */
372 dc->last = dc->cur;
373 dc->cur += dc->vel;
375 return TRUE;
376 }
378 static void
379 sp_eraser_brush(SPEraserContext *dc)
380 {
381 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
383 // How much velocity thins strokestyle
384 double vel_thin = flerp (0, 160, dc->vel_thin);
386 // Influence of pressure on thickness
387 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
389 // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
390 // drag)
391 Geom::Point brush = sp_eraser_get_vpoint(dc, dc->cur);
392 Geom::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush);
394 double trace_thick = 1;
396 double width = (pressure_thick * trace_thick - vel_thin * Geom::L2(dc->vel)) * dc->width;
398 double tremble_left = 0, tremble_right = 0;
399 if (dc->tremor > 0) {
400 // obtain two normally distributed random variables, using polar Box-Muller transform
401 double x1, x2, w, y1, y2;
402 do {
403 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
404 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
405 w = x1 * x1 + x2 * x2;
406 } while ( w >= 1.0 );
407 w = sqrt( (-2.0 * log( w ) ) / w );
408 y1 = x1 * w;
409 y2 = x2 * w;
411 // deflect both left and right edges randomly and independently, so that:
412 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
413 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
414 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
415 // comparatively smooth and slow ones excessively jittery
416 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
417 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
418 }
420 if ( width < 0.02 * dc->width ) {
421 width = 0.02 * dc->width;
422 }
424 double dezoomify_factor = 0.05 * 1000;
425 if (!dc->abs_width) {
426 dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
427 }
429 Geom::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
430 Geom::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
432 dc->point1[dc->npoints] = brush + del_left;
433 dc->point2[dc->npoints] = brush - del_right;
435 dc->del = 0.5*(del_left + del_right);
437 dc->npoints++;
438 }
440 void
441 sp_erc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
442 {
443 desktop->setToolboxAdjustmentValue (id, value);
444 }
446 static void
447 eraser_cancel(SPEraserContext *dc)
448 {
449 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
450 dc->dragging = FALSE;
451 dc->is_drawing = false;
452 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
453 /* Remove all temporary line segments */
454 while (dc->segments) {
455 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
456 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
457 }
458 /* reset accumulated curve */
459 dc->accumulated->reset();
460 clear_current(dc);
461 if (dc->repr) {
462 dc->repr = NULL;
463 }
464 }
467 gint
468 sp_eraser_context_root_handler(SPEventContext *event_context,
469 GdkEvent *event)
470 {
471 SPEraserContext *dc = SP_ERASER_CONTEXT(event_context);
472 SPDesktop *desktop = event_context->desktop;
474 gint ret = FALSE;
476 switch (event->type) {
477 case GDK_BUTTON_PRESS:
478 if (event->button.button == 1 && !event_context->space_panning) {
480 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
481 return TRUE;
482 }
484 Geom::Point const button_w(event->button.x,
485 event->button.y);
486 Geom::Point const button_dt(desktop->w2d(button_w));
487 sp_eraser_reset(dc, button_dt);
488 sp_eraser_extinput(dc, event);
489 sp_eraser_apply(dc, button_dt);
490 dc->accumulated->reset();
491 if (dc->repr) {
492 dc->repr = NULL;
493 }
495 Inkscape::Rubberband::get(desktop)->start(desktop, button_dt);
496 Inkscape::Rubberband::get(desktop)->setMode(RUBBERBAND_MODE_TOUCHPATH);
498 /* initialize first point */
499 dc->npoints = 0;
501 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
502 ( GDK_KEY_PRESS_MASK |
503 GDK_BUTTON_RELEASE_MASK |
504 GDK_POINTER_MOTION_MASK |
505 GDK_BUTTON_PRESS_MASK ),
506 NULL,
507 event->button.time);
509 ret = TRUE;
511 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
512 dc->is_drawing = true;
513 }
514 break;
515 case GDK_MOTION_NOTIFY:
516 {
517 Geom::Point const motion_w(event->motion.x,
518 event->motion.y);
519 Geom::Point motion_dt(desktop->w2d(motion_w));
520 sp_eraser_extinput(dc, event);
522 dc->_message_context->clear();
524 if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
525 dc->dragging = TRUE;
527 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> an eraser stroke"));
529 if (!sp_eraser_apply(dc, motion_dt)) {
530 ret = TRUE;
531 break;
532 }
534 if ( dc->cur != dc->last ) {
535 sp_eraser_brush(dc);
536 g_assert( dc->npoints > 0 );
537 fit_and_split(dc, FALSE);
538 }
539 ret = TRUE;
540 }
541 Inkscape::Rubberband::get(desktop)->move(motion_dt);
542 }
543 break;
546 case GDK_BUTTON_RELEASE:
547 {
548 Geom::Point const motion_w(event->button.x, event->button.y);
549 Geom::Point const motion_dt(desktop->w2d(motion_w));
551 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
552 sp_canvas_end_forced_full_redraws(desktop->canvas);
553 dc->is_drawing = false;
555 if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
556 dc->dragging = FALSE;
558 sp_eraser_apply(dc, motion_dt);
560 /* Remove all temporary line segments */
561 while (dc->segments) {
562 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
563 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
564 }
566 /* Create object */
567 fit_and_split(dc, TRUE);
568 accumulate_eraser(dc);
569 set_to_accumulated(dc); // performs document_done
571 /* reset accumulated curve */
572 dc->accumulated->reset();
574 clear_current(dc);
575 if (dc->repr) {
576 dc->repr = NULL;
577 }
579 dc->_message_context->clear();
580 ret = TRUE;
581 }
582 if (Inkscape::Rubberband::get(desktop)->is_started()) {
583 Inkscape::Rubberband::get(desktop)->stop();
584 }
586 break;
587 }
589 case GDK_KEY_PRESS:
590 switch (get_group0_keyval (&event->key)) {
591 case GDK_Up:
592 case GDK_KP_Up:
593 if (!MOD__CTRL_ONLY) {
594 dc->angle += 5.0;
595 if (dc->angle > 90.0)
596 dc->angle = 90.0;
597 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
598 ret = TRUE;
599 }
600 break;
601 case GDK_Down:
602 case GDK_KP_Down:
603 if (!MOD__CTRL_ONLY) {
604 dc->angle -= 5.0;
605 if (dc->angle < -90.0)
606 dc->angle = -90.0;
607 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
608 ret = TRUE;
609 }
610 break;
611 case GDK_Right:
612 case GDK_KP_Right:
613 if (!MOD__CTRL_ONLY) {
614 dc->width += 0.01;
615 if (dc->width > 1.0)
616 dc->width = 1.0;
617 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100); // the same spinbutton is for alt+x
618 ret = TRUE;
619 }
620 break;
621 case GDK_Left:
622 case GDK_KP_Left:
623 if (!MOD__CTRL_ONLY) {
624 dc->width -= 0.01;
625 if (dc->width < 0.01)
626 dc->width = 0.01;
627 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
628 ret = TRUE;
629 }
630 break;
631 case GDK_Home:
632 case GDK_KP_Home:
633 dc->width = 0.01;
634 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
635 ret = TRUE;
636 break;
637 case GDK_End:
638 case GDK_KP_End:
639 dc->width = 1.0;
640 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
641 ret = TRUE;
642 break;
643 case GDK_x:
644 case GDK_X:
645 if (MOD__ALT_ONLY) {
646 desktop->setToolboxFocusTo ("altx-eraser");
647 ret = TRUE;
648 }
649 break;
650 case GDK_Escape:
651 Inkscape::Rubberband::get(desktop)->stop();
652 if (dc->is_drawing) {
653 // if drawing, cancel, otherwise pass it up for deselecting
654 eraser_cancel (dc);
655 ret = TRUE;
656 }
657 break;
658 case GDK_z:
659 case GDK_Z:
660 if (MOD__CTRL_ONLY && dc->is_drawing) {
661 // if drawing, cancel, otherwise pass it up for undo
662 eraser_cancel (dc);
663 ret = TRUE;
664 }
665 break;
666 default:
667 break;
668 }
669 break;
671 case GDK_KEY_RELEASE:
672 switch (get_group0_keyval(&event->key)) {
673 case GDK_Control_L:
674 case GDK_Control_R:
675 dc->_message_context->clear();
676 break;
677 default:
678 break;
679 }
681 default:
682 break;
683 }
685 if (!ret) {
686 if (((SPEventContextClass *) eraser_parent_class)->root_handler) {
687 ret = ((SPEventContextClass *) eraser_parent_class)->root_handler(event_context, event);
688 }
689 }
691 return ret;
692 }
695 static void
696 clear_current(SPEraserContext *dc)
697 {
698 // reset bpath
699 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
701 // reset curve
702 dc->currentcurve->reset();
703 dc->cal1->reset();
704 dc->cal2->reset();
706 // reset points
707 dc->npoints = 0;
708 }
710 static void
711 set_to_accumulated(SPEraserContext *dc)
712 {
713 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
714 bool workDone = false;
716 if (!dc->accumulated->is_empty()) {
717 if (!dc->repr) {
718 /* Create object */
719 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
720 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
722 /* Set style */
723 sp_desktop_apply_style_tool (desktop, repr, "/tools/eraser", false);
725 dc->repr = repr;
727 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
728 Inkscape::GC::release(dc->repr);
729 item->transform = sp_item_i2doc_affine(SP_ITEM(desktop->currentLayer())).inverse();
730 item->updateRepr();
731 }
732 Geom::PathVector pathv = dc->accumulated->get_pathvector() * desktop->dt2doc();
733 gchar *str = sp_svg_write_path(pathv);
734 g_assert( str != NULL );
735 dc->repr->setAttribute("d", str);
736 g_free(str);
738 if ( dc->repr ) {
739 bool wasSelection = false;
740 Inkscape::Selection *selection = sp_desktop_selection(desktop);
741 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
743 gint eraserMode = prefs->getBool("/tools/eraser/mode") ? 1 : 0;
744 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
746 SPItem* acid = SP_ITEM(desktop->doc()->getObjectByRepr(dc->repr));
747 Geom::OptRect eraserBbox = acid->getBounds(Geom::identity());
748 Geom::Rect bounds = (*eraserBbox) * desktop->doc2dt();
749 std::vector<SPItem*> remainingItems;
750 GSList* toWorkOn = 0;
751 if (selection->isEmpty()) {
752 if ( eraserMode ) {
753 toWorkOn = sp_document_partial_items_in_box(sp_desktop_document(desktop), desktop->dkey, bounds);
754 } else {
755 Inkscape::Rubberband *r = Inkscape::Rubberband::get(desktop);
756 toWorkOn = sp_document_items_at_points(sp_desktop_document(desktop), desktop->dkey, r->getPoints());
757 }
758 toWorkOn = g_slist_remove( toWorkOn, acid );
759 } else {
760 toWorkOn = g_slist_copy(const_cast<GSList*>(selection->itemList()));
761 wasSelection = true;
762 }
764 if ( g_slist_length(toWorkOn) > 0 ) {
765 if ( eraserMode ) {
766 for (GSList *i = toWorkOn ; i ; i = i->next ) {
767 SPItem *item = SP_ITEM(i->data);
768 if ( eraserMode ) {
769 Geom::OptRect bbox = item->getBounds(Geom::identity());
770 if (bbox && bbox->intersects(*eraserBbox)) {
771 Inkscape::XML::Node* dup = dc->repr->duplicate(xml_doc);
772 dc->repr->parent()->appendChild(dup);
773 Inkscape::GC::release(dup); // parent takes over
775 selection->set(item);
776 selection->add(dup);
777 sp_selected_path_diff_skip_undo(desktop);
778 workDone = true; // TODO set this only if something was cut.
779 if ( !selection->isEmpty() ) {
780 // If the item was not completely erased, track the new remainder.
781 GSList *nowSel = g_slist_copy(const_cast<GSList *>(selection->itemList()));
782 for (GSList const *i2 = nowSel ; i2 ; i2 = i2->next ) {
783 remainingItems.push_back(SP_ITEM(i2->data));
784 }
785 g_slist_free(nowSel);
786 }
787 } else {
788 remainingItems.push_back(item);
789 }
790 }
791 }
792 } else {
793 for (GSList *i = toWorkOn ; i ; i = i->next ) {
794 sp_object_ref( SP_ITEM(i->data), 0 );
795 }
796 for (GSList *i = toWorkOn ; i ; i = i->next ) {
797 SPItem *item = SP_ITEM(i->data);
798 item->deleteObject(true);
799 sp_object_unref(item);
800 workDone = true;
801 }
802 }
804 g_slist_free(toWorkOn);
806 if ( !eraserMode ) {
807 //sp_selection_delete(desktop);
808 remainingItems.clear();
809 }
811 selection->clear();
812 if ( wasSelection ) {
813 if ( !remainingItems.empty() ) {
814 selection->add(remainingItems.begin(), remainingItems.end());
815 }
816 }
817 }
819 // Remove the eraser stroke itself:
820 sp_repr_unparent( dc->repr );
821 dc->repr = 0;
822 }
823 } else {
824 if (dc->repr) {
825 sp_repr_unparent(dc->repr);
826 dc->repr = 0;
827 }
828 }
831 if ( workDone ) {
832 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_ERASER,
833 _("Draw eraser stroke"));
834 } else {
835 sp_document_cancel(sp_desktop_document(desktop));
836 }
837 }
839 static void
840 add_cap(SPCurve *curve,
841 Geom::Point const &pre, Geom::Point const &from,
842 Geom::Point const &to, Geom::Point const &post,
843 double rounding)
844 {
845 Geom::Point vel = rounding * Geom::rot90( to - from ) / sqrt(2.0);
846 double mag = Geom::L2(vel);
848 Geom::Point v_in = from - pre;
849 double mag_in = Geom::L2(v_in);
850 if ( mag_in > ERASER_EPSILON ) {
851 v_in = mag * v_in / mag_in;
852 } else {
853 v_in = Geom::Point(0, 0);
854 }
856 Geom::Point v_out = to - post;
857 double mag_out = Geom::L2(v_out);
858 if ( mag_out > ERASER_EPSILON ) {
859 v_out = mag * v_out / mag_out;
860 } else {
861 v_out = Geom::Point(0, 0);
862 }
864 if ( Geom::L2(v_in) > ERASER_EPSILON || Geom::L2(v_out) > ERASER_EPSILON ) {
865 curve->curveto(from + v_in, to + v_out, to);
866 }
867 }
869 static void
870 accumulate_eraser(SPEraserContext *dc)
871 {
872 if ( !dc->cal1->is_empty() && !dc->cal2->is_empty() ) {
873 dc->accumulated->reset(); /* Is this required ?? */
874 SPCurve *rev_cal2 = dc->cal2->create_reverse();
876 g_assert(dc->cal1->get_segment_count() > 0);
877 g_assert(rev_cal2->get_segment_count() > 0);
878 g_assert( ! dc->cal1->first_path()->closed() );
879 g_assert( ! rev_cal2->first_path()->closed() );
881 Geom::CubicBezier const * dc_cal1_firstseg = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->first_segment() );
882 Geom::CubicBezier const * rev_cal2_firstseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->first_segment() );
883 Geom::CubicBezier const * dc_cal1_lastseg = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->last_segment() );
884 Geom::CubicBezier const * rev_cal2_lastseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->last_segment() );
885 g_assert( dc_cal1_firstseg );
886 g_assert( rev_cal2_firstseg );
887 g_assert( dc_cal1_lastseg );
888 g_assert( rev_cal2_lastseg );
890 dc->accumulated->append(dc->cal1, FALSE);
892 add_cap(dc->accumulated, (*dc_cal1_lastseg)[2], (*dc_cal1_lastseg)[3], (*rev_cal2_firstseg)[0], (*rev_cal2_firstseg)[1], dc->cap_rounding);
894 dc->accumulated->append(rev_cal2, TRUE);
896 add_cap(dc->accumulated, (*rev_cal2_lastseg)[2], (*rev_cal2_lastseg)[3], (*dc_cal1_firstseg)[0], (*dc_cal1_firstseg)[1], dc->cap_rounding);
898 dc->accumulated->closepath();
900 rev_cal2->unref();
902 dc->cal1->reset();
903 dc->cal2->reset();
904 }
905 }
907 static double square(double const x)
908 {
909 return x * x;
910 }
912 static void
913 fit_and_split(SPEraserContext *dc, gboolean release)
914 {
915 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
917 double const tolerance_sq = square( desktop->w2d().descrim() * TOLERANCE_ERASER );
919 #ifdef ERASER_VERBOSE
920 g_print("[F&S:R=%c]", release?'T':'F');
921 #endif
923 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
924 return; // just clicked
926 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
927 #define BEZIER_SIZE 4
928 #define BEZIER_MAX_BEZIERS 8
929 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
931 #ifdef ERASER_VERBOSE
932 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
933 dc->npoints, release ? "TRUE" : "FALSE");
934 #endif
936 /* Current eraser */
937 if ( dc->cal1->is_empty() || dc->cal2->is_empty() ) {
938 /* dc->npoints > 0 */
939 /* g_print("erasers(1|2) reset\n"); */
940 dc->cal1->reset();
941 dc->cal2->reset();
943 dc->cal1->moveto(dc->point1[0]);
944 dc->cal2->moveto(dc->point2[0]);
945 }
947 Geom::Point b1[BEZIER_MAX_LENGTH];
948 gint const nb1 = Geom::bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
949 tolerance_sq, BEZIER_MAX_BEZIERS);
950 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
952 Geom::Point b2[BEZIER_MAX_LENGTH];
953 gint const nb2 = Geom::bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
954 tolerance_sq, BEZIER_MAX_BEZIERS);
955 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
957 if ( nb1 != -1 && nb2 != -1 ) {
958 /* Fit and draw and reset state */
959 #ifdef ERASER_VERBOSE
960 g_print("nb1:%d nb2:%d\n", nb1, nb2);
961 #endif
962 /* CanvasShape */
963 if (! release) {
964 dc->currentcurve->reset();
965 dc->currentcurve->moveto(b1[0]);
966 for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
967 dc->currentcurve->curveto(bp1[1],
968 bp1[2], bp1[3]);
969 }
970 dc->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]);
971 for (Geom::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
972 dc->currentcurve->curveto(bp2[2], bp2[1], bp2[0]);
973 }
974 // FIXME: dc->segments is always NULL at this point??
975 if (!dc->segments) { // first segment
976 add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
977 }
978 dc->currentcurve->closepath();
979 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
980 }
982 /* Current eraser */
983 for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
984 dc->cal1->curveto(bp1[1], bp1[2], bp1[3]);
985 }
986 for (Geom::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
987 dc->cal2->curveto(bp2[1], bp2[2], bp2[3]);
988 }
989 } else {
990 /* fixme: ??? */
991 #ifdef ERASER_VERBOSE
992 g_print("[fit_and_split] failed to fit-cubic.\n");
993 #endif
994 draw_temporary_box(dc);
996 for (gint i = 1; i < dc->npoints; i++) {
997 dc->cal1->lineto(dc->point1[i]);
998 }
999 for (gint i = 1; i < dc->npoints; i++) {
1000 dc->cal2->lineto(dc->point2[i]);
1001 }
1002 }
1004 /* Fit and draw and copy last point */
1005 #ifdef ERASER_VERBOSE
1006 g_print("[%d]Yup\n", dc->npoints);
1007 #endif
1008 if (!release) {
1009 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1010 gint eraserMode = prefs->getBool("/tools/eraser/mode") ? 1 : 0;
1011 g_assert(!dc->currentcurve->is_empty());
1013 SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(desktop),
1014 SP_TYPE_CANVAS_BPATH,
1015 NULL);
1016 SPCurve *curve = dc->currentcurve->copy();
1017 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1018 curve->unref();
1020 guint32 fillColor = sp_desktop_get_color_tool (desktop, "/tools/eraser", true);
1021 //guint32 strokeColor = sp_desktop_get_color_tool (desktop, "/tools/eraser", false);
1022 double opacity = sp_desktop_get_master_opacity_tool (desktop, "/tools/eraser");
1023 double fillOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/eraser", true);
1024 //double strokeOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/eraser", false);
1025 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1026 //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1027 //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);
1028 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1029 /* fixme: Cannot we cascade it to root more clearly? */
1030 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), desktop);
1032 dc->segments = g_slist_prepend(dc->segments, cbp);
1034 if ( !eraserMode ) {
1035 sp_canvas_item_hide(cbp);
1036 sp_canvas_item_hide(dc->currentshape);
1037 }
1038 }
1040 dc->point1[0] = dc->point1[dc->npoints - 1];
1041 dc->point2[0] = dc->point2[dc->npoints - 1];
1042 dc->npoints = 1;
1043 } else {
1044 draw_temporary_box(dc);
1045 }
1046 }
1048 static void
1049 draw_temporary_box(SPEraserContext *dc)
1050 {
1051 dc->currentcurve->reset();
1053 dc->currentcurve->moveto(dc->point1[dc->npoints-1]);
1054 for (gint i = dc->npoints-2; i >= 0; i--) {
1055 dc->currentcurve->lineto(dc->point1[i]);
1056 }
1057 for (gint i = 0; i < dc->npoints; i++) {
1058 dc->currentcurve->lineto(dc->point2[i]);
1059 }
1060 if (dc->npoints >= 2) {
1061 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);
1062 }
1064 dc->currentcurve->closepath();
1065 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1066 }
1068 /*
1069 Local Variables:
1070 mode:c++
1071 c-file-style:"stroustrup"
1072 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1073 indent-tabs-mode:nil
1074 fill-column:99
1075 End:
1076 */
1077 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :