Code

From trunk
[inkscape.git] / src / flood-context.cpp
1 #define __SP_FLOOD_CONTEXT_C__
3 /** @file
4  * @brief Bucket fill drawing context, works by bitmap filling an area on a rendered version
5  * of the current display and then tracing the result using potrace.
6  */
7 /* Author:
8  *   Lauris Kaplinski <lauris@kaplinski.com>
9  *   bulia byak <buliabyak@users.sf.net>
10  *   John Bintz <jcoswell@coswellproductions.org>
11  *
12  * Copyright (C) 2006      Johan Engelen <johan@shouraizou.nl>
13  * Copyright (C) 2000-2005 authors
14  * Copyright (C) 2000-2001 Ximian, Inc.
15  *
16  * Released under GNU GPL, read the file 'COPYING' for more information
17  */
19 #ifdef HAVE_CONFIG_H
20 #include "config.h"
21 #endif
23 #include <gdk/gdkkeysyms.h>
24 #include <queue>
25 #include <deque>
27 #include "macros.h"
28 #include "display/sp-canvas.h"
29 #include "document.h"
30 #include "sp-namedview.h"
31 #include "sp-object.h"
32 #include "sp-rect.h"
33 #include "selection.h"
34 #include "desktop-handles.h"
35 #include "desktop.h"
36 #include "desktop-style.h"
37 #include "message-stack.h"
38 #include "message-context.h"
39 #include "pixmaps/cursor-paintbucket.xpm"
40 #include "flood-context.h"
41 #include "sp-metrics.h"
42 #include <glibmm/i18n.h>
43 #include "object-edit.h"
44 #include "xml/repr.h"
45 #include "xml/node-event-vector.h"
46 #include "preferences.h"
47 #include "context-fns.h"
48 #include "rubberband.h"
50 #include "display/nr-arena-item.h"
51 #include "display/nr-arena.h"
52 #include "display/nr-arena-image.h"
53 #include "display/canvas-arena.h"
54 #include "libnr/nr-pixops.h"
55 #include "libnr/nr-matrix-translate-ops.h"
56 #include "libnr/nr-scale-ops.h"
57 #include "libnr/nr-scale-translate-ops.h"
58 #include "libnr/nr-translate-matrix-ops.h"
59 #include "libnr/nr-translate-scale-ops.h"
60 #include "libnr/nr-matrix-ops.h"
61 #include <2geom/pathvector.h>
62 #include "sp-item.h"
63 #include "sp-root.h"
64 #include "sp-defs.h"
65 #include "sp-path.h"
66 #include "splivarot.h"
67 #include "livarot/Path.h"
68 #include "livarot/Shape.h"
69 #include "svg/svg.h"
70 #include "color.h"
72 #include "trace/trace.h"
73 #include "trace/imagemap.h"
74 #include "trace/potrace/inkscape-potrace.h"
76 static void sp_flood_context_class_init(SPFloodContextClass *klass);
77 static void sp_flood_context_init(SPFloodContext *flood_context);
78 static void sp_flood_context_dispose(GObject *object);
80 static void sp_flood_context_setup(SPEventContext *ec);
82 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event);
83 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event);
85 static void sp_flood_finish(SPFloodContext *rc);
87 static SPEventContextClass *parent_class;
90 GtkType sp_flood_context_get_type()
91 {
92     static GType type = 0;
93     if (!type) {
94         GTypeInfo info = {
95             sizeof(SPFloodContextClass),
96             NULL, NULL,
97             (GClassInitFunc) sp_flood_context_class_init,
98             NULL, NULL,
99             sizeof(SPFloodContext),
100             4,
101             (GInstanceInitFunc) sp_flood_context_init,
102             NULL,    /* value_table */
103         };
104         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPFloodContext", &info, (GTypeFlags) 0);
105     }
106     return type;
109 static void sp_flood_context_class_init(SPFloodContextClass *klass)
111     GObjectClass *object_class = (GObjectClass *) klass;
112     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
114     parent_class = (SPEventContextClass *) g_type_class_peek_parent(klass);
116     object_class->dispose = sp_flood_context_dispose;
118     event_context_class->setup = sp_flood_context_setup;
119     event_context_class->root_handler  = sp_flood_context_root_handler;
120     event_context_class->item_handler  = sp_flood_context_item_handler;
123 static void sp_flood_context_init(SPFloodContext *flood_context)
125     SPEventContext *event_context = SP_EVENT_CONTEXT(flood_context);
127     event_context->cursor_shape = cursor_paintbucket_xpm;
128     event_context->hot_x = 11;
129     event_context->hot_y = 30;
130     event_context->xp = 0;
131     event_context->yp = 0;
132     event_context->tolerance = 4;
133     event_context->within_tolerance = false;
134     event_context->item_to_select = NULL;
136     event_context->shape_repr = NULL;
137     event_context->shape_knot_holder = NULL;
139     flood_context->item = NULL;
141     new (&flood_context->sel_changed_connection) sigc::connection();
144 static void sp_flood_context_dispose(GObject *object)
146     SPFloodContext *rc = SP_FLOOD_CONTEXT(object);
147     SPEventContext *ec = SP_EVENT_CONTEXT(object);
149     rc->sel_changed_connection.disconnect();
150     rc->sel_changed_connection.~connection();
152     /* fixme: This is necessary because we do not grab */
153     if (rc->item) {
154         sp_flood_finish(rc);
155     }
157     if (ec->shape_repr) { // remove old listener
158         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
159         Inkscape::GC::release(ec->shape_repr);
160         ec->shape_repr = 0;
161     }
163     if (rc->_message_context) {
164         delete rc->_message_context;
165     }
167     G_OBJECT_CLASS(parent_class)->dispose(object);
170 static Inkscape::XML::NodeEventVector ec_shape_repr_events = {
171     NULL, /* child_added */
172     NULL, /* child_removed */
173     ec_shape_event_attr_changed,
174     NULL, /* content_changed */
175     NULL  /* order_changed */
176 };
178 /**
179 \brief  Callback that processes the "changed" signal on the selection;
180 destroys old and creates new knotholder
181 */
182 void sp_flood_context_selection_changed(Inkscape::Selection *selection, gpointer data)
184     SPFloodContext *rc = SP_FLOOD_CONTEXT(data);
185     SPEventContext *ec = SP_EVENT_CONTEXT(rc);
187     if (ec->shape_repr) { // remove old listener
188         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
189         Inkscape::GC::release(ec->shape_repr);
190         ec->shape_repr = 0;
191     }
193     SPItem *item = selection->singleItem();
194     if (item) {
195         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
196         if (shape_repr) {
197             ec->shape_repr = shape_repr;
198             Inkscape::GC::anchor(shape_repr);
199             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
200         }
201     }
204 static void sp_flood_context_setup(SPEventContext *ec)
206     SPFloodContext *rc = SP_FLOOD_CONTEXT(ec);
208     if (((SPEventContextClass *) parent_class)->setup) {
209         ((SPEventContextClass *) parent_class)->setup(ec);
210     }
212     SPItem *item = sp_desktop_selection(ec->desktop)->singleItem();
213     if (item) {
214         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
215         if (shape_repr) {
216             ec->shape_repr = shape_repr;
217             Inkscape::GC::anchor(shape_repr);
218             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
219         }
220     }
222     rc->sel_changed_connection.disconnect();
223     rc->sel_changed_connection = sp_desktop_selection(ec->desktop)->connectChanged(
224         sigc::bind(sigc::ptr_fun(&sp_flood_context_selection_changed), (gpointer)rc)
225     );
227     rc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
229     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
230     if (prefs->getBool("/tools/paintbucket/selcue")) {
231         rc->enableSelectionCue();
232     }
235 /**
236  * \brief Merge a pixel with the background color.
237  * \param orig The pixel to merge with the background.
238  * \param bg The background color.
239  * \param base The pixel to merge the original and background into.
240  */
241 inline static void
242 merge_pixel_with_background (unsigned char *orig, unsigned char *bg,
243            unsigned char *base)
245     int precalc_bg_alpha = (255 * (255 - bg[3])) / 255;
246     
247     for (int i = 0; i < 3; i++) {
248         base[i] = precalc_bg_alpha + (bg[i] * bg[3]) / 255;
249         base[i] = (base[i] * (255 - orig[3])) / 255 + (orig[i] * orig[3]) / 255;
250     }
253 /**
254  * \brief Get the pointer to a pixel in a pixel buffer.
255  * \param px The pixel buffer.
256  * \param x The X coordinate.
257  * \param y The Y coordinate.
258  * \param width The width of the pixel buffer.
259  */
260 inline unsigned char * get_pixel(guchar *px, int x, int y, int width) {
261     return px + (x + y * width) * 4;
264 inline unsigned char * get_trace_pixel(guchar *trace_px, int x, int y, int width) {
265     return trace_px + (x + y * width);
268 /**
269  * \brief Generate the list of trace channel selection entries.
270  */
271 GList * flood_channels_dropdown_items_list() {
272     GList *glist = NULL;
274     glist = g_list_append (glist, _("Visible Colors"));
275     glist = g_list_append (glist, _("Red"));
276     glist = g_list_append (glist, _("Green"));
277     glist = g_list_append (glist, _("Blue"));
278     glist = g_list_append (glist, _("Hue"));
279     glist = g_list_append (glist, _("Saturation"));
280     glist = g_list_append (glist, _("Lightness"));
281     glist = g_list_append (glist, _("Alpha"));
283     return glist;
286 /**
287  * \brief Generate the list of autogap selection entries.
288  */
289 GList * flood_autogap_dropdown_items_list() {
290     GList *glist = NULL;
292     glist = g_list_append (glist, _("None"));
293     glist = g_list_append (glist, _("Small"));
294     glist = g_list_append (glist, _("Medium"));
295     glist = g_list_append (glist, _("Large"));
297     return glist;
300 /**
301  * \brief Compare a pixel in a pixel buffer with another pixel to determine if a point should be included in the fill operation.
302  * \param check The pixel in the pixel buffer to check.
303  * \param orig The original selected pixel to use as the fill target color.
304  * \param merged_orig_pixel The original pixel merged with the background.
305  * \param dtc The desktop background color.
306  * \param threshold The fill threshold.
307  * \param method The fill method to use as defined in PaintBucketChannels.
308  */
309 static bool compare_pixels(unsigned char *check, unsigned char *orig, unsigned char *merged_orig_pixel, unsigned char *dtc, int threshold, PaintBucketChannels method) {
310     int diff = 0;
311     float hsl_check[3], hsl_orig[3];
312     
313     if ((method == FLOOD_CHANNELS_H) ||
314         (method == FLOOD_CHANNELS_S) ||
315         (method == FLOOD_CHANNELS_L)) {
316         sp_color_rgb_to_hsl_floatv(hsl_check, check[0] / 255.0, check[1] / 255.0, check[2] / 255.0);
317         sp_color_rgb_to_hsl_floatv(hsl_orig, orig[0] / 255.0, orig[1] / 255.0, orig[2] / 255.0);
318     }
319     
320     switch (method) {
321         case FLOOD_CHANNELS_ALPHA:
322             return ((int)abs(check[3] - orig[3]) <= threshold);
323         case FLOOD_CHANNELS_R:
324             return ((int)abs(check[0] - orig[0]) <= threshold);
325         case FLOOD_CHANNELS_G:
326             return ((int)abs(check[1] - orig[1]) <= threshold);
327         case FLOOD_CHANNELS_B:
328             return ((int)abs(check[2] - orig[2]) <= threshold);
329         case FLOOD_CHANNELS_RGB:
330             unsigned char merged_check[3];
331             
332             merge_pixel_with_background(check, dtc, merged_check);
333             
334             for (int i = 0; i < 3; i++) {
335               diff += (int)abs(merged_check[i] - merged_orig_pixel[i]);
336             }
337             return ((diff / 3) <= ((threshold * 3) / 4));
338         
339         case FLOOD_CHANNELS_H:
340             return ((int)(fabs(hsl_check[0] - hsl_orig[0]) * 100.0) <= threshold);
341         case FLOOD_CHANNELS_S:
342             return ((int)(fabs(hsl_check[1] - hsl_orig[1]) * 100.0) <= threshold);
343         case FLOOD_CHANNELS_L:
344             return ((int)(fabs(hsl_check[2] - hsl_orig[2]) * 100.0) <= threshold);
345     }
346     
347     return false;
350 enum {
351   PIXEL_CHECKED = 1,
352   PIXEL_QUEUED  = 2,
353   PIXEL_PAINTABLE = 4,
354   PIXEL_NOT_PAINTABLE = 8,
355   PIXEL_COLORED = 16
356 };
358 static inline bool is_pixel_checked(unsigned char *t) { return (*t & PIXEL_CHECKED) == PIXEL_CHECKED; }
359 static inline bool is_pixel_queued(unsigned char *t) { return (*t & PIXEL_QUEUED) == PIXEL_QUEUED; }
360 static inline bool is_pixel_paintability_checked(unsigned char *t) {
361   return !((*t & PIXEL_PAINTABLE) == 0) && ((*t & PIXEL_NOT_PAINTABLE) == 0);
363 static inline bool is_pixel_paintable(unsigned char *t) { return (*t & PIXEL_PAINTABLE) == PIXEL_PAINTABLE; }
364 static inline bool is_pixel_colored(unsigned char *t) { return (*t & PIXEL_COLORED) == PIXEL_COLORED; }
366 static inline void mark_pixel_checked(unsigned char *t) { *t |= PIXEL_CHECKED; }
367 static inline void mark_pixel_unchecked(unsigned char *t) { *t ^= PIXEL_CHECKED; }
368 static inline void mark_pixel_queued(unsigned char *t) { *t |= PIXEL_QUEUED; }
369 static inline void mark_pixel_paintable(unsigned char *t) { *t |= PIXEL_PAINTABLE; *t ^= PIXEL_NOT_PAINTABLE; }
370 static inline void mark_pixel_not_paintable(unsigned char *t) { *t |= PIXEL_NOT_PAINTABLE; *t ^= PIXEL_PAINTABLE; }
371 static inline void mark_pixel_colored(unsigned char *t) { *t |= PIXEL_COLORED; }
373 static inline void clear_pixel_paintability(unsigned char *t) { *t ^= PIXEL_PAINTABLE; *t ^= PIXEL_NOT_PAINTABLE; }
375 struct bitmap_coords_info {
376     bool is_left;
377     unsigned int x;
378     unsigned int y;
379     int y_limit;
380     unsigned int width;
381     unsigned int height;
382     unsigned int threshold;
383     unsigned int radius;
384     PaintBucketChannels method;
385     unsigned char *dtc;
386     unsigned char *merged_orig_pixel;
387     Geom::Rect bbox;
388     Geom::Rect screen;
389     unsigned int max_queue_size;
390     unsigned int current_step;
391 };
393 /**
394  * \brief Check if a pixel can be included in the fill.
395  * \param px The rendered pixel buffer to check.
396  * \param trace_t The pixel in the trace pixel buffer to check or mark.
397  * \param x The X coordinate.
398  * \param y The y coordinate.
399  * \param orig_color The original selected pixel to use as the fill target color.
400  * \param bci The bitmap_coords_info structure.
401  */
402 inline static bool check_if_pixel_is_paintable(guchar *px, unsigned char *trace_t, int x, int y, unsigned char *orig_color, bitmap_coords_info bci) {
403     if (is_pixel_paintability_checked(trace_t)) {
404         return is_pixel_paintable(trace_t);
405     } else {
406         unsigned char *t = get_pixel(px, x, y, bci.width);
407         if (compare_pixels(t, orig_color, bci.merged_orig_pixel, bci.dtc, bci.threshold, bci.method)) {
408             mark_pixel_paintable(trace_t);
409             return true;
410         } else {
411             mark_pixel_not_paintable(trace_t);
412             return false;
413         }
414     }
417 /**
418  * \brief Perform the bitmap-to-vector tracing and place the traced path onto the document.
419  * \param px The trace pixel buffer to trace to SVG.
420  * \param desktop The desktop on which to place the final SVG path.
421  * \param transform The transform to apply to the final SVG path.
422  * \param union_with_selection If true, merge the final SVG path with the current selection.
423  */
424 static void do_trace(bitmap_coords_info bci, guchar *trace_px, SPDesktop *desktop, Geom::Matrix transform, unsigned int min_x, unsigned int max_x, unsigned int min_y, unsigned int max_y, bool union_with_selection) {
425     SPDocument *document = sp_desktop_document(desktop);
427     unsigned char *trace_t;
429     GrayMap *gray_map = GrayMapCreate((max_x - min_x + 1), (max_y - min_y + 1));
430     unsigned int gray_map_y = 0;
431     for (unsigned int y = min_y; y <= max_y; y++) {
432         unsigned long *gray_map_t = gray_map->rows[gray_map_y];
434         trace_t = get_trace_pixel(trace_px, min_x, y, bci.width);
435         for (unsigned int x = min_x; x <= max_x; x++) {
436             *gray_map_t = is_pixel_colored(trace_t) ? GRAYMAP_BLACK : GRAYMAP_WHITE;
437             gray_map_t++;
438             trace_t++;
439         }
440         gray_map_y++;
441     }
443     Inkscape::Trace::Potrace::PotraceTracingEngine pte;
444     pte.keepGoing = 1;
445     std::vector<Inkscape::Trace::TracingEngineResult> results = pte.traceGrayMap(gray_map);
446     gray_map->destroy(gray_map);
448     Inkscape::XML::Node *layer_repr = SP_GROUP(desktop->currentLayer())->repr;
449     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
451     long totalNodeCount = 0L;
453     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
454     double offset = prefs->getDouble("/tools/paintbucket/offset", 0.0);
456     for (unsigned int i=0 ; i<results.size() ; i++) {
457         Inkscape::Trace::TracingEngineResult result = results[i];
458         totalNodeCount += result.getNodeCount();
460         Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path");
461         /* Set style */
462         sp_desktop_apply_style_tool (desktop, pathRepr, "/tools/paintbucket", false);
464         Geom::PathVector pathv = sp_svg_read_pathv(result.getPathData().c_str());
465         Path *path = new Path;
466         path->LoadPathVector(pathv);
468         if (offset != 0) {
469         
470             Shape *path_shape = new Shape();
471         
472             path->ConvertWithBackData(0.03);
473             path->Fill(path_shape, 0);
474             delete path;
475         
476             Shape *expanded_path_shape = new Shape();
477         
478             expanded_path_shape->ConvertToShape(path_shape, fill_nonZero);
479             path_shape->MakeOffset(expanded_path_shape, offset * desktop->current_zoom(), join_round, 4);
480             expanded_path_shape->ConvertToShape(path_shape, fill_positive);
482             Path *expanded_path = new Path();
483         
484             expanded_path->Reset();
485             expanded_path_shape->ConvertToForme(expanded_path);
486             expanded_path->ConvertEvenLines(1.0);
487             expanded_path->Simplify(1.0);
488         
489             delete path_shape;
490             delete expanded_path_shape;
491         
492             gchar *str = expanded_path->svg_dump_path();
493             if (str && *str) {
494                 pathRepr->setAttribute("d", str);
495                 g_free(str);
496             } else {
497                 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Too much inset</b>, the result is empty."));
498                 Inkscape::GC::release(pathRepr);
499                 g_free(str);
500                 return;
501             }
503             delete expanded_path;
505         } else {
506             gchar *str = path->svg_dump_path();
507             delete path;
508             pathRepr->setAttribute("d", str);
509             g_free(str);
510         }
512         layer_repr->addChild(pathRepr, NULL);
514         SPObject *reprobj = document->getObjectByRepr(pathRepr);
515         if (reprobj) {
516             sp_item_write_transform(SP_ITEM(reprobj), pathRepr, transform, NULL);
517             
518             // premultiply the item transform by the accumulated parent transform in the paste layer
519             Geom::Matrix local (sp_item_i2doc_affine(SP_GROUP(desktop->currentLayer())));
520             if (!local.isIdentity()) {
521                 gchar const *t_str = pathRepr->attribute("transform");
522                 Geom::Matrix item_t (Geom::identity());
523                 if (t_str)
524                     sp_svg_transform_read(t_str, &item_t);
525                 item_t *= local.inverse();
526                 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
527                 gchar *affinestr=sp_svg_transform_write(item_t);
528                 pathRepr->setAttribute("transform", affinestr);
529                 g_free(affinestr);
530             }
532             Inkscape::Selection *selection = sp_desktop_selection(desktop);
534             pathRepr->setPosition(-1);
536             if (union_with_selection) {
537                 desktop->messageStack()->flashF(Inkscape::WARNING_MESSAGE, ngettext("Area filled, path with <b>%d</b> node created and unioned with selection.","Area filled, path with <b>%d</b> nodes created and unioned with selection.",sp_nodes_in_path(SP_PATH(reprobj))), sp_nodes_in_path(SP_PATH(reprobj)));
538                 selection->add(reprobj);
539                 sp_selected_path_union_skip_undo(desktop);
540             } else {
541                 desktop->messageStack()->flashF(Inkscape::WARNING_MESSAGE, ngettext("Area filled, path with <b>%d</b> node created.","Area filled, path with <b>%d</b> nodes created.",sp_nodes_in_path(SP_PATH(reprobj))), sp_nodes_in_path(SP_PATH(reprobj)));
542                 selection->set(reprobj);
543             }
545         }
547         Inkscape::GC::release(pathRepr);
549     }
552 /**
553  * \brief The possible return states of perform_bitmap_scanline_check()
554  */
555 enum ScanlineCheckResult {
556     SCANLINE_CHECK_OK,
557     SCANLINE_CHECK_ABORTED,
558     SCANLINE_CHECK_BOUNDARY
559 };
561 /**
562  * \brief Determine if the provided coordinates are within the pixel buffer limits.
563  * \param x The X coordinate.
564  * \param y The Y coordinate.
565  * \param bci The bitmap_coords_info structure.
566  */
567 inline static bool coords_in_range(unsigned int x, unsigned int y, bitmap_coords_info bci) {
568     return (x < bci.width) &&
569            (y < bci.height);
572 #define PAINT_DIRECTION_LEFT 1
573 #define PAINT_DIRECTION_RIGHT 2
574 #define PAINT_DIRECTION_UP 4
575 #define PAINT_DIRECTION_DOWN 8
576 #define PAINT_DIRECTION_ALL 15
578 /**
579  * \brief Paint a pixel or a square (if autogap is enabled) on the trace pixel buffer
580  * \param px The rendered pixel buffer to check.
581  * \param trace_px The trace pixel buffer.
582  * \param orig_color The original selected pixel to use as the fill target color.
583  * \param bci The bitmap_coords_info structure.
584  * \param original_point_trace_t The original pixel in the trace pixel buffer to check.
585  */
586 inline static unsigned int paint_pixel(guchar *px, guchar *trace_px, unsigned char *orig_color, bitmap_coords_info bci, unsigned char *original_point_trace_t) {
587     if (bci.radius == 0) {
588         mark_pixel_colored(original_point_trace_t); 
589         return PAINT_DIRECTION_ALL;
590     } else {
591         unsigned char *trace_t;
592   
593         bool can_paint_up = true;
594         bool can_paint_down = true;
595         bool can_paint_left = true;
596         bool can_paint_right = true;
597       
598         for (unsigned int ty = bci.y - bci.radius; ty <= bci.y + bci.radius; ty++) {
599             for (unsigned int tx = bci.x - bci.radius; tx <= bci.x + bci.radius; tx++) {
600                 if (coords_in_range(tx, ty, bci)) {
601                     trace_t = get_trace_pixel(trace_px, tx, ty, bci.width);
602                     if (!is_pixel_colored(trace_t)) {
603                         if (check_if_pixel_is_paintable(px, trace_t, tx, ty, orig_color, bci)) {
604                             mark_pixel_colored(trace_t); 
605                         } else {
606                             if (tx < bci.x) { can_paint_left = false; }
607                             if (tx > bci.x) { can_paint_right = false; }
608                             if (ty < bci.y) { can_paint_up = false; }
609                             if (ty > bci.y) { can_paint_down = false; }
610                         }
611                     }
612                 }
613             }
614         }
615     
616         unsigned int paint_directions = 0;
617         if (can_paint_left) { paint_directions += PAINT_DIRECTION_LEFT; }
618         if (can_paint_right) { paint_directions += PAINT_DIRECTION_RIGHT; }
619         if (can_paint_up) { paint_directions += PAINT_DIRECTION_UP; }
620         if (can_paint_down) { paint_directions += PAINT_DIRECTION_DOWN; }
621         
622         return paint_directions;
623     }
626 /**
627  * \brief Push a point to be checked onto the bottom of the rendered pixel buffer check queue.
628  * \param fill_queue The fill queue to add the point to.
629  * \param max_queue_size The maximum size of the fill queue.
630  * \param trace_t The trace pixel buffer pixel.
631  * \param x The X coordinate.
632  * \param y The Y coordinate.
633  */
634 static void push_point_onto_queue(std::deque<Geom::Point> *fill_queue, unsigned int max_queue_size, unsigned char *trace_t, unsigned int x, unsigned int y) {
635     if (!is_pixel_queued(trace_t)) {
636         if ((fill_queue->size() < max_queue_size)) {
637             fill_queue->push_back(Geom::Point(x, y));
638             mark_pixel_queued(trace_t);
639         }
640     }
643 /**
644  * \brief Shift a point to be checked onto the top of the rendered pixel buffer check queue.
645  * \param fill_queue The fill queue to add the point to.
646  * \param max_queue_size The maximum size of the fill queue.
647  * \param trace_t The trace pixel buffer pixel.
648  * \param x The X coordinate.
649  * \param y The Y coordinate.
650  */
651 static void shift_point_onto_queue(std::deque<Geom::Point> *fill_queue, unsigned int max_queue_size, unsigned char *trace_t, unsigned int x, unsigned int y) {
652     if (!is_pixel_queued(trace_t)) {
653         if ((fill_queue->size() < max_queue_size)) {
654             fill_queue->push_front(Geom::Point(x, y));
655             mark_pixel_queued(trace_t);
656         }
657     }
660 /**
661  * \brief Scan a row in the rendered pixel buffer and add points to the fill queue as necessary.
662  * \param fill_queue The fill queue to add the point to.
663  * \param px The rendered pixel buffer.
664  * \param trace_px The trace pixel buffer.
665  * \param orig_color The original selected pixel to use as the fill target color.
666  * \param bci The bitmap_coords_info structure.
667  */
668 static ScanlineCheckResult perform_bitmap_scanline_check(std::deque<Geom::Point> *fill_queue, guchar *px, guchar *trace_px, unsigned char *orig_color, bitmap_coords_info bci, unsigned int *min_x, unsigned int *max_x) {
669     bool aborted = false;
670     bool reached_screen_boundary = false;
671     bool ok;
673     bool keep_tracing;
674     bool initial_paint = true;
676     unsigned char *current_trace_t = get_trace_pixel(trace_px, bci.x, bci.y, bci.width);
677     unsigned int paint_directions;
679     bool currently_painting_top = false;
680     bool currently_painting_bottom = false;
682     unsigned int top_ty = bci.y - 1;
683     unsigned int bottom_ty = bci.y + 1;
685     bool can_paint_top = (top_ty > 0);
686     bool can_paint_bottom = (bottom_ty < bci.height);
688     Geom::Point t = fill_queue->front();
690     do {
691         ok = false;
692         if (bci.is_left) {
693             keep_tracing = (bci.x != 0);
694         } else {
695             keep_tracing = (bci.x < bci.width);
696         }
698         *min_x = MIN(*min_x, bci.x);
699         *max_x = MAX(*max_x, bci.x);
701         if (keep_tracing) {
702             if (check_if_pixel_is_paintable(px, current_trace_t, bci.x, bci.y, orig_color, bci)) {
703                 paint_directions = paint_pixel(px, trace_px, orig_color, bci, current_trace_t);
704                 if (bci.radius == 0) {
705                     mark_pixel_checked(current_trace_t);
706                     if ((t[Geom::X] == bci.x) && (t[Geom::Y] == bci.y)) {
707                         fill_queue->pop_front(); t = fill_queue->front();
708                     }
709                 }
711                 if (can_paint_top) {
712                     if (paint_directions & PAINT_DIRECTION_UP) { 
713                         unsigned char *trace_t = current_trace_t - bci.width;
714                         if (!is_pixel_queued(trace_t)) {
715                             bool ok_to_paint = check_if_pixel_is_paintable(px, trace_t, bci.x, top_ty, orig_color, bci);
717                             if (initial_paint) { currently_painting_top = !ok_to_paint; }
719                             if (ok_to_paint && (!currently_painting_top)) {
720                                 currently_painting_top = true;
721                                 push_point_onto_queue(fill_queue, bci.max_queue_size, trace_t, bci.x, top_ty);
722                             }
723                             if ((!ok_to_paint) && currently_painting_top) {
724                                 currently_painting_top = false;
725                             }
726                         }
727                     }
728                 }
730                 if (can_paint_bottom) {
731                     if (paint_directions & PAINT_DIRECTION_DOWN) { 
732                         unsigned char *trace_t = current_trace_t + bci.width;
733                         if (!is_pixel_queued(trace_t)) {
734                             bool ok_to_paint = check_if_pixel_is_paintable(px, trace_t, bci.x, bottom_ty, orig_color, bci);
736                             if (initial_paint) { currently_painting_bottom = !ok_to_paint; }
738                             if (ok_to_paint && (!currently_painting_bottom)) {
739                                 currently_painting_bottom = true;
740                                 push_point_onto_queue(fill_queue, bci.max_queue_size, trace_t, bci.x, bottom_ty);
741                             }
742                             if ((!ok_to_paint) && currently_painting_bottom) {
743                                 currently_painting_bottom = false;
744                             }
745                         }
746                     }
747                 }
749                 if (bci.is_left) {
750                     if (paint_directions & PAINT_DIRECTION_LEFT) {
751                         bci.x--; current_trace_t--;
752                         ok = true;
753                     }
754                 } else {
755                     if (paint_directions & PAINT_DIRECTION_RIGHT) {
756                         bci.x++; current_trace_t++;
757                         ok = true;
758                     }
759                 }
761                 initial_paint = false;
762             }
763         } else {
764             if (bci.bbox.min()[Geom::X] > bci.screen.min()[Geom::X]) {
765                 aborted = true; break;
766             } else {
767                 reached_screen_boundary = true;
768             }
769         }
770     } while (ok);
772     if (aborted) { return SCANLINE_CHECK_ABORTED; }
773     if (reached_screen_boundary) { return SCANLINE_CHECK_BOUNDARY; }
774     return SCANLINE_CHECK_OK;
777 /**
778  * \brief Sort the rendered pixel buffer check queue vertically.
779  */
780 static bool sort_fill_queue_vertical(Geom::Point a, Geom::Point b) {
781     return a[Geom::Y] > b[Geom::Y];
784 /**
785  * \brief Sort the rendered pixel buffer check queue horizontally.
786  */
787 static bool sort_fill_queue_horizontal(Geom::Point a, Geom::Point b) {
788     return a[Geom::X] > b[Geom::X];
791 /**
792  * \brief Perform a flood fill operation.
793  * \param event_context The event context for this tool.
794  * \param event The details of this event.
795  * \param union_with_selection If true, union the new fill with the current selection.
796  * \param is_point_fill If false, use the Rubberband "touch selection" to get the initial points for the fill.
797  * \param is_touch_fill If true, use only the initial contact point in the Rubberband "touch selection" as the fill target color.
798  */
799 static void sp_flood_do_flood_fill(SPEventContext *event_context, GdkEvent *event, bool union_with_selection, bool is_point_fill, bool is_touch_fill) {
800     SPDesktop *desktop = event_context->desktop;
801     SPDocument *document = sp_desktop_document(desktop);
803     /* Create new arena */
804     NRArena *arena = NRArena::create();
805     unsigned dkey = sp_item_display_key_new(1);
807     sp_document_ensure_up_to_date (document);
808     
809     SPItem *document_root = SP_ITEM(SP_DOCUMENT_ROOT(document));
810     boost::optional<Geom::Rect> bbox = document_root->getBounds(Geom::identity());
812     if (!bbox) {
813         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
814         return;
815     }
816     
817     double zoom_scale = desktop->current_zoom();
818     
819     // Render 160% of the physical display to the render pixel buffer, so that available
820     // fill areas off the screen can be included in the fill.
821     double padding = 1.6;
823     Geom::Rect screen = desktop->get_display_area();
825     unsigned int width = (int)ceil(screen.width() * zoom_scale * padding);
826     unsigned int height = (int)ceil(screen.height() * zoom_scale * padding);
828     Geom::Point origin(screen.min()[Geom::X],
829                        sp_document_height(document) - screen.height() - screen.min()[Geom::Y]);
830                     
831     origin[Geom::X] = origin[Geom::X] + (screen.width() * ((1 - padding) / 2));
832     origin[Geom::Y] = origin[Geom::Y] + (screen.height() * ((1 - padding) / 2));
833     
834     Geom::Scale scale(zoom_scale, zoom_scale);
835     Geom::Matrix affine = scale * Geom::Translate(-origin * scale);
836     
837     /* Create ArenaItems and set transform */
838     NRArenaItem *root = sp_item_invoke_show(SP_ITEM(sp_document_root(document)), arena, dkey, SP_ITEM_SHOW_DISPLAY);
839     nr_arena_item_set_transform(NR_ARENA_ITEM(root), affine);
841     NRGC gc(NULL);
842     gc.transform.setIdentity();
843     
844     NRRectL final_bbox;
845     final_bbox.x0 = 0;
846     final_bbox.y0 = 0; //row;
847     final_bbox.x1 = width;
848     final_bbox.y1 = height; //row + num_rows;
849     
850     nr_arena_item_invoke_update(root, &final_bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
852     guchar *px = g_new(guchar, 4 * width * height);
853     
854     NRPixBlock B;
855     nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
856                               final_bbox.x0, final_bbox.y0, final_bbox.x1, final_bbox.y1,
857                               px, 4 * width, FALSE, FALSE );
858     
859     SPNamedView *nv = sp_desktop_namedview(desktop);
860     unsigned long bgcolor = nv->pagecolor;
861     
862     unsigned char dtc[4];
863     dtc[0] = NR_RGBA32_R(bgcolor);
864     dtc[1] = NR_RGBA32_G(bgcolor);
865     dtc[2] = NR_RGBA32_B(bgcolor);
866     dtc[3] = NR_RGBA32_A(bgcolor);
867     
868     for (unsigned int fy = 0; fy < height; fy++) {
869         guchar *p = NR_PIXBLOCK_PX(&B) + fy * B.rs;
870         for (unsigned int fx = 0; fx < width; fx++) {
871             for (int i = 0; i < 4; i++) { 
872                 *p++ = dtc[i];
873             }
874         }
875     }
877     nr_arena_item_invoke_render(NULL, root, &final_bbox, &B, NR_ARENA_ITEM_RENDER_NO_CACHE );
878     nr_pixblock_release(&B);
879     
880     // Hide items
881     sp_item_invoke_hide(SP_ITEM(sp_document_root(document)), dkey);
882     
883     nr_object_unref((NRObject *) arena);
884     
885     guchar *trace_px = g_new(guchar, width * height);
886     memset(trace_px, 0x00, width * height);
887     
888     std::deque<Geom::Point> fill_queue;
889     std::queue<Geom::Point> color_queue;
890     
891     std::vector<Geom::Point> fill_points;
892     
893     bool aborted = false;
894     int y_limit = height - 1;
896     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
897     PaintBucketChannels method = (PaintBucketChannels) prefs->getInt("/tools/paintbucket/channels", 0);
898     int threshold = prefs->getIntLimited("/tools/paintbucket/threshold", 1, 0, 100);
900     switch(method) {
901         case FLOOD_CHANNELS_ALPHA:
902         case FLOOD_CHANNELS_RGB:
903         case FLOOD_CHANNELS_R:
904         case FLOOD_CHANNELS_G:
905         case FLOOD_CHANNELS_B:
906             threshold = (255 * threshold) / 100;
907             break;
908         case FLOOD_CHANNELS_H:
909         case FLOOD_CHANNELS_S:
910         case FLOOD_CHANNELS_L:
911             break;
912     }
914     bitmap_coords_info bci;
915     
916     bci.y_limit = y_limit;
917     bci.width = width;
918     bci.height = height;
919     bci.threshold = threshold;
920     bci.method = method;
921     bci.bbox = *bbox;
922     bci.screen = screen;
923     bci.dtc = dtc;
924     bci.radius = prefs->getIntLimited("/tools/paintbucket/autogap", 0, 0, 3);
925     bci.max_queue_size = (width * height) / 4;
926     bci.current_step = 0;
928     if (is_point_fill) {
929         fill_points.push_back(Geom::Point(event->button.x, event->button.y));
930     } else {
931         Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get(desktop);
932         fill_points = r->getPoints();
933     }
935     for (unsigned int i = 0; i < fill_points.size(); i++) {
936         Geom::Point pw = Geom::Point(fill_points[i][Geom::X] / zoom_scale, sp_document_height(document) + (fill_points[i][Geom::Y] / zoom_scale)) * affine;
938         pw[Geom::X] = (int)MIN(width - 1, MAX(0, pw[Geom::X]));
939         pw[Geom::Y] = (int)MIN(height - 1, MAX(0, pw[Geom::Y]));
941         if (is_touch_fill) {
942             if (i == 0) {
943                 color_queue.push(pw);
944             } else {
945                 unsigned char *trace_t = get_trace_pixel(trace_px, (int)pw[Geom::X], (int)pw[Geom::Y], width);
946                 push_point_onto_queue(&fill_queue, bci.max_queue_size, trace_t, (int)pw[Geom::X], (int)pw[Geom::Y]);
947             }
948         } else {
949             color_queue.push(pw);
950         }
951     }
953     bool reached_screen_boundary = false;
955     bool first_run = true;
957     unsigned long sort_size_threshold = 5;
959     unsigned int min_y = height;
960     unsigned int max_y = 0;
961     unsigned int min_x = width;
962     unsigned int max_x = 0;
964     while (!color_queue.empty() && !aborted) {
965         Geom::Point color_point = color_queue.front();
966         color_queue.pop();
968         int cx = (int)color_point[Geom::X];
969         int cy = (int)color_point[Geom::Y];
971         unsigned char *orig_px = get_pixel(px, cx, cy, width);
972         unsigned char orig_color[4];
973         for (int i = 0; i < 4; i++) { orig_color[i] = orig_px[i]; }
975         unsigned char merged_orig[3];
977         merge_pixel_with_background(orig_color, dtc, merged_orig);
979         bci.merged_orig_pixel = merged_orig;
981         unsigned char *trace_t = get_trace_pixel(trace_px, cx, cy, width);
982         if (!is_pixel_checked(trace_t) && !is_pixel_colored(trace_t)) {
983             if (check_if_pixel_is_paintable(px, trace_px, cx, cy, orig_color, bci)) {
984                 shift_point_onto_queue(&fill_queue, bci.max_queue_size, trace_t, cx, cy);
986                 if (!first_run) {
987                     for (unsigned int y = 0; y < height; y++) {
988                         trace_t = get_trace_pixel(trace_px, 0, y, width);
989                         for (unsigned int x = 0; x < width; x++) {
990                             clear_pixel_paintability(trace_t);
991                             trace_t++;
992                         }
993                     }
994                 }
995                 first_run = false;
996             }
997         }
999         unsigned long old_fill_queue_size = fill_queue.size();
1001         while (!fill_queue.empty() && !aborted) {
1002             Geom::Point cp = fill_queue.front();
1004             if (bci.radius == 0) {
1005                 unsigned long new_fill_queue_size = fill_queue.size();
1007                 /*
1008                  * To reduce the number of points in the fill queue, periodically
1009                  * resort all of the points in the queue so that scanline checks
1010                  * can complete more quickly.  A point cannot be checked twice
1011                  * in a normal scanline checks, so forcing scanline checks to start
1012                  * from one corner of the rendered area as often as possible
1013                  * will reduce the number of points that need to be checked and queued.
1014                  */
1015                 if (new_fill_queue_size > sort_size_threshold) {
1016                     if (new_fill_queue_size > old_fill_queue_size) {
1017                         std::sort(fill_queue.begin(), fill_queue.end(), sort_fill_queue_vertical);
1019                         std::deque<Geom::Point>::iterator start_sort = fill_queue.begin();
1020                         std::deque<Geom::Point>::iterator end_sort = fill_queue.begin();
1021                         unsigned int sort_y = (unsigned int)cp[Geom::Y];
1022                         unsigned int current_y = sort_y;
1023                         
1024                         for (std::deque<Geom::Point>::iterator i = fill_queue.begin(); i != fill_queue.end(); i++) {
1025                             Geom::Point current = *i;
1026                             current_y = (unsigned int)current[Geom::Y];
1027                             if (current_y != sort_y) {
1028                                 if (start_sort != end_sort) {
1029                                     std::sort(start_sort, end_sort, sort_fill_queue_horizontal);
1030                                 }
1031                                 sort_y = current_y;
1032                                 start_sort = i;
1033                             }
1034                             end_sort = i;
1035                         }
1036                         if (start_sort != end_sort) {
1037                             std::sort(start_sort, end_sort, sort_fill_queue_horizontal);
1038                         }
1039                         
1040                         cp = fill_queue.front();
1041                     }
1042                 }
1044                 old_fill_queue_size = new_fill_queue_size;
1045             }
1047             fill_queue.pop_front();
1049             int x = (int)cp[Geom::X];
1050             int y = (int)cp[Geom::Y];
1052             min_y = MIN((unsigned int)y, min_y);
1053             max_y = MAX((unsigned int)y, max_y);
1055             unsigned char *trace_t = get_trace_pixel(trace_px, x, y, width);
1056             if (!is_pixel_checked(trace_t)) {
1057                 mark_pixel_checked(trace_t);
1059                 if (y == 0) {
1060                     if (bbox->min()[Geom::Y] > screen.min()[Geom::Y]) {
1061                         aborted = true; break;
1062                     } else {
1063                         reached_screen_boundary = true;
1064                     }
1065                 }
1067                 if (y == y_limit) {
1068                     if (bbox->max()[Geom::Y] < screen.max()[Geom::Y]) {
1069                         aborted = true; break;
1070                     } else {
1071                         reached_screen_boundary = true;
1072                     }
1073                 }
1075                 bci.is_left = true;
1076                 bci.x = x;
1077                 bci.y = y;
1079                 ScanlineCheckResult result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci, &min_x, &max_x);
1081                 switch (result) {
1082                     case SCANLINE_CHECK_ABORTED:
1083                         aborted = true;
1084                         break;
1085                     case SCANLINE_CHECK_BOUNDARY:
1086                         reached_screen_boundary = true;
1087                         break;
1088                     default:
1089                         break;
1090                 }
1092                 if (bci.x < width) {
1093                     trace_t++;
1094                     if (!is_pixel_checked(trace_t) && !is_pixel_queued(trace_t)) {
1095                         mark_pixel_checked(trace_t);
1096                         bci.is_left = false;
1097                         bci.x = x + 1;
1099                         result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci, &min_x, &max_x);
1101                         switch (result) {
1102                             case SCANLINE_CHECK_ABORTED:
1103                                 aborted = true;
1104                                 break;
1105                             case SCANLINE_CHECK_BOUNDARY:
1106                                 reached_screen_boundary = true;
1107                                 break;
1108                             default:
1109                                 break;
1110                         }
1111                     }
1112                 }
1113             }
1115             bci.current_step++;
1117             if (bci.current_step > bci.max_queue_size) {
1118                 aborted = true;
1119             }
1120         }
1121     }
1122     
1123     g_free(px);
1124     
1125     if (aborted) {
1126         g_free(trace_px);
1127         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
1128         return;
1129     }
1130     
1131     if (reached_screen_boundary) {
1132         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Only the visible part of the bounded area was filled.</b> If you want to fill all of the area, undo, zoom out, and fill again.")); 
1133     }
1135     unsigned int trace_padding = bci.radius + 1;
1136     if (min_y > trace_padding) { min_y -= trace_padding; }
1137     if (max_y < (y_limit - trace_padding)) { max_y += trace_padding; }
1138     if (min_x > trace_padding) { min_x -= trace_padding; }
1139     if (max_x < (width - 1 - trace_padding)) { max_x += trace_padding; }
1141     Geom::Point min_start = Geom::Point(min_x, min_y);
1142     
1143     affine = scale * Geom::Translate(-origin * scale - min_start);
1144     Geom::Matrix inverted_affine = Geom::Matrix(affine).inverse();
1145     
1146     do_trace(bci, trace_px, desktop, inverted_affine, min_x, max_x, min_y, max_y, union_with_selection);
1148     g_free(trace_px);
1149     
1150     sp_document_done(document, SP_VERB_CONTEXT_PAINTBUCKET, _("Fill bounded area"));
1153 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
1155     gint ret = FALSE;
1157     SPDesktop *desktop = event_context->desktop;
1159     switch (event->type) {
1160     case GDK_BUTTON_PRESS:
1161         if ((event->button.state & GDK_CONTROL_MASK) && event->button.button == 1 && !event_context->space_panning) {
1162             Geom::Point const button_w(event->button.x,
1163                                        event->button.y);
1164             
1165             SPItem *item = sp_event_context_find_item (desktop, button_w, TRUE, TRUE);
1166             
1167             Inkscape::XML::Node *pathRepr = SP_OBJECT_REPR(item);
1168             /* Set style */
1169             sp_desktop_apply_style_tool (desktop, pathRepr, "/tools/paintbucket", false);
1170             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET, _("Set style on object"));
1171             ret = TRUE;
1172         }
1173         break;
1174     default:
1175         break;
1176     }
1178     if (((SPEventContextClass *) parent_class)->item_handler) {
1179         ret = ((SPEventContextClass *) parent_class)->item_handler(event_context, item, event);
1180     }
1182     return ret;
1185 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event)
1187     static bool dragging;
1188     
1189     gint ret = FALSE;
1190     SPDesktop *desktop = event_context->desktop;
1192     switch (event->type) {
1193     case GDK_BUTTON_PRESS:
1194         if (event->button.button == 1 && !event_context->space_panning) {
1195             if (!(event->button.state & GDK_CONTROL_MASK)) {
1196                 Geom::Point const button_w(event->button.x,
1197                                            event->button.y);
1198     
1199                 if (Inkscape::have_viable_layer(desktop, event_context->defaultMessageContext())) {
1200                     // save drag origin
1201                     event_context->xp = (gint) button_w[Geom::X];
1202                     event_context->yp = (gint) button_w[Geom::Y];
1203                     event_context->within_tolerance = true;
1204                       
1205                     dragging = true;
1206                     
1207                     Geom::Point const p(desktop->w2d(button_w));
1208                     Inkscape::Rubberband::get(desktop)->setMode(RUBBERBAND_MODE_TOUCHPATH);
1209                     Inkscape::Rubberband::get(desktop)->start(desktop, p);
1210                 }
1211             }
1212         }
1213     case GDK_MOTION_NOTIFY:
1214         if ( dragging
1215              && ( event->motion.state & GDK_BUTTON1_MASK ) && !event_context->space_panning)
1216         {
1217             if ( event_context->within_tolerance
1218                  && ( abs( (gint) event->motion.x - event_context->xp ) < event_context->tolerance )
1219                  && ( abs( (gint) event->motion.y - event_context->yp ) < event_context->tolerance ) ) {
1220                 break; // do not drag if we're within tolerance from origin
1221             }
1222             
1223             event_context->within_tolerance = false;
1224             
1225             Geom::Point const motion_pt(event->motion.x, event->motion.y);
1226             Geom::Point const p(desktop->w2d(motion_pt));
1227             if (Inkscape::Rubberband::get(desktop)->is_started()) {
1228                 Inkscape::Rubberband::get(desktop)->move(p);
1229                 event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Draw over</b> areas to add to fill, hold <b>Alt</b> for touch fill"));
1230                 gobble_motion_events(GDK_BUTTON1_MASK);
1231             }
1232         }
1233         break;
1235     case GDK_BUTTON_RELEASE:
1236         if (event->button.button == 1 && !event_context->space_panning) {
1237             Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get(desktop);
1238             if (r->is_started()) {
1239                 // set "busy" cursor
1240                 desktop->setWaitingCursor();
1242                 if (SP_IS_EVENT_CONTEXT(event_context)) { 
1243                     // Since setWaitingCursor runs main loop iterations, we may have already left this tool!
1244                     // So check if the tool is valid before doing anything
1245                     dragging = false;
1247                     bool is_point_fill = event_context->within_tolerance;
1248                     bool is_touch_fill = event->button.state & GDK_MOD1_MASK;
1249                     
1250                     sp_flood_do_flood_fill(event_context, event, event->button.state & GDK_SHIFT_MASK, is_point_fill, is_touch_fill);
1251                     
1252                     desktop->clearWaitingCursor();
1253                     // restore cursor when done; note that it may already be different if e.g. user 
1254                     // switched to another tool during interruptible tracing or drawing, in which case do nothing
1256                     ret = TRUE;
1257                 }
1259                 r->stop();
1261                 if (SP_IS_EVENT_CONTEXT(event_context)) {
1262                     event_context->defaultMessageContext()->clear();
1263                 }
1264             }
1265         }
1266         break;
1267     case GDK_KEY_PRESS:
1268         switch (get_group0_keyval (&event->key)) {
1269         case GDK_Up:
1270         case GDK_Down:
1271         case GDK_KP_Up:
1272         case GDK_KP_Down:
1273             // prevent the zoom field from activation
1274             if (!MOD__CTRL_ONLY)
1275                 ret = TRUE;
1276             break;
1277         default:
1278             break;
1279         }
1280         break;
1281     default:
1282         break;
1283     }
1285     if (!ret) {
1286         if (((SPEventContextClass *) parent_class)->root_handler) {
1287             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1288         }
1289     }
1291     return ret;
1295 static void sp_flood_finish(SPFloodContext *rc)
1297     rc->_message_context->clear();
1299     if ( rc->item != NULL ) {
1300         SPDesktop * desktop;
1302         desktop = SP_EVENT_CONTEXT_DESKTOP(rc);
1304         SP_OBJECT(rc->item)->updateRepr();
1306         sp_canvas_end_forced_full_redraws(desktop->canvas);
1308         sp_desktop_selection(desktop)->set(rc->item);
1309         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET,
1310                         _("Fill bounded area"));
1312         rc->item = NULL;
1313     }
1316 void flood_channels_set_channels( gint channels )
1318     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1319     prefs->setInt("/tools/paintbucket/channels", channels);
1322 /*
1323   Local Variables:
1324   mode:c++
1325   c-file-style:"stroustrup"
1326   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1327   indent-tabs-mode:nil
1328   fill-column:99
1329   End:
1330 */
1331 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :