Code

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