1 /*
2 * Eraser drawing mode
3 *
4 * Authors:
5 * Mitsuru Oka <oka326@parkcity.ne.jp>
6 * Lauris Kaplinski <lauris@kaplinski.com>
7 * bulia byak <buliabyak@users.sf.net>
8 * MenTaLguY <mental@rydia.net>
9 * Jon A. Cruz <jon@joncruz.org>
10 *
11 * The original dynadraw code:
12 * Paul Haeberli <paul@sgi.com>
13 *
14 * Copyright (C) 1998 The Free Software Foundation
15 * Copyright (C) 1999-2005 authors
16 * Copyright (C) 2001-2002 Ximian, Inc.
17 * Copyright (C) 2005-2007 bulia byak
18 * Copyright (C) 2006 MenTaLguY
19 * Copyright (C) 2008 Jon A. Cruz
20 *
21 * Released under GNU GPL, read the file 'COPYING' for more information
22 */
24 #define noERASER_VERBOSE
26 #include "config.h"
28 #include <gtk/gtk.h>
29 #include <gdk/gdkkeysyms.h>
30 #include <glibmm/i18n.h>
31 #include <string>
32 #include <cstring>
33 #include <numeric>
35 #include "svg/svg.h"
36 #include "display/canvas-bpath.h"
37 #include "display/bezier-utils.h"
39 #include <glib/gmem.h>
40 #include "macros.h"
41 #include "document.h"
42 #include "selection.h"
43 #include "desktop.h"
44 #include "desktop-events.h"
45 #include "desktop-handles.h"
46 #include "desktop-affine.h"
47 #include "desktop-style.h"
48 #include "message-context.h"
49 #include "prefs-utils.h"
50 #include "pixmaps/cursor-eraser.xpm"
51 #include "libnr/n-art-bpath.h"
52 #include "libnr/nr-path.h"
53 #include "libnr/nr-matrix-ops.h"
54 #include "libnr/nr-scale-translate-ops.h"
55 #include "xml/repr.h"
56 #include "context-fns.h"
57 #include "sp-item.h"
58 #include "inkscape.h"
59 #include "color.h"
60 #include "rubberband.h"
61 #include "splivarot.h"
62 #include "sp-item-group.h"
63 #include "sp-shape.h"
64 #include "sp-path.h"
65 #include "sp-text.h"
66 #include "display/canvas-bpath.h"
67 #include "display/canvas-arena.h"
68 #include "livarot/Shape.h"
69 #include "isnan.h"
71 #include "eraser-context.h"
73 #define ERC_RED_RGBA 0xff0000ff
75 #define TOLERANCE_ERASER 0.1
77 #define ERASER_EPSILON 0.5e-6
78 #define ERASER_EPSILON_START 0.5e-2
79 #define ERASER_VEL_START 1e-5
81 #define DRAG_MIN 0.0
82 #define DRAG_DEFAULT 1.0
83 #define DRAG_MAX 1.0
86 static void sp_eraser_context_class_init(SPEraserContextClass *klass);
87 static void sp_eraser_context_init(SPEraserContext *erc);
88 static void sp_eraser_context_dispose(GObject *object);
90 static void sp_eraser_context_setup(SPEventContext *ec);
91 static void sp_eraser_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
92 static gint sp_eraser_context_root_handler(SPEventContext *ec, GdkEvent *event);
94 static void clear_current(SPEraserContext *dc);
95 static void set_to_accumulated(SPEraserContext *dc);
96 static void add_cap(SPCurve *curve, NR::Point const &pre, NR::Point const &from, NR::Point const &to, NR::Point const &post, double rounding);
97 static void accumulate_eraser(SPEraserContext *dc);
99 static void fit_and_split(SPEraserContext *erc, gboolean release);
101 static void sp_eraser_reset(SPEraserContext *erc, NR::Point p);
102 static NR::Point sp_eraser_get_npoint(SPEraserContext const *erc, NR::Point v);
103 static NR::Point sp_eraser_get_vpoint(SPEraserContext const *erc, NR::Point n);
104 static void draw_temporary_box(SPEraserContext *dc);
107 static SPEventContextClass *eraser_parent_class = 0;
109 GType sp_eraser_context_get_type(void)
110 {
111 static GType type = 0;
112 if (!type) {
113 GTypeInfo info = {
114 sizeof(SPEraserContextClass),
115 0, // base_init
116 0, // base_finalize
117 (GClassInitFunc)sp_eraser_context_class_init,
118 0, // class_finalize
119 0, // class_data
120 sizeof(SPEraserContext),
121 0, // n_preallocs
122 (GInstanceInitFunc)sp_eraser_context_init,
123 0 // value_table
124 };
125 type = g_type_register_static(SP_TYPE_COMMON_CONTEXT, "SPEraserContext", &info, static_cast<GTypeFlags>(0));
126 }
127 return type;
128 }
130 static void
131 sp_eraser_context_class_init(SPEraserContextClass *klass)
132 {
133 GObjectClass *object_class = (GObjectClass *) klass;
134 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
136 eraser_parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
138 object_class->dispose = sp_eraser_context_dispose;
140 event_context_class->setup = sp_eraser_context_setup;
141 event_context_class->set = sp_eraser_context_set;
142 event_context_class->root_handler = sp_eraser_context_root_handler;
143 }
145 static void
146 sp_eraser_context_init(SPEraserContext *erc)
147 {
148 erc->cursor_shape = cursor_eraser_xpm;
149 erc->hot_x = 4;
150 erc->hot_y = 4;
151 }
153 static void
154 sp_eraser_context_dispose(GObject *object)
155 {
156 //SPEraserContext *erc = SP_ERASER_CONTEXT(object);
158 G_OBJECT_CLASS(eraser_parent_class)->dispose(object);
159 }
161 static void
162 sp_eraser_context_setup(SPEventContext *ec)
163 {
164 SPEraserContext *erc = SP_ERASER_CONTEXT(ec);
166 if (((SPEventContextClass *) eraser_parent_class)->setup)
167 ((SPEventContextClass *) eraser_parent_class)->setup(ec);
169 erc->accumulated = new SPCurve(32);
170 erc->currentcurve = new SPCurve(4);
172 erc->cal1 = new SPCurve(32);
173 erc->cal2 = new SPCurve(32);
175 erc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
176 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(erc->currentshape), ERC_RED_RGBA, SP_WIND_RULE_EVENODD);
177 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(erc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
178 /* fixme: Cannot we cascade it to root more clearly? */
179 g_signal_connect(G_OBJECT(erc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
181 /*
182 static ProfileFloatElement f_profile[PROFILE_FLOAT_SIZE] = {
183 {"mass",0.02, 0.0, 1.0},
184 {"wiggle",0.0, 0.0, 1.0},
185 {"angle",30.0, -90.0, 90.0},
186 {"thinning",0.1, -1.0, 1.0},
187 {"tremor",0.0, 0.0, 1.0},
188 {"flatness",0.9, 0.0, 1.0},
189 {"cap_rounding",0.0, 0.0, 5.0}
190 };
191 */
193 sp_event_context_read(ec, "mass");
194 sp_event_context_read(ec, "wiggle");
195 sp_event_context_read(ec, "angle");
196 sp_event_context_read(ec, "width");
197 sp_event_context_read(ec, "thinning");
198 sp_event_context_read(ec, "tremor");
199 sp_event_context_read(ec, "flatness");
200 sp_event_context_read(ec, "tracebackground");
201 sp_event_context_read(ec, "usepressure");
202 sp_event_context_read(ec, "usetilt");
203 sp_event_context_read(ec, "abs_width");
204 sp_event_context_read(ec, "cap_rounding");
206 erc->is_drawing = false;
208 erc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
210 if (prefs_get_int_attribute("tools.eraser", "selcue", 0) != 0) {
211 ec->enableSelectionCue();
212 }
213 // TODO temp force:
214 ec->enableSelectionCue();
216 }
218 static void
219 sp_eraser_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
220 {
221 SPEraserContext *erc = SP_ERASER_CONTEXT(ec);
223 if (!strcmp(key, "mass")) {
224 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
225 erc->mass = CLAMP(dval, -1000.0, 1000.0);
226 } else if (!strcmp(key, "wiggle")) {
227 double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
228 erc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
229 } else if (!strcmp(key, "angle")) {
230 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
231 erc->angle = CLAMP (dval, -90, 90);
232 } else if (!strcmp(key, "width")) {
233 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
234 erc->width = CLAMP(dval, -1000.0, 1000.0);
235 } else if (!strcmp(key, "thinning")) {
236 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
237 erc->vel_thin = CLAMP(dval, -1.0, 1.0);
238 } else if (!strcmp(key, "tremor")) {
239 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
240 erc->tremor = CLAMP(dval, 0.0, 1.0);
241 } else if (!strcmp(key, "flatness")) {
242 double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
243 erc->flatness = CLAMP(dval, 0, 1.0);
244 } else if (!strcmp(key, "usepressure")) {
245 erc->usepressure = (val && strcmp(val, "0"));
246 } else if (!strcmp(key, "usetilt")) {
247 erc->usetilt = (val && strcmp(val, "0"));
248 } else if (!strcmp(key, "abs_width")) {
249 erc->abs_width = (val && strcmp(val, "0"));
250 } else if (!strcmp(key, "cap_rounding")) {
251 erc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
252 }
254 //g_print("ERC: %g %g %g %g\n", erc->mass, erc->drag, erc->angle, erc->width);
255 }
257 static double
258 flerp(double f0, double f1, double p)
259 {
260 return f0 + ( f1 - f0 ) * p;
261 }
263 /* Get normalized point */
264 static NR::Point
265 sp_eraser_get_npoint(SPEraserContext const *dc, NR::Point v)
266 {
267 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
268 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
269 return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max, ( v[NR::Y] - drect.min()[NR::Y] ) / max);
270 }
272 /* Get view point */
273 static NR::Point
274 sp_eraser_get_vpoint(SPEraserContext const *dc, NR::Point n)
275 {
276 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
277 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
278 return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
279 }
281 static void
282 sp_eraser_reset(SPEraserContext *dc, NR::Point p)
283 {
284 dc->last = dc->cur = sp_eraser_get_npoint(dc, p);
285 dc->vel = NR::Point(0,0);
286 dc->vel_max = 0;
287 dc->acc = NR::Point(0,0);
288 dc->ang = NR::Point(0,0);
289 dc->del = NR::Point(0,0);
290 }
292 static void
293 sp_eraser_extinput(SPEraserContext *dc, GdkEvent *event)
294 {
295 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
296 dc->pressure = CLAMP (dc->pressure, ERC_MIN_PRESSURE, ERC_MAX_PRESSURE);
297 else
298 dc->pressure = ERC_DEFAULT_PRESSURE;
300 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
301 dc->xtilt = CLAMP (dc->xtilt, ERC_MIN_TILT, ERC_MAX_TILT);
302 else
303 dc->xtilt = ERC_DEFAULT_TILT;
305 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
306 dc->ytilt = CLAMP (dc->ytilt, ERC_MIN_TILT, ERC_MAX_TILT);
307 else
308 dc->ytilt = ERC_DEFAULT_TILT;
309 }
312 static gboolean
313 sp_eraser_apply(SPEraserContext *dc, NR::Point p)
314 {
315 NR::Point n = sp_eraser_get_npoint(dc, p);
317 /* Calculate mass and drag */
318 double const mass = flerp(1.0, 160.0, dc->mass);
319 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
321 /* Calculate force and acceleration */
322 NR::Point force = n - dc->cur;
324 // If force is below the absolute threshold ERASER_EPSILON,
325 // or we haven't yet reached ERASER_VEL_START (i.e. at the beginning of stroke)
326 // _and_ the force is below the (higher) ERASER_EPSILON_START threshold,
327 // discard this move.
328 // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
329 // especially bothersome at the start of the stroke where we don't yet have the inertia to
330 // smooth them out.
331 if ( NR::L2(force) < ERASER_EPSILON || (dc->vel_max < ERASER_VEL_START && NR::L2(force) < ERASER_EPSILON_START)) {
332 return FALSE;
333 }
335 dc->acc = force / mass;
337 /* Calculate new velocity */
338 dc->vel += dc->acc;
340 if (NR::L2(dc->vel) > dc->vel_max)
341 dc->vel_max = NR::L2(dc->vel);
343 /* Calculate angle of drawing tool */
345 double a1;
346 if (dc->usetilt) {
347 // 1a. calculate nib angle from input device tilt:
348 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
350 if (length > 0) {
351 NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
352 a1 = atan2(ang1);
353 }
354 else
355 a1 = 0.0;
356 }
357 else {
358 // 1b. fixed dc->angle (absolutely flat nib):
359 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
360 NR::Point ang1 = NR::Point(-sin(radians), cos(radians));
361 a1 = atan2(ang1);
362 }
364 // 2. perpendicular to dc->vel (absolutely non-flat nib):
365 gdouble const mag_vel = NR::L2(dc->vel);
366 if ( mag_vel < ERASER_EPSILON ) {
367 return FALSE;
368 }
369 NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
371 // 3. Average them using flatness parameter:
372 // calculate angles
373 double a2 = atan2(ang2);
374 // flip a2 to force it to be in the same half-circle as a1
375 bool flipped = false;
376 if (fabs (a2-a1) > 0.5*M_PI) {
377 a2 += M_PI;
378 flipped = true;
379 }
380 // normalize a2
381 if (a2 > M_PI)
382 a2 -= 2*M_PI;
383 if (a2 < -M_PI)
384 a2 += 2*M_PI;
385 // find the flatness-weighted bisector angle, unflip if a2 was flipped
386 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
387 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
389 // Try to detect a sudden flip when the new angle differs too much from the previous for the
390 // current velocity; in that case discard this move
391 double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
392 if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
393 return FALSE;
394 }
396 // convert to point
397 dc->ang = NR::Point (cos (new_ang), sin (new_ang));
399 // 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);
401 /* Apply drag */
402 dc->vel *= 1.0 - drag;
404 /* Update position */
405 dc->last = dc->cur;
406 dc->cur += dc->vel;
408 return TRUE;
409 }
411 static void
412 sp_eraser_brush(SPEraserContext *dc)
413 {
414 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
416 // How much velocity thins strokestyle
417 double vel_thin = flerp (0, 160, dc->vel_thin);
419 // Influence of pressure on thickness
420 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
422 // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
423 // drag)
424 NR::Point brush = sp_eraser_get_vpoint(dc, dc->cur);
425 NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush);
427 double trace_thick = 1;
429 double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
431 double tremble_left = 0, tremble_right = 0;
432 if (dc->tremor > 0) {
433 // obtain two normally distributed random variables, using polar Box-Muller transform
434 double x1, x2, w, y1, y2;
435 do {
436 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
437 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
438 w = x1 * x1 + x2 * x2;
439 } while ( w >= 1.0 );
440 w = sqrt( (-2.0 * log( w ) ) / w );
441 y1 = x1 * w;
442 y2 = x2 * w;
444 // deflect both left and right edges randomly and independently, so that:
445 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
446 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
447 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
448 // comparatively smooth and slow ones excessively jittery
449 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
450 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
451 }
453 if ( width < 0.02 * dc->width ) {
454 width = 0.02 * dc->width;
455 }
457 double dezoomify_factor = 0.05 * 1000;
458 if (!dc->abs_width) {
459 dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
460 }
462 NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
463 NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
465 dc->point1[dc->npoints] = brush + del_left;
466 dc->point2[dc->npoints] = brush - del_right;
468 dc->del = 0.5*(del_left + del_right);
470 dc->npoints++;
471 }
473 void
474 sp_erc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
475 {
476 desktop->setToolboxAdjustmentValue (id, value);
477 }
479 static void
480 eraser_cancel(SPEraserContext *dc)
481 {
482 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
483 dc->dragging = FALSE;
484 dc->is_drawing = false;
485 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
486 /* Remove all temporary line segments */
487 while (dc->segments) {
488 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
489 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
490 }
491 /* reset accumulated curve */
492 dc->accumulated->reset();
493 clear_current(dc);
494 if (dc->repr) {
495 dc->repr = NULL;
496 }
497 }
500 gint
501 sp_eraser_context_root_handler(SPEventContext *event_context,
502 GdkEvent *event)
503 {
504 SPEraserContext *dc = SP_ERASER_CONTEXT(event_context);
505 SPDesktop *desktop = event_context->desktop;
507 gint ret = FALSE;
509 switch (event->type) {
510 case GDK_BUTTON_PRESS:
511 if (event->button.button == 1 && !event_context->space_panning) {
513 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
515 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
516 return TRUE;
517 }
519 NR::Point const button_w(event->button.x,
520 event->button.y);
521 NR::Point const button_dt(desktop->w2d(button_w));
522 sp_eraser_reset(dc, button_dt);
523 sp_eraser_extinput(dc, event);
524 sp_eraser_apply(dc, button_dt);
525 dc->accumulated->reset();
526 if (dc->repr) {
527 dc->repr = NULL;
528 }
530 Inkscape::Rubberband::get()->start(desktop, button_dt);
531 Inkscape::Rubberband::get()->setMode(RUBBERBAND_MODE_TOUCHPATH);
533 /* initialize first point */
534 dc->npoints = 0;
536 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
537 ( GDK_KEY_PRESS_MASK |
538 GDK_BUTTON_RELEASE_MASK |
539 GDK_POINTER_MOTION_MASK |
540 GDK_BUTTON_PRESS_MASK ),
541 NULL,
542 event->button.time);
544 ret = TRUE;
546 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
547 dc->is_drawing = true;
548 }
549 break;
550 case GDK_MOTION_NOTIFY:
551 {
552 NR::Point const motion_w(event->motion.x,
553 event->motion.y);
554 NR::Point motion_dt(desktop->w2d(motion_w));
555 sp_eraser_extinput(dc, event);
557 dc->_message_context->clear();
559 if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
560 dc->dragging = TRUE;
562 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> an eraser stroke"));
564 if (!sp_eraser_apply(dc, motion_dt)) {
565 ret = TRUE;
566 break;
567 }
569 if ( dc->cur != dc->last ) {
570 sp_eraser_brush(dc);
571 g_assert( dc->npoints > 0 );
572 fit_and_split(dc, FALSE);
573 }
574 ret = TRUE;
575 }
576 Inkscape::Rubberband::get()->move(motion_dt);
577 }
578 break;
581 case GDK_BUTTON_RELEASE:
582 {
583 NR::Point const motion_w(event->button.x, event->button.y);
584 NR::Point const motion_dt(desktop->w2d(motion_w));
586 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
587 sp_canvas_end_forced_full_redraws(desktop->canvas);
588 dc->is_drawing = false;
590 if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
591 dc->dragging = FALSE;
593 NR::Maybe<NR::Rect> const b = Inkscape::Rubberband::get()->getRectangle();
595 sp_eraser_apply(dc, motion_dt);
597 /* Remove all temporary line segments */
598 while (dc->segments) {
599 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
600 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
601 }
603 /* Create object */
604 fit_and_split(dc, TRUE);
605 accumulate_eraser(dc);
606 set_to_accumulated(dc); // performs document_done
608 /* reset accumulated curve */
609 dc->accumulated->reset();
611 clear_current(dc);
612 if (dc->repr) {
613 dc->repr = NULL;
614 }
616 Inkscape::Rubberband::get()->stop();
617 dc->_message_context->clear();
618 ret = TRUE;
619 }
620 break;
621 }
623 case GDK_KEY_PRESS:
624 switch (get_group0_keyval (&event->key)) {
625 case GDK_Up:
626 case GDK_KP_Up:
627 if (!MOD__CTRL_ONLY) {
628 dc->angle += 5.0;
629 if (dc->angle > 90.0)
630 dc->angle = 90.0;
631 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
632 ret = TRUE;
633 }
634 break;
635 case GDK_Down:
636 case GDK_KP_Down:
637 if (!MOD__CTRL_ONLY) {
638 dc->angle -= 5.0;
639 if (dc->angle < -90.0)
640 dc->angle = -90.0;
641 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
642 ret = TRUE;
643 }
644 break;
645 case GDK_Right:
646 case GDK_KP_Right:
647 if (!MOD__CTRL_ONLY) {
648 dc->width += 0.01;
649 if (dc->width > 1.0)
650 dc->width = 1.0;
651 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100); // the same spinbutton is for alt+x
652 ret = TRUE;
653 }
654 break;
655 case GDK_Left:
656 case GDK_KP_Left:
657 if (!MOD__CTRL_ONLY) {
658 dc->width -= 0.01;
659 if (dc->width < 0.01)
660 dc->width = 0.01;
661 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
662 ret = TRUE;
663 }
664 break;
665 case GDK_Home:
666 case GDK_KP_Home:
667 dc->width = 0.01;
668 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
669 ret = TRUE;
670 break;
671 case GDK_End:
672 case GDK_KP_End:
673 dc->width = 1.0;
674 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
675 ret = TRUE;
676 break;
677 case GDK_x:
678 case GDK_X:
679 if (MOD__ALT_ONLY) {
680 desktop->setToolboxFocusTo ("altx-eraser");
681 ret = TRUE;
682 }
683 break;
684 case GDK_Escape:
685 Inkscape::Rubberband::get()->stop();
686 if (dc->is_drawing) {
687 // if drawing, cancel, otherwise pass it up for deselecting
688 eraser_cancel (dc);
689 ret = TRUE;
690 }
691 break;
692 case GDK_z:
693 case GDK_Z:
694 if (MOD__CTRL_ONLY && dc->is_drawing) {
695 // if drawing, cancel, otherwise pass it up for undo
696 eraser_cancel (dc);
697 ret = TRUE;
698 }
699 break;
700 default:
701 break;
702 }
703 break;
705 case GDK_KEY_RELEASE:
706 switch (get_group0_keyval(&event->key)) {
707 case GDK_Control_L:
708 case GDK_Control_R:
709 dc->_message_context->clear();
710 break;
711 default:
712 break;
713 }
715 default:
716 break;
717 }
719 if (!ret) {
720 if (((SPEventContextClass *) eraser_parent_class)->root_handler) {
721 ret = ((SPEventContextClass *) eraser_parent_class)->root_handler(event_context, event);
722 }
723 }
725 return ret;
726 }
729 static void
730 clear_current(SPEraserContext *dc)
731 {
732 // reset bpath
733 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
735 // reset curve
736 dc->currentcurve->reset();
737 dc->cal1->reset();
738 dc->cal2->reset();
740 // reset points
741 dc->npoints = 0;
742 }
744 static void
745 set_to_accumulated(SPEraserContext *dc)
746 {
747 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
748 bool workDone = false;
750 if (!dc->accumulated->is_empty()) {
751 NArtBpath *abp;
752 gchar *str;
754 if (!dc->repr) {
755 /* Create object */
756 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
757 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
759 /* Set style */
760 sp_desktop_apply_style_tool (desktop, repr, "tools.eraser", false);
762 dc->repr = repr;
764 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
765 Inkscape::GC::release(dc->repr);
766 item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
767 item->updateRepr();
768 }
769 abp = nr_artpath_affine(dc->accumulated->first_bpath(), sp_desktop_dt2root_affine(desktop));
770 str = sp_svg_write_path(abp);
771 g_assert( str != NULL );
772 g_free(abp);
773 dc->repr->setAttribute("d", str);
774 g_free(str);
776 if ( dc->repr ) {
777 bool wasSelection = false;
778 Inkscape::Selection *selection = sp_desktop_selection(desktop);
779 gint eraserMode = (prefs_get_int_attribute("tools.eraser", "mode", 0) != 0) ? 1 : 0;
780 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
782 SPItem* acid = SP_ITEM(desktop->doc()->getObjectByRepr(dc->repr));
783 NR::Maybe<NR::Rect> eraserBbox = acid->getBounds(NR::identity());
784 NR::Rect bounds = (*eraserBbox) * desktop->doc2dt();
785 std::vector<SPItem*> remainingItems;
786 GSList* toWorkOn = 0;
787 if (selection->isEmpty()) {
788 if ( eraserMode ) {
789 toWorkOn = sp_document_partial_items_in_box(sp_desktop_document(desktop), desktop->dkey, bounds);
790 } else {
791 Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
792 toWorkOn = sp_document_items_at_points(sp_desktop_document(desktop), desktop->dkey, r->getPoints());
793 }
794 toWorkOn = g_slist_remove( toWorkOn, acid );
795 } else {
796 toWorkOn = g_slist_copy(const_cast<GSList*>(selection->itemList()));
797 wasSelection = true;
798 }
800 if ( g_slist_length(toWorkOn) > 0 ) {
801 if ( eraserMode ) {
802 for (GSList *i = toWorkOn ; i ; i = i->next ) {
803 SPItem *item = SP_ITEM(i->data);
804 if ( eraserMode ) {
805 NR::Maybe<NR::Rect> bbox = item->getBounds(NR::identity());
806 if (bbox && bbox->intersects(*eraserBbox)) {
807 Inkscape::XML::Node* dup = dc->repr->duplicate(xml_doc);
808 dc->repr->parent()->appendChild(dup);
809 Inkscape::GC::release(dup); // parent takes over
811 selection->set(item);
812 selection->add(dup);
813 sp_selected_path_diff_skip_undo();
814 workDone = true; // TODO set this only if something was cut.
815 if ( !selection->isEmpty() ) {
816 // If the item was not completely erased, track the new remainder.
817 GSList *nowSel = g_slist_copy(const_cast<GSList *>(selection->itemList()));
818 for (GSList const *i2 = nowSel ; i2 ; i2 = i2->next ) {
819 remainingItems.push_back(SP_ITEM(i2->data));
820 }
821 g_slist_free(nowSel);
822 }
823 } else {
824 remainingItems.push_back(item);
825 }
826 }
827 }
828 } else {
829 for (GSList *i = toWorkOn ; i ; i = i->next ) {
830 sp_object_ref( SP_ITEM(i->data), 0 );
831 }
832 for (GSList *i = toWorkOn ; i ; i = i->next ) {
833 SPItem *item = SP_ITEM(i->data);
834 item->deleteObject(true);
835 sp_object_unref(item);
836 workDone = true;
837 }
838 }
840 g_slist_free(toWorkOn);
842 if ( !eraserMode ) {
843 //sp_selection_delete();
844 remainingItems.clear();
845 }
847 selection->clear();
848 if ( wasSelection ) {
849 if ( !remainingItems.empty() ) {
850 selection->add(remainingItems.begin(), remainingItems.end());
851 }
852 }
853 }
855 // Remove the eraser stroke itself:
856 sp_repr_unparent( dc->repr );
857 dc->repr = 0;
858 }
859 } else {
860 if (dc->repr) {
861 sp_repr_unparent(dc->repr);
862 dc->repr = 0;
863 }
864 }
867 if ( workDone ) {
868 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_ERASER,
869 _("Draw eraser stroke"));
870 } else {
871 sp_document_cancel(sp_desktop_document(desktop));
872 }
873 }
875 static void
876 add_cap(SPCurve *curve,
877 NR::Point const &pre, NR::Point const &from,
878 NR::Point const &to, NR::Point const &post,
879 double rounding)
880 {
881 NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
882 double mag = NR::L2(vel);
884 NR::Point v_in = from - pre;
885 double mag_in = NR::L2(v_in);
886 if ( mag_in > ERASER_EPSILON ) {
887 v_in = mag * v_in / mag_in;
888 } else {
889 v_in = NR::Point(0, 0);
890 }
892 NR::Point v_out = to - post;
893 double mag_out = NR::L2(v_out);
894 if ( mag_out > ERASER_EPSILON ) {
895 v_out = mag * v_out / mag_out;
896 } else {
897 v_out = NR::Point(0, 0);
898 }
900 if ( NR::L2(v_in) > ERASER_EPSILON || NR::L2(v_out) > ERASER_EPSILON ) {
901 curve->curveto(from + v_in, to + v_out, to);
902 }
903 }
905 static void
906 accumulate_eraser(SPEraserContext *dc)
907 {
908 if ( !dc->cal1->is_empty() && !dc->cal2->is_empty() ) {
909 dc->accumulated->reset(); /* Is this required ?? */
910 SPCurve *rev_cal2 = dc->cal2->create_reverse();
912 g_assert(dc->cal1->_end > 1);
913 g_assert(rev_cal2->_end > 1);
914 g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
915 g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
916 g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
917 g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
918 g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->_end-1)->code == NR_CURVETO);
919 g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->_end-1)->code == NR_CURVETO);
921 dc->accumulated->append(dc->cal1, FALSE);
923 add_cap(dc->accumulated, SP_CURVE_SEGMENT(dc->cal1, dc->cal1->_end-1)->c(2), SP_CURVE_SEGMENT(dc->cal1, dc->cal1->_end-1)->c(3), SP_CURVE_SEGMENT(rev_cal2, 0)->c(3), SP_CURVE_SEGMENT(rev_cal2, 1)->c(1), dc->cap_rounding);
925 dc->accumulated->append(rev_cal2, TRUE);
927 add_cap(dc->accumulated, SP_CURVE_SEGMENT(rev_cal2, rev_cal2->_end-1)->c(2), SP_CURVE_SEGMENT(rev_cal2, rev_cal2->_end-1)->c(3), SP_CURVE_SEGMENT(dc->cal1, 0)->c(3), SP_CURVE_SEGMENT(dc->cal1, 1)->c(1), dc->cap_rounding);
929 dc->accumulated->closepath();
931 rev_cal2->unref();
933 dc->cal1->reset();
934 dc->cal2->reset();
935 }
936 }
938 static double square(double const x)
939 {
940 return x * x;
941 }
943 static void
944 fit_and_split(SPEraserContext *dc, gboolean release)
945 {
946 double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_ERASER );
948 #ifdef ERASER_VERBOSE
949 g_print("[F&S:R=%c]", release?'T':'F');
950 #endif
952 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
953 return; // just clicked
955 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
956 #define BEZIER_SIZE 4
957 #define BEZIER_MAX_BEZIERS 8
958 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
960 #ifdef ERASER_VERBOSE
961 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
962 dc->npoints, release ? "TRUE" : "FALSE");
963 #endif
965 /* Current eraser */
966 if ( dc->cal1->_end == 0 || dc->cal2->_end == 0 ) {
967 /* dc->npoints > 0 */
968 /* g_print("erasers(1|2) reset\n"); */
969 dc->cal1->reset();
970 dc->cal2->reset();
972 dc->cal1->moveto(dc->point1[0]);
973 dc->cal2->moveto(dc->point2[0]);
974 }
976 NR::Point b1[BEZIER_MAX_LENGTH];
977 gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
978 tolerance_sq, BEZIER_MAX_BEZIERS);
979 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
981 NR::Point b2[BEZIER_MAX_LENGTH];
982 gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
983 tolerance_sq, BEZIER_MAX_BEZIERS);
984 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
986 if ( nb1 != -1 && nb2 != -1 ) {
987 /* Fit and draw and reset state */
988 #ifdef ERASER_VERBOSE
989 g_print("nb1:%d nb2:%d\n", nb1, nb2);
990 #endif
991 /* CanvasShape */
992 if (! release) {
993 dc->currentcurve->reset();
994 dc->currentcurve->moveto(b1[0]);
995 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
996 dc->currentcurve->curveto(bp1[1],
997 bp1[2], bp1[3]);
998 }
999 dc->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]);
1000 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1001 dc->currentcurve->curveto(bp2[2], bp2[1], bp2[0]);
1002 }
1003 // FIXME: dc->segments is always NULL at this point??
1004 if (!dc->segments) { // first segment
1005 add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
1006 }
1007 dc->currentcurve->closepath();
1008 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1009 }
1011 /* Current eraser */
1012 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1013 dc->cal1->curveto(bp1[1], bp1[2], bp1[3]);
1014 }
1015 for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1016 dc->cal2->curveto(bp2[1], bp2[2], bp2[3]);
1017 }
1018 } else {
1019 /* fixme: ??? */
1020 #ifdef ERASER_VERBOSE
1021 g_print("[fit_and_split] failed to fit-cubic.\n");
1022 #endif
1023 draw_temporary_box(dc);
1025 for (gint i = 1; i < dc->npoints; i++) {
1026 dc->cal1->lineto(dc->point1[i]);
1027 }
1028 for (gint i = 1; i < dc->npoints; i++) {
1029 dc->cal2->lineto(dc->point2[i]);
1030 }
1031 }
1033 /* Fit and draw and copy last point */
1034 #ifdef ERASER_VERBOSE
1035 g_print("[%d]Yup\n", dc->npoints);
1036 #endif
1037 if (!release) {
1038 gint eraserMode = (prefs_get_int_attribute("tools.eraser", "mode", 0) != 0) ? 1 : 0;
1039 g_assert(!dc->currentcurve->is_empty());
1041 SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1042 SP_TYPE_CANVAS_BPATH,
1043 NULL);
1044 SPCurve *curve = dc->currentcurve->copy();
1045 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1046 curve->unref();
1048 guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.eraser", true);
1049 //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.eraser", false);
1050 double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser");
1051 double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser", true);
1052 //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.eraser", false);
1053 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1054 //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1055 //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);
1056 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1057 /* fixme: Cannot we cascade it to root more clearly? */
1058 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1060 dc->segments = g_slist_prepend(dc->segments, cbp);
1062 if ( !eraserMode ) {
1063 sp_canvas_item_hide(cbp);
1064 sp_canvas_item_hide(dc->currentshape);
1065 }
1066 }
1068 dc->point1[0] = dc->point1[dc->npoints - 1];
1069 dc->point2[0] = dc->point2[dc->npoints - 1];
1070 dc->npoints = 1;
1071 } else {
1072 draw_temporary_box(dc);
1073 }
1074 }
1076 static void
1077 draw_temporary_box(SPEraserContext *dc)
1078 {
1079 dc->currentcurve->reset();
1081 dc->currentcurve->moveto(dc->point1[dc->npoints-1]);
1082 for (gint i = dc->npoints-2; i >= 0; i--) {
1083 dc->currentcurve->lineto(dc->point1[i]);
1084 }
1085 for (gint i = 0; i < dc->npoints; i++) {
1086 dc->currentcurve->lineto(dc->point2[i]);
1087 }
1088 if (dc->npoints >= 2) {
1089 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);
1090 }
1092 dc->currentcurve->closepath();
1093 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1094 }
1096 /*
1097 Local Variables:
1098 mode:c++
1099 c-file-style:"stroustrup"
1100 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1101 indent-tabs-mode:nil
1102 fill-column:99
1103 End:
1104 */
1105 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :