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 "xml/repr.h"
52 #include "context-fns.h"
53 #include "sp-item.h"
54 #include "inkscape.h"
55 #include "color.h"
56 #include "rubberband.h"
57 #include "splivarot.h"
58 #include "sp-item-group.h"
59 #include "sp-shape.h"
60 #include "sp-path.h"
61 #include "sp-text.h"
62 #include "display/canvas-bpath.h"
63 #include "display/canvas-arena.h"
64 #include "livarot/Shape.h"
65 #include <2geom/isnan.h>
66 #include <2geom/pathvector.h>
68 #include "eraser-context.h"
70 #define ERC_RED_RGBA 0xff0000ff
72 #define TOLERANCE_ERASER 0.1
74 #define ERASER_EPSILON 0.5e-6
75 #define ERASER_EPSILON_START 0.5e-2
76 #define ERASER_VEL_START 1e-5
78 #define DRAG_MIN 0.0
79 #define DRAG_DEFAULT 1.0
80 #define DRAG_MAX 1.0
83 static void sp_eraser_context_class_init(SPEraserContextClass *klass);
84 static void sp_eraser_context_init(SPEraserContext *erc);
85 static void sp_eraser_context_dispose(GObject *object);
87 static void sp_eraser_context_setup(SPEventContext *ec);
88 static void sp_eraser_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
89 static gint sp_eraser_context_root_handler(SPEventContext *ec, GdkEvent *event);
91 static void clear_current(SPEraserContext *dc);
92 static void set_to_accumulated(SPEraserContext *dc);
93 static void add_cap(SPCurve *curve, NR::Point const &pre, NR::Point const &from, NR::Point const &to, NR::Point const &post, double rounding);
94 static void accumulate_eraser(SPEraserContext *dc);
96 static void fit_and_split(SPEraserContext *erc, gboolean release);
98 static void sp_eraser_reset(SPEraserContext *erc, NR::Point p);
99 static NR::Point sp_eraser_get_npoint(SPEraserContext const *erc, NR::Point v);
100 static NR::Point sp_eraser_get_vpoint(SPEraserContext const *erc, NR::Point n);
101 static void draw_temporary_box(SPEraserContext *dc);
104 static SPEventContextClass *eraser_parent_class = 0;
106 GType sp_eraser_context_get_type(void)
107 {
108 static GType type = 0;
109 if (!type) {
110 GTypeInfo info = {
111 sizeof(SPEraserContextClass),
112 0, // base_init
113 0, // base_finalize
114 (GClassInitFunc)sp_eraser_context_class_init,
115 0, // class_finalize
116 0, // class_data
117 sizeof(SPEraserContext),
118 0, // n_preallocs
119 (GInstanceInitFunc)sp_eraser_context_init,
120 0 // value_table
121 };
122 type = g_type_register_static(SP_TYPE_COMMON_CONTEXT, "SPEraserContext", &info, static_cast<GTypeFlags>(0));
123 }
124 return type;
125 }
127 static void
128 sp_eraser_context_class_init(SPEraserContextClass *klass)
129 {
130 GObjectClass *object_class = (GObjectClass *) klass;
131 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
133 eraser_parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
135 object_class->dispose = sp_eraser_context_dispose;
137 event_context_class->setup = sp_eraser_context_setup;
138 event_context_class->set = sp_eraser_context_set;
139 event_context_class->root_handler = sp_eraser_context_root_handler;
140 }
142 static void
143 sp_eraser_context_init(SPEraserContext *erc)
144 {
145 erc->cursor_shape = cursor_eraser_xpm;
146 erc->hot_x = 4;
147 erc->hot_y = 4;
148 }
150 static void
151 sp_eraser_context_dispose(GObject *object)
152 {
153 //SPEraserContext *erc = SP_ERASER_CONTEXT(object);
155 G_OBJECT_CLASS(eraser_parent_class)->dispose(object);
156 }
158 static void
159 sp_eraser_context_setup(SPEventContext *ec)
160 {
161 SPEraserContext *erc = SP_ERASER_CONTEXT(ec);
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(ec->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), ec->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((ec->desktop)->messageStack());
207 if (prefs_get_int_attribute("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, gchar const *key, gchar const *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, key, 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 NR::Point
232 sp_eraser_get_npoint(SPEraserContext const *dc, NR::Point v)
233 {
234 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
235 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
236 return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max, ( v[NR::Y] - drect.min()[NR::Y] ) / max);
237 }
239 /* Get view point */
240 static NR::Point
241 sp_eraser_get_vpoint(SPEraserContext const *dc, NR::Point n)
242 {
243 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
244 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
245 return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
246 }
248 static void
249 sp_eraser_reset(SPEraserContext *dc, NR::Point p)
250 {
251 dc->last = dc->cur = sp_eraser_get_npoint(dc, p);
252 dc->vel = NR::Point(0,0);
253 dc->vel_max = 0;
254 dc->acc = NR::Point(0,0);
255 dc->ang = NR::Point(0,0);
256 dc->del = NR::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, NR::Point p)
281 {
282 NR::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 NR::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 ( NR::L2(force) < ERASER_EPSILON || (dc->vel_max < ERASER_VEL_START && NR::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 (NR::L2(dc->vel) > dc->vel_max)
308 dc->vel_max = NR::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 NR::Point ang1 = NR::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 NR::Point ang1 = NR::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 = NR::L2(dc->vel);
333 if ( mag_vel < ERASER_EPSILON ) {
334 return FALSE;
335 }
336 NR::Point ang2 = NR::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 = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
359 if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
360 return FALSE;
361 }
363 // convert to point
364 dc->ang = NR::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", NR::L2(force), NR::L2(dc->acc), dc->vel_max, NR::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 NR::Point brush = sp_eraser_get_vpoint(dc, dc->cur);
392 NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush);
394 double trace_thick = 1;
396 double width = (pressure_thick * trace_thick - vel_thin * NR::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*NR::L2(dc->vel));
417 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::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 NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
430 NR::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 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
482 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
483 return TRUE;
484 }
486 NR::Point const button_w(event->button.x,
487 event->button.y);
488 NR::Point const button_dt(desktop->w2d(button_w));
489 sp_eraser_reset(dc, button_dt);
490 sp_eraser_extinput(dc, event);
491 sp_eraser_apply(dc, button_dt);
492 dc->accumulated->reset();
493 if (dc->repr) {
494 dc->repr = NULL;
495 }
497 Inkscape::Rubberband::get()->start(desktop, button_dt);
498 Inkscape::Rubberband::get()->setMode(RUBBERBAND_MODE_TOUCHPATH);
500 /* initialize first point */
501 dc->npoints = 0;
503 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
504 ( GDK_KEY_PRESS_MASK |
505 GDK_BUTTON_RELEASE_MASK |
506 GDK_POINTER_MOTION_MASK |
507 GDK_BUTTON_PRESS_MASK ),
508 NULL,
509 event->button.time);
511 ret = TRUE;
513 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
514 dc->is_drawing = true;
515 }
516 break;
517 case GDK_MOTION_NOTIFY:
518 {
519 NR::Point const motion_w(event->motion.x,
520 event->motion.y);
521 NR::Point motion_dt(desktop->w2d(motion_w));
522 sp_eraser_extinput(dc, event);
524 dc->_message_context->clear();
526 if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
527 dc->dragging = TRUE;
529 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> an eraser stroke"));
531 if (!sp_eraser_apply(dc, motion_dt)) {
532 ret = TRUE;
533 break;
534 }
536 if ( dc->cur != dc->last ) {
537 sp_eraser_brush(dc);
538 g_assert( dc->npoints > 0 );
539 fit_and_split(dc, FALSE);
540 }
541 ret = TRUE;
542 }
543 Inkscape::Rubberband::get()->move(motion_dt);
544 }
545 break;
548 case GDK_BUTTON_RELEASE:
549 {
550 NR::Point const motion_w(event->button.x, event->button.y);
551 NR::Point const motion_dt(desktop->w2d(motion_w));
553 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
554 sp_canvas_end_forced_full_redraws(desktop->canvas);
555 dc->is_drawing = false;
557 if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
558 dc->dragging = FALSE;
560 NR::Maybe<NR::Rect> const b = Inkscape::Rubberband::get()->getRectangle();
562 sp_eraser_apply(dc, motion_dt);
564 /* Remove all temporary line segments */
565 while (dc->segments) {
566 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
567 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
568 }
570 /* Create object */
571 fit_and_split(dc, TRUE);
572 accumulate_eraser(dc);
573 set_to_accumulated(dc); // performs document_done
575 /* reset accumulated curve */
576 dc->accumulated->reset();
578 clear_current(dc);
579 if (dc->repr) {
580 dc->repr = NULL;
581 }
583 Inkscape::Rubberband::get()->stop();
584 dc->_message_context->clear();
585 ret = TRUE;
586 }
587 break;
588 }
590 case GDK_KEY_PRESS:
591 switch (get_group0_keyval (&event->key)) {
592 case GDK_Up:
593 case GDK_KP_Up:
594 if (!MOD__CTRL_ONLY) {
595 dc->angle += 5.0;
596 if (dc->angle > 90.0)
597 dc->angle = 90.0;
598 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
599 ret = TRUE;
600 }
601 break;
602 case GDK_Down:
603 case GDK_KP_Down:
604 if (!MOD__CTRL_ONLY) {
605 dc->angle -= 5.0;
606 if (dc->angle < -90.0)
607 dc->angle = -90.0;
608 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
609 ret = TRUE;
610 }
611 break;
612 case GDK_Right:
613 case GDK_KP_Right:
614 if (!MOD__CTRL_ONLY) {
615 dc->width += 0.01;
616 if (dc->width > 1.0)
617 dc->width = 1.0;
618 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100); // the same spinbutton is for alt+x
619 ret = TRUE;
620 }
621 break;
622 case GDK_Left:
623 case GDK_KP_Left:
624 if (!MOD__CTRL_ONLY) {
625 dc->width -= 0.01;
626 if (dc->width < 0.01)
627 dc->width = 0.01;
628 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
629 ret = TRUE;
630 }
631 break;
632 case GDK_Home:
633 case GDK_KP_Home:
634 dc->width = 0.01;
635 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
636 ret = TRUE;
637 break;
638 case GDK_End:
639 case GDK_KP_End:
640 dc->width = 1.0;
641 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
642 ret = TRUE;
643 break;
644 case GDK_x:
645 case GDK_X:
646 if (MOD__ALT_ONLY) {
647 desktop->setToolboxFocusTo ("altx-eraser");
648 ret = TRUE;
649 }
650 break;
651 case GDK_Escape:
652 Inkscape::Rubberband::get()->stop();
653 if (dc->is_drawing) {
654 // if drawing, cancel, otherwise pass it up for deselecting
655 eraser_cancel (dc);
656 ret = TRUE;
657 }
658 break;
659 case GDK_z:
660 case GDK_Z:
661 if (MOD__CTRL_ONLY && dc->is_drawing) {
662 // if drawing, cancel, otherwise pass it up for undo
663 eraser_cancel (dc);
664 ret = TRUE;
665 }
666 break;
667 default:
668 break;
669 }
670 break;
672 case GDK_KEY_RELEASE:
673 switch (get_group0_keyval(&event->key)) {
674 case GDK_Control_L:
675 case GDK_Control_R:
676 dc->_message_context->clear();
677 break;
678 default:
679 break;
680 }
682 default:
683 break;
684 }
686 if (!ret) {
687 if (((SPEventContextClass *) eraser_parent_class)->root_handler) {
688 ret = ((SPEventContextClass *) eraser_parent_class)->root_handler(event_context, event);
689 }
690 }
692 return ret;
693 }
696 static void
697 clear_current(SPEraserContext *dc)
698 {
699 // reset bpath
700 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
702 // reset curve
703 dc->currentcurve->reset();
704 dc->cal1->reset();
705 dc->cal2->reset();
707 // reset points
708 dc->npoints = 0;
709 }
711 static void
712 set_to_accumulated(SPEraserContext *dc)
713 {
714 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
715 bool workDone = false;
717 if (!dc->accumulated->is_empty()) {
718 if (!dc->repr) {
719 /* Create object */
720 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
721 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
723 /* Set style */
724 sp_desktop_apply_style_tool (desktop, repr, "tools.eraser", false);
726 dc->repr = repr;
728 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
729 Inkscape::GC::release(dc->repr);
730 item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
731 item->updateRepr();
732 }
733 Geom::PathVector pathv = dc->accumulated->get_pathvector() * to_2geom(sp_desktop_dt2root_affine(desktop));
734 gchar *str = sp_svg_write_path(pathv);
735 g_assert( str != NULL );
736 dc->repr->setAttribute("d", str);
737 g_free(str);
739 if ( dc->repr ) {
740 bool wasSelection = false;
741 Inkscape::Selection *selection = sp_desktop_selection(desktop);
742 gint eraserMode = (prefs_get_int_attribute("tools.eraser", "mode", 0) != 0) ? 1 : 0;
743 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
745 SPItem* acid = SP_ITEM(desktop->doc()->getObjectByRepr(dc->repr));
746 NR::Maybe<NR::Rect> eraserBbox = acid->getBounds(NR::identity());
747 NR::Rect bounds = (*eraserBbox) * desktop->doc2dt();
748 std::vector<SPItem*> remainingItems;
749 GSList* toWorkOn = 0;
750 if (selection->isEmpty()) {
751 if ( eraserMode ) {
752 toWorkOn = sp_document_partial_items_in_box(sp_desktop_document(desktop), desktop->dkey, bounds);
753 } else {
754 Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
755 toWorkOn = sp_document_items_at_points(sp_desktop_document(desktop), desktop->dkey, r->getPoints());
756 }
757 toWorkOn = g_slist_remove( toWorkOn, acid );
758 } else {
759 toWorkOn = g_slist_copy(const_cast<GSList*>(selection->itemList()));
760 wasSelection = true;
761 }
763 if ( g_slist_length(toWorkOn) > 0 ) {
764 if ( eraserMode ) {
765 for (GSList *i = toWorkOn ; i ; i = i->next ) {
766 SPItem *item = SP_ITEM(i->data);
767 if ( eraserMode ) {
768 NR::Maybe<NR::Rect> bbox = item->getBounds(NR::identity());
769 if (bbox && bbox->intersects(*eraserBbox)) {
770 Inkscape::XML::Node* dup = dc->repr->duplicate(xml_doc);
771 dc->repr->parent()->appendChild(dup);
772 Inkscape::GC::release(dup); // parent takes over
774 selection->set(item);
775 selection->add(dup);
776 sp_selected_path_diff_skip_undo();
777 workDone = true; // TODO set this only if something was cut.
778 if ( !selection->isEmpty() ) {
779 // If the item was not completely erased, track the new remainder.
780 GSList *nowSel = g_slist_copy(const_cast<GSList *>(selection->itemList()));
781 for (GSList const *i2 = nowSel ; i2 ; i2 = i2->next ) {
782 remainingItems.push_back(SP_ITEM(i2->data));
783 }
784 g_slist_free(nowSel);
785 }
786 } else {
787 remainingItems.push_back(item);
788 }
789 }
790 }
791 } else {
792 for (GSList *i = toWorkOn ; i ; i = i->next ) {
793 sp_object_ref( SP_ITEM(i->data), 0 );
794 }
795 for (GSList *i = toWorkOn ; i ; i = i->next ) {
796 SPItem *item = SP_ITEM(i->data);
797 item->deleteObject(true);
798 sp_object_unref(item);
799 workDone = true;
800 }
801 }
803 g_slist_free(toWorkOn);
805 if ( !eraserMode ) {
806 //sp_selection_delete();
807 remainingItems.clear();
808 }
810 selection->clear();
811 if ( wasSelection ) {
812 if ( !remainingItems.empty() ) {
813 selection->add(remainingItems.begin(), remainingItems.end());
814 }
815 }
816 }
818 // Remove the eraser stroke itself:
819 sp_repr_unparent( dc->repr );
820 dc->repr = 0;
821 }
822 } else {
823 if (dc->repr) {
824 sp_repr_unparent(dc->repr);
825 dc->repr = 0;
826 }
827 }
830 if ( workDone ) {
831 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_ERASER,
832 _("Draw eraser stroke"));
833 } else {
834 sp_document_cancel(sp_desktop_document(desktop));
835 }
836 }
838 static void
839 add_cap(SPCurve *curve,
840 NR::Point const &pre, NR::Point const &from,
841 NR::Point const &to, NR::Point const &post,
842 double rounding)
843 {
844 NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
845 double mag = NR::L2(vel);
847 NR::Point v_in = from - pre;
848 double mag_in = NR::L2(v_in);
849 if ( mag_in > ERASER_EPSILON ) {
850 v_in = mag * v_in / mag_in;
851 } else {
852 v_in = NR::Point(0, 0);
853 }
855 NR::Point v_out = to - post;
856 double mag_out = NR::L2(v_out);
857 if ( mag_out > ERASER_EPSILON ) {
858 v_out = mag * v_out / mag_out;
859 } else {
860 v_out = NR::Point(0, 0);
861 }
863 if ( NR::L2(v_in) > ERASER_EPSILON || NR::L2(v_out) > ERASER_EPSILON ) {
864 curve->curveto(from + v_in, to + v_out, to);
865 }
866 }
868 static void
869 accumulate_eraser(SPEraserContext *dc)
870 {
871 if ( !dc->cal1->is_empty() && !dc->cal2->is_empty() ) {
872 dc->accumulated->reset(); /* Is this required ?? */
873 SPCurve *rev_cal2 = dc->cal2->create_reverse();
875 g_assert(dc->cal1->get_segment_count() > 0);
876 g_assert(rev_cal2->get_segment_count() > 0);
877 g_assert( ! dc->cal1->first_path()->closed() );
878 g_assert( ! rev_cal2->first_path()->closed() );
880 Geom::CubicBezier const * dc_cal1_firstseg = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->first_segment() );
881 Geom::CubicBezier const * rev_cal2_firstseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->first_segment() );
882 Geom::CubicBezier const * dc_cal1_lastseg = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->last_segment() );
883 Geom::CubicBezier const * rev_cal2_lastseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->last_segment() );
884 g_assert( dc_cal1_firstseg );
885 g_assert( rev_cal2_firstseg );
886 g_assert( dc_cal1_lastseg );
887 g_assert( rev_cal2_lastseg );
889 dc->accumulated->append(dc->cal1, FALSE);
891 add_cap(dc->accumulated, (*dc_cal1_lastseg)[2], (*dc_cal1_lastseg)[3], (*rev_cal2_firstseg)[0], (*rev_cal2_firstseg)[1], dc->cap_rounding);
893 dc->accumulated->append(rev_cal2, TRUE);
895 add_cap(dc->accumulated, (*rev_cal2_lastseg)[2], (*rev_cal2_lastseg)[3], (*dc_cal1_firstseg)[0], (*dc_cal1_firstseg)[1], dc->cap_rounding);
897 dc->accumulated->closepath();
899 rev_cal2->unref();
901 dc->cal1->reset();
902 dc->cal2->reset();
903 }
904 }
906 static double square(double const x)
907 {
908 return x * x;
909 }
911 static void
912 fit_and_split(SPEraserContext *dc, gboolean release)
913 {
914 double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_ERASER );
916 #ifdef ERASER_VERBOSE
917 g_print("[F&S:R=%c]", release?'T':'F');
918 #endif
920 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
921 return; // just clicked
923 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
924 #define BEZIER_SIZE 4
925 #define BEZIER_MAX_BEZIERS 8
926 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
928 #ifdef ERASER_VERBOSE
929 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
930 dc->npoints, release ? "TRUE" : "FALSE");
931 #endif
933 /* Current eraser */
934 if ( dc->cal1->is_empty() || dc->cal2->is_empty() ) {
935 /* dc->npoints > 0 */
936 /* g_print("erasers(1|2) reset\n"); */
937 dc->cal1->reset();
938 dc->cal2->reset();
940 dc->cal1->moveto(dc->point1[0]);
941 dc->cal2->moveto(dc->point2[0]);
942 }
944 NR::Point b1[BEZIER_MAX_LENGTH];
945 gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
946 tolerance_sq, BEZIER_MAX_BEZIERS);
947 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
949 NR::Point b2[BEZIER_MAX_LENGTH];
950 gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
951 tolerance_sq, BEZIER_MAX_BEZIERS);
952 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
954 if ( nb1 != -1 && nb2 != -1 ) {
955 /* Fit and draw and reset state */
956 #ifdef ERASER_VERBOSE
957 g_print("nb1:%d nb2:%d\n", nb1, nb2);
958 #endif
959 /* CanvasShape */
960 if (! release) {
961 dc->currentcurve->reset();
962 dc->currentcurve->moveto(b1[0]);
963 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
964 dc->currentcurve->curveto(bp1[1],
965 bp1[2], bp1[3]);
966 }
967 dc->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]);
968 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
969 dc->currentcurve->curveto(bp2[2], bp2[1], bp2[0]);
970 }
971 // FIXME: dc->segments is always NULL at this point??
972 if (!dc->segments) { // first segment
973 add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
974 }
975 dc->currentcurve->closepath();
976 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
977 }
979 /* Current eraser */
980 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
981 dc->cal1->curveto(bp1[1], bp1[2], bp1[3]);
982 }
983 for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
984 dc->cal2->curveto(bp2[1], bp2[2], bp2[3]);
985 }
986 } else {
987 /* fixme: ??? */
988 #ifdef ERASER_VERBOSE
989 g_print("[fit_and_split] failed to fit-cubic.\n");
990 #endif
991 draw_temporary_box(dc);
993 for (gint i = 1; i < dc->npoints; i++) {
994 dc->cal1->lineto(dc->point1[i]);
995 }
996 for (gint i = 1; i < dc->npoints; i++) {
997 dc->cal2->lineto(dc->point2[i]);
998 }
999 }
1001 /* Fit and draw and copy last point */
1002 #ifdef ERASER_VERBOSE
1003 g_print("[%d]Yup\n", dc->npoints);
1004 #endif
1005 if (!release) {
1006 gint eraserMode = (prefs_get_int_attribute("tools.eraser", "mode", 0) != 0) ? 1 : 0;
1007 g_assert(!dc->currentcurve->is_empty());
1009 SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1010 SP_TYPE_CANVAS_BPATH,
1011 NULL);
1012 SPCurve *curve = dc->currentcurve->copy();
1013 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1014 curve->unref();
1016 guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.eraser", true);
1017 //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.eraser", false);
1018 double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser");
1019 double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser", true);
1020 //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser", false);
1021 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1022 //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1023 //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);
1024 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1025 /* fixme: Cannot we cascade it to root more clearly? */
1026 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1028 dc->segments = g_slist_prepend(dc->segments, cbp);
1030 if ( !eraserMode ) {
1031 sp_canvas_item_hide(cbp);
1032 sp_canvas_item_hide(dc->currentshape);
1033 }
1034 }
1036 dc->point1[0] = dc->point1[dc->npoints - 1];
1037 dc->point2[0] = dc->point2[dc->npoints - 1];
1038 dc->npoints = 1;
1039 } else {
1040 draw_temporary_box(dc);
1041 }
1042 }
1044 static void
1045 draw_temporary_box(SPEraserContext *dc)
1046 {
1047 dc->currentcurve->reset();
1049 dc->currentcurve->moveto(dc->point1[dc->npoints-1]);
1050 for (gint i = dc->npoints-2; i >= 0; i--) {
1051 dc->currentcurve->lineto(dc->point1[i]);
1052 }
1053 for (gint i = 0; i < dc->npoints; i++) {
1054 dc->currentcurve->lineto(dc->point2[i]);
1055 }
1056 if (dc->npoints >= 2) {
1057 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);
1058 }
1060 dc->currentcurve->closepath();
1061 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1062 }
1064 /*
1065 Local Variables:
1066 mode:c++
1067 c-file-style:"stroustrup"
1068 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1069 indent-tabs-mode:nil
1070 fill-column:99
1071 End:
1072 */
1073 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :