Code

Merge and cleanup of GSoC C++-ification project.
[inkscape.git] / src / eraser-context.cpp
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  *   Abhishek Sharma
11  *
12  * The original dynadraw code:
13  *   Paul Haeberli <paul@sgi.com>
14  *
15  * Copyright (C) 1998 The Free Software Foundation
16  * Copyright (C) 1999-2005 authors
17  * Copyright (C) 2001-2002 Ximian, Inc.
18  * Copyright (C) 2005-2007 bulia byak
19  * Copyright (C) 2006 MenTaLguY
20  * Copyright (C) 2008 Jon A. Cruz
21  *
22  * Released under GNU GPL, read the file 'COPYING' for more information
23  */
25 #define noERASER_VERBOSE
27 #include "config.h"
29 #include <gtk/gtk.h>
30 #include <gdk/gdkkeysyms.h>
31 #include <glibmm/i18n.h>
32 #include <string>
33 #include <cstring>
34 #include <numeric>
36 #include "svg/svg.h"
37 #include "display/canvas-bpath.h"
38 #include <2geom/bezier-utils.h>
40 #include <glib/gmem.h>
41 #include "macros.h"
42 #include "document.h"
43 #include "selection.h"
44 #include "desktop.h"
45 #include "desktop-events.h"
46 #include "desktop-handles.h"
47 #include "desktop-style.h"
48 #include "message-context.h"
49 #include "preferences.h"
50 #include "pixmaps/cursor-eraser.xpm"
51 #include "xml/repr.h"
52 #include "context-fns.h"
53 #include "sp-item.h"
54 #include "color.h"
55 #include "rubberband.h"
56 #include "splivarot.h"
57 #include "sp-item-group.h"
58 #include "sp-shape.h"
59 #include "sp-path.h"
60 #include "sp-text.h"
61 #include "display/canvas-bpath.h"
62 #include "display/canvas-arena.h"
63 #include "livarot/Shape.h"
64 #include <2geom/isnan.h>
65 #include <2geom/pathvector.h>
67 #include "eraser-context.h"
69 using Inkscape::DocumentUndo;
71 #define ERC_RED_RGBA 0xff0000ff
73 #define TOLERANCE_ERASER 0.1
75 #define ERASER_EPSILON 0.5e-6
76 #define ERASER_EPSILON_START 0.5e-2
77 #define ERASER_VEL_START 1e-5
79 #define DRAG_MIN 0.0
80 #define DRAG_DEFAULT 1.0
81 #define DRAG_MAX 1.0
84 static void sp_eraser_context_class_init(SPEraserContextClass *klass);
85 static void sp_eraser_context_init(SPEraserContext *erc);
86 static void sp_eraser_context_dispose(GObject *object);
88 static void sp_eraser_context_setup(SPEventContext *ec);
89 static void sp_eraser_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val);
90 static gint sp_eraser_context_root_handler(SPEventContext *ec, GdkEvent *event);
92 static void clear_current(SPEraserContext *dc);
93 static void set_to_accumulated(SPEraserContext *dc);
94 static void add_cap(SPCurve *curve, Geom::Point const &pre, Geom::Point const &from, Geom::Point const &to, Geom::Point const &post, double rounding);
95 static void accumulate_eraser(SPEraserContext *dc);
97 static void fit_and_split(SPEraserContext *erc, gboolean release);
99 static void sp_eraser_reset(SPEraserContext *erc, Geom::Point p);
100 static Geom::Point sp_eraser_get_npoint(SPEraserContext const *erc, Geom::Point v);
101 static Geom::Point sp_eraser_get_vpoint(SPEraserContext const *erc, Geom::Point n);
102 static void draw_temporary_box(SPEraserContext *dc);
105 static SPEventContextClass *eraser_parent_class = 0;
107 GType sp_eraser_context_get_type(void)
109     static GType type = 0;
110     if (!type) {
111         GTypeInfo info = {
112             sizeof(SPEraserContextClass),
113             0, // base_init
114             0, // base_finalize
115             (GClassInitFunc)sp_eraser_context_class_init,
116             0, // class_finalize
117             0, // class_data
118             sizeof(SPEraserContext),
119             0, // n_preallocs
120             (GInstanceInitFunc)sp_eraser_context_init,
121             0 // value_table
122         };
123         type = g_type_register_static(SP_TYPE_COMMON_CONTEXT, "SPEraserContext", &info, static_cast<GTypeFlags>(0));
124     }
125     return type;
128 static void
129 sp_eraser_context_class_init(SPEraserContextClass *klass)
131     GObjectClass *object_class = (GObjectClass *) klass;
132     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
134     eraser_parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
136     object_class->dispose = sp_eraser_context_dispose;
138     event_context_class->setup = sp_eraser_context_setup;
139     event_context_class->set = sp_eraser_context_set;
140     event_context_class->root_handler = sp_eraser_context_root_handler;
143 static void
144 sp_eraser_context_init(SPEraserContext *erc)
146     erc->cursor_shape = cursor_eraser_xpm;
147     erc->hot_x = 4;
148     erc->hot_y = 4;
151 static void
152 sp_eraser_context_dispose(GObject *object)
154     //SPEraserContext *erc = SP_ERASER_CONTEXT(object);
156     G_OBJECT_CLASS(eraser_parent_class)->dispose(object);
159 static void
160 sp_eraser_context_setup(SPEventContext *ec)
162     SPEraserContext *erc = SP_ERASER_CONTEXT(ec);
163     SPDesktop *desktop = ec->desktop;
165     if (((SPEventContextClass *) eraser_parent_class)->setup)
166         ((SPEventContextClass *) eraser_parent_class)->setup(ec);
168     erc->accumulated = new SPCurve();
169     erc->currentcurve = new SPCurve();
171     erc->cal1 = new SPCurve();
172     erc->cal2 = new SPCurve();
174     erc->currentshape = sp_canvas_item_new(sp_desktop_sketch(desktop), SP_TYPE_CANVAS_BPATH, NULL);
175     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(erc->currentshape), ERC_RED_RGBA, SP_WIND_RULE_EVENODD);
176     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(erc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
177     /* fixme: Cannot we cascade it to root more clearly? */
178     g_signal_connect(G_OBJECT(erc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), desktop);
180 /*
181 static ProfileFloatElement f_profile[PROFILE_FLOAT_SIZE] = {
182     {"mass",0.02, 0.0, 1.0},
183     {"wiggle",0.0, 0.0, 1.0},
184     {"angle",30.0, -90.0, 90.0},
185     {"thinning",0.1, -1.0, 1.0},
186     {"tremor",0.0, 0.0, 1.0},
187     {"flatness",0.9, 0.0, 1.0},
188     {"cap_rounding",0.0, 0.0, 5.0}
189 };
190 */
192     sp_event_context_read(ec, "mass");
193     sp_event_context_read(ec, "wiggle");
194     sp_event_context_read(ec, "angle");
195     sp_event_context_read(ec, "width");
196     sp_event_context_read(ec, "thinning");
197     sp_event_context_read(ec, "tremor");
198     sp_event_context_read(ec, "flatness");
199     sp_event_context_read(ec, "tracebackground");
200     sp_event_context_read(ec, "usepressure");
201     sp_event_context_read(ec, "usetilt");
202     sp_event_context_read(ec, "abs_width");
203     sp_event_context_read(ec, "cap_rounding");
205     erc->is_drawing = false;
207     erc->_message_context = new Inkscape::MessageContext(desktop->messageStack());
209     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
210     if (prefs->getBool("/tools/eraser/selcue", 0) != 0) {
211         ec->enableSelectionCue();
212     }
213 // TODO temp force:
214     ec->enableSelectionCue();
218 static void
219 sp_eraser_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val)
221     //pass on up to parent class to handle common attributes.
222     if ( eraser_parent_class->set ) {
223         eraser_parent_class->set(ec, val);
224     }
227 static double
228 flerp(double f0, double f1, double p)
230     return f0 + ( f1 - f0 ) * p;
233 /* Get normalized point */
234 static Geom::Point
235 sp_eraser_get_npoint(SPEraserContext const *dc, Geom::Point v)
237     Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
238     double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
239     return Geom::Point(( v[Geom::X] - drect.min()[Geom::X] ) / max,  ( v[Geom::Y] - drect.min()[Geom::Y] ) / max);
242 /* Get view point */
243 static Geom::Point
244 sp_eraser_get_vpoint(SPEraserContext const *dc, Geom::Point n)
246     Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
247     double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
248     return Geom::Point(n[Geom::X] * max + drect.min()[Geom::X], n[Geom::Y] * max + drect.min()[Geom::Y]);
251 static void
252 sp_eraser_reset(SPEraserContext *dc, Geom::Point p)
254     dc->last = dc->cur = sp_eraser_get_npoint(dc, p);
255     dc->vel = Geom::Point(0,0);
256     dc->vel_max = 0;
257     dc->acc = Geom::Point(0,0);
258     dc->ang = Geom::Point(0,0);
259     dc->del = Geom::Point(0,0);
262 static void
263 sp_eraser_extinput(SPEraserContext *dc, GdkEvent *event)
265     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
266         dc->pressure = CLAMP (dc->pressure, ERC_MIN_PRESSURE, ERC_MAX_PRESSURE);
267     else
268         dc->pressure = ERC_DEFAULT_PRESSURE;
270     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
271         dc->xtilt = CLAMP (dc->xtilt, ERC_MIN_TILT, ERC_MAX_TILT);
272     else
273         dc->xtilt = ERC_DEFAULT_TILT;
275     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
276         dc->ytilt = CLAMP (dc->ytilt, ERC_MIN_TILT, ERC_MAX_TILT);
277     else
278         dc->ytilt = ERC_DEFAULT_TILT;
282 static gboolean
283 sp_eraser_apply(SPEraserContext *dc, Geom::Point p)
285     Geom::Point n = sp_eraser_get_npoint(dc, p);
287     /* Calculate mass and drag */
288     double const mass = flerp(1.0, 160.0, dc->mass);
289     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
291     /* Calculate force and acceleration */
292     Geom::Point force = n - dc->cur;
294     // If force is below the absolute threshold ERASER_EPSILON,
295     // or we haven't yet reached ERASER_VEL_START (i.e. at the beginning of stroke)
296     // _and_ the force is below the (higher) ERASER_EPSILON_START threshold,
297     // discard this move. 
298     // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
299     // especially bothersome at the start of the stroke where we don't yet have the inertia to
300     // smooth them out.
301     if ( Geom::L2(force) < ERASER_EPSILON || (dc->vel_max < ERASER_VEL_START && Geom::L2(force) < ERASER_EPSILON_START)) {
302         return FALSE;
303     }
305     dc->acc = force / mass;
307     /* Calculate new velocity */
308     dc->vel += dc->acc;
310     if (Geom::L2(dc->vel) > dc->vel_max)
311         dc->vel_max = Geom::L2(dc->vel);
313     /* Calculate angle of drawing tool */
315     double a1;
316     if (dc->usetilt) {
317         // 1a. calculate nib angle from input device tilt:
318         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
320         if (length > 0) {
321             Geom::Point ang1 = Geom::Point(dc->ytilt/length, dc->xtilt/length);
322             a1 = atan2(ang1);
323         }
324         else
325             a1 = 0.0;
326     }
327     else {
328         // 1b. fixed dc->angle (absolutely flat nib):
329         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
330         Geom::Point ang1 = Geom::Point(-sin(radians),  cos(radians));
331         a1 = atan2(ang1);
332     }
334     // 2. perpendicular to dc->vel (absolutely non-flat nib):
335     gdouble const mag_vel = Geom::L2(dc->vel);
336     if ( mag_vel < ERASER_EPSILON ) {
337         return FALSE;
338     }
339     Geom::Point ang2 = Geom::rot90(dc->vel) / mag_vel;
341     // 3. Average them using flatness parameter:
342     // calculate angles
343     double a2 = atan2(ang2);
344     // flip a2 to force it to be in the same half-circle as a1
345     bool flipped = false;
346     if (fabs (a2-a1) > 0.5*M_PI) {
347         a2 += M_PI;
348         flipped = true;
349     }
350     // normalize a2
351     if (a2 > M_PI)
352         a2 -= 2*M_PI;
353     if (a2 < -M_PI)
354         a2 += 2*M_PI;
355     // find the flatness-weighted bisector angle, unflip if a2 was flipped
356     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
357     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
359     // Try to detect a sudden flip when the new angle differs too much from the previous for the
360     // current velocity; in that case discard this move
361     double angle_delta = Geom::L2(Geom::Point (cos (new_ang), sin (new_ang)) - dc->ang);
362     if ( angle_delta / Geom::L2(dc->vel) > 4000 ) {
363         return FALSE;
364     }
366     // convert to point
367     dc->ang = Geom::Point (cos (new_ang), sin (new_ang));
369 //    g_print ("force %g  acc %g  vel_max %g  vel %g  a1 %g  a2 %g  new_ang %g\n", Geom::L2(force), Geom::L2(dc->acc), dc->vel_max, Geom::L2(dc->vel), a1, a2, new_ang);
371     /* Apply drag */
372     dc->vel *= 1.0 - drag;
374     /* Update position */
375     dc->last = dc->cur;
376     dc->cur += dc->vel;
378     return TRUE;
381 static void
382 sp_eraser_brush(SPEraserContext *dc)
384     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
386     // How much velocity thins strokestyle
387     double vel_thin = flerp (0, 160, dc->vel_thin);
389     // Influence of pressure on thickness
390     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
392     // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
393     // drag)
394     Geom::Point brush = sp_eraser_get_vpoint(dc, dc->cur);
395     Geom::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush); 
397     double trace_thick = 1;
399     double width = (pressure_thick * trace_thick - vel_thin * Geom::L2(dc->vel)) * dc->width;
401     double tremble_left = 0, tremble_right = 0;
402     if (dc->tremor > 0) {
403         // obtain two normally distributed random variables, using polar Box-Muller transform
404         double x1, x2, w, y1, y2;
405         do {
406             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
407             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
408             w = x1 * x1 + x2 * x2;
409         } while ( w >= 1.0 );
410         w = sqrt( (-2.0 * log( w ) ) / w );
411         y1 = x1 * w;
412         y2 = x2 * w;
414         // deflect both left and right edges randomly and independently, so that:
415         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
416         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
417         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
418         // comparatively smooth and slow ones excessively jittery
419         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
420         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
421     }
423     if ( width < 0.02 * dc->width ) {
424         width = 0.02 * dc->width;
425     }
427     double dezoomify_factor = 0.05 * 1000;
428     if (!dc->abs_width) {
429         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
430     }
432     Geom::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
433     Geom::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
435     dc->point1[dc->npoints] = brush + del_left;
436     dc->point2[dc->npoints] = brush - del_right;
438     dc->del = 0.5*(del_left + del_right);
440     dc->npoints++;
443 void
444 sp_erc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
446     desktop->setToolboxAdjustmentValue (id, value);
449 static void
450 eraser_cancel(SPEraserContext *dc)
452     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
453     dc->dragging = FALSE;
454     dc->is_drawing = false;
455     sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
456             /* Remove all temporary line segments */
457             while (dc->segments) {
458                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
459                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
460             }
461             /* reset accumulated curve */
462             dc->accumulated->reset();
463             clear_current(dc);
464             if (dc->repr) {
465                 dc->repr = NULL;
466             }
470 gint
471 sp_eraser_context_root_handler(SPEventContext *event_context,
472                                   GdkEvent *event)
474     SPEraserContext *dc = SP_ERASER_CONTEXT(event_context);
475     SPDesktop *desktop = event_context->desktop;
477     gint ret = FALSE;
479     switch (event->type) {
480         case GDK_BUTTON_PRESS:
481             if (event->button.button == 1 && !event_context->space_panning) {
483                 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
484                     return TRUE;
485                 }
487                 Geom::Point const button_w(event->button.x,
488                                          event->button.y);
489                 Geom::Point const button_dt(desktop->w2d(button_w));
490                 sp_eraser_reset(dc, button_dt);
491                 sp_eraser_extinput(dc, event);
492                 sp_eraser_apply(dc, button_dt);
493                 dc->accumulated->reset();
494                 if (dc->repr) {
495                     dc->repr = NULL;
496                 }
498                 Inkscape::Rubberband::get(desktop)->start(desktop, button_dt);
499                 Inkscape::Rubberband::get(desktop)->setMode(RUBBERBAND_MODE_TOUCHPATH);
501                 /* initialize first point */
502                 dc->npoints = 0;
504                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
505                                     ( GDK_KEY_PRESS_MASK |
506                                       GDK_BUTTON_RELEASE_MASK |
507                                       GDK_POINTER_MOTION_MASK |
508                                       GDK_BUTTON_PRESS_MASK ),
509                                     NULL,
510                                     event->button.time);
512                 ret = TRUE;
514                 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
515                 dc->is_drawing = true;
516             }
517             break;
518         case GDK_MOTION_NOTIFY:
519         {
520             Geom::Point const motion_w(event->motion.x,
521                                      event->motion.y);
522             Geom::Point motion_dt(desktop->w2d(motion_w));
523             sp_eraser_extinput(dc, event);
525             dc->_message_context->clear();
527             if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
528                 dc->dragging = TRUE;
530                 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> an eraser stroke"));
532                 if (!sp_eraser_apply(dc, motion_dt)) {
533                     ret = TRUE;
534                     break;
535                 }
537                 if ( dc->cur != dc->last ) {
538                     sp_eraser_brush(dc);
539                     g_assert( dc->npoints > 0 );
540                     fit_and_split(dc, FALSE);
541                 }
542                 ret = TRUE;
543             }
544             Inkscape::Rubberband::get(desktop)->move(motion_dt);
545         }
546         break;
549     case GDK_BUTTON_RELEASE:
550     {
551         Geom::Point const motion_w(event->button.x, event->button.y);
552         Geom::Point const motion_dt(desktop->w2d(motion_w));
554         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
555         sp_canvas_end_forced_full_redraws(desktop->canvas);
556         dc->is_drawing = false;
558         if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
559             dc->dragging = FALSE;
561             sp_eraser_apply(dc, motion_dt);
563             /* Remove all temporary line segments */
564             while (dc->segments) {
565                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
566                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
567             }
569             /* Create object */
570             fit_and_split(dc, TRUE);
571             accumulate_eraser(dc);
572             set_to_accumulated(dc); // performs document_done
574             /* reset accumulated curve */
575             dc->accumulated->reset();
577             clear_current(dc);
578             if (dc->repr) {
579                 dc->repr = NULL;
580             }
582             dc->_message_context->clear();
583             ret = TRUE;
584         }
585         if (Inkscape::Rubberband::get(desktop)->is_started()) {
586             Inkscape::Rubberband::get(desktop)->stop();
587         }
588             
589         break;
590     }
592     case GDK_KEY_PRESS:
593         switch (get_group0_keyval (&event->key)) {
594         case GDK_Up:
595         case GDK_KP_Up:
596             if (!MOD__CTRL_ONLY) {
597                 dc->angle += 5.0;
598                 if (dc->angle > 90.0)
599                     dc->angle = 90.0;
600                 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
601                 ret = TRUE;
602             }
603             break;
604         case GDK_Down:
605         case GDK_KP_Down:
606             if (!MOD__CTRL_ONLY) {
607                 dc->angle -= 5.0;
608                 if (dc->angle < -90.0)
609                     dc->angle = -90.0;
610                 sp_erc_update_toolbox (desktop, "eraser-angle", dc->angle);
611                 ret = TRUE;
612             }
613             break;
614         case GDK_Right:
615         case GDK_KP_Right:
616             if (!MOD__CTRL_ONLY) {
617                 dc->width += 0.01;
618                 if (dc->width > 1.0)
619                     dc->width = 1.0;
620                 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100); // the same spinbutton is for alt+x
621                 ret = TRUE;
622             }
623             break;
624         case GDK_Left:
625         case GDK_KP_Left:
626             if (!MOD__CTRL_ONLY) {
627                 dc->width -= 0.01;
628                 if (dc->width < 0.01)
629                     dc->width = 0.01;
630                 sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
631                 ret = TRUE;
632             }
633             break;
634         case GDK_Home:
635         case GDK_KP_Home:
636             dc->width = 0.01;
637             sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
638             ret = TRUE;
639             break;
640         case GDK_End:
641         case GDK_KP_End:
642             dc->width = 1.0;
643             sp_erc_update_toolbox (desktop, "altx-eraser", dc->width * 100);
644             ret = TRUE;
645             break;
646         case GDK_x:
647         case GDK_X:
648             if (MOD__ALT_ONLY) {
649                 desktop->setToolboxFocusTo ("altx-eraser");
650                 ret = TRUE;
651             }
652             break;
653         case GDK_Escape:
654             Inkscape::Rubberband::get(desktop)->stop();
655             if (dc->is_drawing) {
656                 // if drawing, cancel, otherwise pass it up for deselecting
657                 eraser_cancel (dc);
658                 ret = TRUE;
659             }
660             break;
661         case GDK_z:
662         case GDK_Z:
663             if (MOD__CTRL_ONLY && dc->is_drawing) {
664                 // if drawing, cancel, otherwise pass it up for undo
665                 eraser_cancel (dc);
666                 ret = TRUE;
667             }
668             break;
669         default:
670             break;
671         }
672         break;
674     case GDK_KEY_RELEASE:
675         switch (get_group0_keyval(&event->key)) {
676             case GDK_Control_L:
677             case GDK_Control_R:
678                 dc->_message_context->clear();
679                 break;
680             default:
681                 break;
682         }
684     default:
685         break;
686     }
688     if (!ret) {
689         if (((SPEventContextClass *) eraser_parent_class)->root_handler) {
690             ret = ((SPEventContextClass *) eraser_parent_class)->root_handler(event_context, event);
691         }
692     }
694     return ret;
698 static void
699 clear_current(SPEraserContext *dc)
701     // reset bpath
702     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
704     // reset curve
705     dc->currentcurve->reset();
706     dc->cal1->reset();
707     dc->cal2->reset();
709     // reset points
710     dc->npoints = 0;
713 static void
714 set_to_accumulated(SPEraserContext *dc)
716     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
717     bool workDone = false;
719     if (!dc->accumulated->is_empty()) {
720         if (!dc->repr) {
721             /* Create object */
722             Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc();
723             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
725             /* Set style */
726             sp_desktop_apply_style_tool (desktop, repr, "/tools/eraser", false);
728             dc->repr = repr;
730             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
731             Inkscape::GC::release(dc->repr);
732             item->transform = SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse();
733             item->updateRepr();
734         }
735         Geom::PathVector pathv = dc->accumulated->get_pathvector() * desktop->dt2doc();
736         gchar *str = sp_svg_write_path(pathv);
737         g_assert( str != NULL );
738         dc->repr->setAttribute("d", str);
739         g_free(str);
741         if ( dc->repr ) {
742             bool wasSelection = false;
743             Inkscape::Selection *selection = sp_desktop_selection(desktop);
744             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
745             
746             gint eraserMode = prefs->getBool("/tools/eraser/mode") ? 1 : 0;
747             Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc();
749             SPItem* acid = SP_ITEM(desktop->doc()->getObjectByRepr(dc->repr));
750             Geom::OptRect eraserBbox = acid->getBounds(Geom::identity());
751             Geom::Rect bounds = (*eraserBbox) * desktop->doc2dt();
752             std::vector<SPItem*> remainingItems;
753             GSList* toWorkOn = 0;
754             if (selection->isEmpty()) {
755                 if ( eraserMode ) {
756                     toWorkOn = sp_desktop_document(desktop)->getItemsPartiallyInBox(desktop->dkey, bounds);
757                 } else {
758                     Inkscape::Rubberband *r = Inkscape::Rubberband::get(desktop);
759                     toWorkOn = sp_desktop_document(desktop)->getItemsAtPoints(desktop->dkey, r->getPoints());
760                 }
761                 toWorkOn = g_slist_remove( toWorkOn, acid );
762             } else {
763                 toWorkOn = g_slist_copy(const_cast<GSList*>(selection->itemList()));
764                 wasSelection = true;
765             }
767             if ( g_slist_length(toWorkOn) > 0 ) {
768                 if ( eraserMode ) {
769                     for (GSList *i = toWorkOn ; i ; i = i->next ) {
770                         SPItem *item = SP_ITEM(i->data);
771                         if ( eraserMode ) {
772                             Geom::OptRect bbox = item->getBounds(Geom::identity());
773                             if (bbox && bbox->intersects(*eraserBbox)) {
774                                 Inkscape::XML::Node* dup = dc->repr->duplicate(xml_doc);
775                                 dc->repr->parent()->appendChild(dup);
776                                 Inkscape::GC::release(dup); // parent takes over
778                                 selection->set(item);
779                                 selection->add(dup);
780                                 sp_selected_path_diff_skip_undo(desktop);
781                                 workDone = true; // TODO set this only if something was cut.
782                                 if ( !selection->isEmpty() ) {
783                                     // If the item was not completely erased, track the new remainder.
784                                     GSList *nowSel = g_slist_copy(const_cast<GSList *>(selection->itemList()));
785                                     for (GSList const *i2 = nowSel ; i2 ; i2 = i2->next ) {
786                                         remainingItems.push_back(SP_ITEM(i2->data));
787                                     }
788                                     g_slist_free(nowSel);
789                                 }
790                             } else {
791                                 remainingItems.push_back(item);
792                             }
793                         }
794                     }
795                 } else {
796                     for (GSList *i = toWorkOn ; i ; i = i->next ) {
797                         sp_object_ref( SP_ITEM(i->data), 0 );
798                     }
799                     for (GSList *i = toWorkOn ; i ; i = i->next ) {
800                         SPItem *item = SP_ITEM(i->data);
801                         item->deleteObject(true);
802                         sp_object_unref(item);
803                         workDone = true;
804                     }
805                 }
807                 g_slist_free(toWorkOn);
809                 if ( !eraserMode ) {
810                     //sp_selection_delete(desktop);
811                     remainingItems.clear();
812                 }
814                 selection->clear();
815                 if ( wasSelection ) {
816                     if ( !remainingItems.empty() ) {
817                         selection->add(remainingItems.begin(), remainingItems.end());
818                     }
819                 }
820             }
822             // Remove the eraser stroke itself:
823             sp_repr_unparent( dc->repr );
824             dc->repr = 0;
825         }
826     } else {
827         if (dc->repr) {
828             sp_repr_unparent(dc->repr);
829             dc->repr = 0;
830         }
831     }
834     if ( workDone ) {
835         DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_ERASER, 
836                            _("Draw eraser stroke"));
837     } else {
838         DocumentUndo::cancel(sp_desktop_document(desktop));
839     }
842 static void
843 add_cap(SPCurve *curve,
844         Geom::Point const &pre, Geom::Point const &from,
845         Geom::Point const &to, Geom::Point const &post,
846         double rounding)
848     Geom::Point vel = rounding * Geom::rot90( to - from ) / sqrt(2.0);
849     double mag = Geom::L2(vel);
851     Geom::Point v_in = from - pre;
852     double mag_in = Geom::L2(v_in);
853     if ( mag_in > ERASER_EPSILON ) {
854         v_in = mag * v_in / mag_in;
855     } else {
856         v_in = Geom::Point(0, 0);
857     }
859     Geom::Point v_out = to - post;
860     double mag_out = Geom::L2(v_out);
861     if ( mag_out > ERASER_EPSILON ) {
862         v_out = mag * v_out / mag_out;
863     } else {
864         v_out = Geom::Point(0, 0);
865     }
867     if ( Geom::L2(v_in) > ERASER_EPSILON || Geom::L2(v_out) > ERASER_EPSILON ) {
868         curve->curveto(from + v_in, to + v_out, to);
869     }
872 static void
873 accumulate_eraser(SPEraserContext *dc)
875     if ( !dc->cal1->is_empty() && !dc->cal2->is_empty() ) {
876         dc->accumulated->reset(); /*  Is this required ?? */
877         SPCurve *rev_cal2 = dc->cal2->create_reverse();
879         g_assert(dc->cal1->get_segment_count() > 0);
880         g_assert(rev_cal2->get_segment_count() > 0);
881         g_assert( ! dc->cal1->first_path()->closed() );
882         g_assert( ! rev_cal2->first_path()->closed() );
884         Geom::CubicBezier const * dc_cal1_firstseg  = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->first_segment() );
885         Geom::CubicBezier const * rev_cal2_firstseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->first_segment() );
886         Geom::CubicBezier const * dc_cal1_lastseg   = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->last_segment() );
887         Geom::CubicBezier const * rev_cal2_lastseg  = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->last_segment() );
888         g_assert( dc_cal1_firstseg );
889         g_assert( rev_cal2_firstseg );
890         g_assert( dc_cal1_lastseg );
891         g_assert( rev_cal2_lastseg );
893         dc->accumulated->append(dc->cal1, FALSE);
895         add_cap(dc->accumulated, (*dc_cal1_lastseg)[2], (*dc_cal1_lastseg)[3], (*rev_cal2_firstseg)[0], (*rev_cal2_firstseg)[1], dc->cap_rounding);
897         dc->accumulated->append(rev_cal2, TRUE);
899         add_cap(dc->accumulated, (*rev_cal2_lastseg)[2], (*rev_cal2_lastseg)[3], (*dc_cal1_firstseg)[0], (*dc_cal1_firstseg)[1], dc->cap_rounding);
901         dc->accumulated->closepath();
903         rev_cal2->unref();
905         dc->cal1->reset();
906         dc->cal2->reset();
907     }
910 static double square(double const x)
912     return x * x;
915 static void
916 fit_and_split(SPEraserContext *dc, gboolean release)
918     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
920     double const tolerance_sq = square( desktop->w2d().descrim() * TOLERANCE_ERASER );
922 #ifdef ERASER_VERBOSE
923     g_print("[F&S:R=%c]", release?'T':'F');
924 #endif
926     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
927         return; // just clicked
929     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
930 #define BEZIER_SIZE       4
931 #define BEZIER_MAX_BEZIERS  8
932 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
934 #ifdef ERASER_VERBOSE
935         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
936                 dc->npoints, release ? "TRUE" : "FALSE");
937 #endif
939         /* Current eraser */
940         if ( dc->cal1->is_empty() || dc->cal2->is_empty() ) {
941             /* dc->npoints > 0 */
942             /* g_print("erasers(1|2) reset\n"); */
943             dc->cal1->reset();
944             dc->cal2->reset();
946             dc->cal1->moveto(dc->point1[0]);
947             dc->cal2->moveto(dc->point2[0]);
948         }
950         Geom::Point b1[BEZIER_MAX_LENGTH];
951         gint const nb1 = Geom::bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
952                                                tolerance_sq, BEZIER_MAX_BEZIERS);
953         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
955         Geom::Point b2[BEZIER_MAX_LENGTH];
956         gint const nb2 = Geom::bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
957                                                tolerance_sq, BEZIER_MAX_BEZIERS);
958         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
960         if ( nb1 != -1 && nb2 != -1 ) {
961             /* Fit and draw and reset state */
962 #ifdef ERASER_VERBOSE
963             g_print("nb1:%d nb2:%d\n", nb1, nb2);
964 #endif
965             /* CanvasShape */
966             if (! release) {
967                 dc->currentcurve->reset();
968                 dc->currentcurve->moveto(b1[0]);
969                 for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
970                     dc->currentcurve->curveto(bp1[1],
971                                      bp1[2], bp1[3]);
972                 }
973                 dc->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]);
974                 for (Geom::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
975                     dc->currentcurve->curveto(bp2[2], bp2[1], bp2[0]);
976                 }
977                 // FIXME: dc->segments is always NULL at this point??
978                 if (!dc->segments) { // first segment
979                     add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
980                 }
981                 dc->currentcurve->closepath();
982                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
983             }
985             /* Current eraser */
986             for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
987                 dc->cal1->curveto(bp1[1], bp1[2], bp1[3]);
988             }
989             for (Geom::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
990                 dc->cal2->curveto(bp2[1], bp2[2], bp2[3]);
991             }
992         } else {
993             /* fixme: ??? */
994 #ifdef ERASER_VERBOSE
995             g_print("[fit_and_split] failed to fit-cubic.\n");
996 #endif
997             draw_temporary_box(dc);
999             for (gint i = 1; i < dc->npoints; i++) {
1000                 dc->cal1->lineto(dc->point1[i]);
1001             }
1002             for (gint i = 1; i < dc->npoints; i++) {
1003                 dc->cal2->lineto(dc->point2[i]);
1004             }
1005         }
1007         /* Fit and draw and copy last point */
1008 #ifdef ERASER_VERBOSE
1009         g_print("[%d]Yup\n", dc->npoints);
1010 #endif
1011         if (!release) {
1012             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1013             gint eraserMode = prefs->getBool("/tools/eraser/mode") ? 1 : 0;
1014             g_assert(!dc->currentcurve->is_empty());
1016             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(desktop),
1017                                                    SP_TYPE_CANVAS_BPATH,
1018                                                    NULL);
1019             SPCurve *curve = dc->currentcurve->copy();
1020             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1021             curve->unref();
1023             guint32 fillColor = sp_desktop_get_color_tool (desktop, "/tools/eraser", true);
1024             //guint32 strokeColor = sp_desktop_get_color_tool (desktop, "/tools/eraser", false);
1025             double opacity = sp_desktop_get_master_opacity_tool (desktop, "/tools/eraser");
1026             double fillOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/eraser", true);
1027             //double strokeOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/eraser", false);
1028             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1029             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1030             //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);
1031             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1032             /* fixme: Cannot we cascade it to root more clearly? */
1033             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), desktop);
1035             dc->segments = g_slist_prepend(dc->segments, cbp);
1037             if ( !eraserMode ) {
1038                 sp_canvas_item_hide(cbp);
1039                 sp_canvas_item_hide(dc->currentshape);
1040             }
1041         }
1043         dc->point1[0] = dc->point1[dc->npoints - 1];
1044         dc->point2[0] = dc->point2[dc->npoints - 1];
1045         dc->npoints = 1;
1046     } else {
1047         draw_temporary_box(dc);
1048     }
1051 static void
1052 draw_temporary_box(SPEraserContext *dc)
1054     dc->currentcurve->reset();
1056     dc->currentcurve->moveto(dc->point1[dc->npoints-1]);
1057     for (gint i = dc->npoints-2; i >= 0; i--) {
1058         dc->currentcurve->lineto(dc->point1[i]);
1059     }
1060     for (gint i = 0; i < dc->npoints; i++) {
1061         dc->currentcurve->lineto(dc->point2[i]);
1062     }
1063     if (dc->npoints >= 2) {
1064         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);
1065     }
1067     dc->currentcurve->closepath();
1068     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1071 /*
1072   Local Variables:
1073   mode:c++
1074   c-file-style:"stroustrup"
1075   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1076   indent-tabs-mode:nil
1077   fill-column:99
1078   End:
1079 */
1080 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :