Code

remove many unnecessary to_2geom and from_2geom calls
[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 "svg/svg.h"
67 #include "color.h"
69 #include "trace/trace.h"
70 #include "trace/imagemap.h"
71 #include "trace/potrace/inkscape-potrace.h"
73 static void sp_flood_context_class_init(SPFloodContextClass *klass);
74 static void sp_flood_context_init(SPFloodContext *flood_context);
75 static void sp_flood_context_dispose(GObject *object);
77 static void sp_flood_context_setup(SPEventContext *ec);
79 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event);
80 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event);
82 static void sp_flood_finish(SPFloodContext *rc);
84 static SPEventContextClass *parent_class;
87 GtkType sp_flood_context_get_type()
88 {
89     static GType type = 0;
90     if (!type) {
91         GTypeInfo info = {
92             sizeof(SPFloodContextClass),
93             NULL, NULL,
94             (GClassInitFunc) sp_flood_context_class_init,
95             NULL, NULL,
96             sizeof(SPFloodContext),
97             4,
98             (GInstanceInitFunc) sp_flood_context_init,
99             NULL,    /* value_table */
100         };
101         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPFloodContext", &info, (GTypeFlags) 0);
102     }
103     return type;
106 static void sp_flood_context_class_init(SPFloodContextClass *klass)
108     GObjectClass *object_class = (GObjectClass *) klass;
109     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
111     parent_class = (SPEventContextClass *) g_type_class_peek_parent(klass);
113     object_class->dispose = sp_flood_context_dispose;
115     event_context_class->setup = sp_flood_context_setup;
116     event_context_class->root_handler  = sp_flood_context_root_handler;
117     event_context_class->item_handler  = sp_flood_context_item_handler;
120 static void sp_flood_context_init(SPFloodContext *flood_context)
122     SPEventContext *event_context = SP_EVENT_CONTEXT(flood_context);
124     event_context->cursor_shape = cursor_paintbucket_xpm;
125     event_context->hot_x = 11;
126     event_context->hot_y = 30;
127     event_context->xp = 0;
128     event_context->yp = 0;
129     event_context->tolerance = 4;
130     event_context->within_tolerance = false;
131     event_context->item_to_select = NULL;
133     event_context->shape_repr = NULL;
134     event_context->shape_knot_holder = NULL;
136     flood_context->item = NULL;
138     new (&flood_context->sel_changed_connection) sigc::connection();
141 static void sp_flood_context_dispose(GObject *object)
143     SPFloodContext *rc = SP_FLOOD_CONTEXT(object);
144     SPEventContext *ec = SP_EVENT_CONTEXT(object);
146     rc->sel_changed_connection.disconnect();
147     rc->sel_changed_connection.~connection();
149     /* fixme: This is necessary because we do not grab */
150     if (rc->item) {
151         sp_flood_finish(rc);
152     }
154     if (ec->shape_repr) { // remove old listener
155         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
156         Inkscape::GC::release(ec->shape_repr);
157         ec->shape_repr = 0;
158     }
160     if (rc->_message_context) {
161         delete rc->_message_context;
162     }
164     G_OBJECT_CLASS(parent_class)->dispose(object);
167 static Inkscape::XML::NodeEventVector ec_shape_repr_events = {
168     NULL, /* child_added */
169     NULL, /* child_removed */
170     ec_shape_event_attr_changed,
171     NULL, /* content_changed */
172     NULL  /* order_changed */
173 };
175 /**
176 \brief  Callback that processes the "changed" signal on the selection;
177 destroys old and creates new knotholder
178 */
179 void sp_flood_context_selection_changed(Inkscape::Selection *selection, gpointer data)
181     SPFloodContext *rc = SP_FLOOD_CONTEXT(data);
182     SPEventContext *ec = SP_EVENT_CONTEXT(rc);
184     if (ec->shape_repr) { // remove old listener
185         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
186         Inkscape::GC::release(ec->shape_repr);
187         ec->shape_repr = 0;
188     }
190     SPItem *item = selection->singleItem();
191     if (item) {
192         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
193         if (shape_repr) {
194             ec->shape_repr = shape_repr;
195             Inkscape::GC::anchor(shape_repr);
196             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
197         }
198     }
201 static void sp_flood_context_setup(SPEventContext *ec)
203     SPFloodContext *rc = SP_FLOOD_CONTEXT(ec);
205     if (((SPEventContextClass *) parent_class)->setup) {
206         ((SPEventContextClass *) parent_class)->setup(ec);
207     }
209     SPItem *item = sp_desktop_selection(ec->desktop)->singleItem();
210     if (item) {
211         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
212         if (shape_repr) {
213             ec->shape_repr = shape_repr;
214             Inkscape::GC::anchor(shape_repr);
215             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
216         }
217     }
219     rc->sel_changed_connection.disconnect();
220     rc->sel_changed_connection = sp_desktop_selection(ec->desktop)->connectChanged(
221         sigc::bind(sigc::ptr_fun(&sp_flood_context_selection_changed), (gpointer)rc)
222     );
224     rc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
226     if (prefs_get_int_attribute("tools.paintbucket", "selcue", 0) != 0) {
227         rc->enableSelectionCue();
228     }
231 /**
232  * \brief Merge a pixel with the background color.
233  * \param orig The pixel to merge with the background.
234  * \param bg The background color.
235  * \param base The pixel to merge the original and background into.
236  */
237 inline static void
238 merge_pixel_with_background (unsigned char *orig, unsigned char *bg,
239            unsigned char *base)
241     int precalc_bg_alpha = (255 * (255 - bg[3])) / 255;
242     
243     for (int i = 0; i < 3; i++) {
244         base[i] = precalc_bg_alpha + (bg[i] * bg[3]) / 255;
245         base[i] = (base[i] * (255 - orig[3])) / 255 + (orig[i] * orig[3]) / 255;
246     }
249 /**
250  * \brief Get the pointer to a pixel in a pixel buffer.
251  * \param px The pixel buffer.
252  * \param x The X coordinate.
253  * \param y The Y coordinate.
254  * \param width The width of the pixel buffer.
255  */
256 inline unsigned char * get_pixel(guchar *px, int x, int y, int width) {
257     return px + (x + y * width) * 4;
260 inline unsigned char * get_trace_pixel(guchar *trace_px, int x, int y, int width) {
261     return trace_px + (x + y * width);
264 /**
265  * \brief Generate the list of trace channel selection entries.
266  */
267 GList * flood_channels_dropdown_items_list() {
268     GList *glist = NULL;
270     glist = g_list_append (glist, _("Visible Colors"));
271     glist = g_list_append (glist, _("Red"));
272     glist = g_list_append (glist, _("Green"));
273     glist = g_list_append (glist, _("Blue"));
274     glist = g_list_append (glist, _("Hue"));
275     glist = g_list_append (glist, _("Saturation"));
276     glist = g_list_append (glist, _("Lightness"));
277     glist = g_list_append (glist, _("Alpha"));
279     return glist;
282 /**
283  * \brief Generate the list of autogap selection entries.
284  */
285 GList * flood_autogap_dropdown_items_list() {
286     GList *glist = NULL;
288     glist = g_list_append (glist, _("None"));
289     glist = g_list_append (glist, _("Small"));
290     glist = g_list_append (glist, _("Medium"));
291     glist = g_list_append (glist, _("Large"));
293     return glist;
296 /**
297  * \brief Compare a pixel in a pixel buffer with another pixel to determine if a point should be included in the fill operation.
298  * \param check The pixel in the pixel buffer to check.
299  * \param orig The original selected pixel to use as the fill target color.
300  * \param merged_orig_pixel The original pixel merged with the background.
301  * \param dtc The desktop background color.
302  * \param threshold The fill threshold.
303  * \param method The fill method to use as defined in PaintBucketChannels.
304  */
305 static bool compare_pixels(unsigned char *check, unsigned char *orig, unsigned char *merged_orig_pixel, unsigned char *dtc, int threshold, PaintBucketChannels method) {
306     int diff = 0;
307     float hsl_check[3], hsl_orig[3];
308     
309     if ((method == FLOOD_CHANNELS_H) ||
310         (method == FLOOD_CHANNELS_S) ||
311         (method == FLOOD_CHANNELS_L)) {
312         sp_color_rgb_to_hsl_floatv(hsl_check, check[0] / 255.0, check[1] / 255.0, check[2] / 255.0);
313         sp_color_rgb_to_hsl_floatv(hsl_orig, orig[0] / 255.0, orig[1] / 255.0, orig[2] / 255.0);
314     }
315     
316     switch (method) {
317         case FLOOD_CHANNELS_ALPHA:
318             return ((int)abs(check[3] - orig[3]) <= threshold);
319         case FLOOD_CHANNELS_R:
320             return ((int)abs(check[0] - orig[0]) <= threshold);
321         case FLOOD_CHANNELS_G:
322             return ((int)abs(check[1] - orig[1]) <= threshold);
323         case FLOOD_CHANNELS_B:
324             return ((int)abs(check[2] - orig[2]) <= threshold);
325         case FLOOD_CHANNELS_RGB:
326             unsigned char merged_check[3];
327             
328             merge_pixel_with_background(check, dtc, merged_check);
329             
330             for (int i = 0; i < 3; i++) {
331               diff += (int)abs(merged_check[i] - merged_orig_pixel[i]);
332             }
333             return ((diff / 3) <= ((threshold * 3) / 4));
334         
335         case FLOOD_CHANNELS_H:
336             return ((int)(fabs(hsl_check[0] - hsl_orig[0]) * 100.0) <= threshold);
337         case FLOOD_CHANNELS_S:
338             return ((int)(fabs(hsl_check[1] - hsl_orig[1]) * 100.0) <= threshold);
339         case FLOOD_CHANNELS_L:
340             return ((int)(fabs(hsl_check[2] - hsl_orig[2]) * 100.0) <= threshold);
341     }
342     
343     return false;
346 enum {
347   PIXEL_CHECKED = 1,
348   PIXEL_QUEUED  = 2,
349   PIXEL_PAINTABLE = 4,
350   PIXEL_NOT_PAINTABLE = 8,
351   PIXEL_COLORED = 16
352 };
354 static inline bool is_pixel_checked(unsigned char *t) { return (*t & PIXEL_CHECKED) == PIXEL_CHECKED; }
355 static inline bool is_pixel_queued(unsigned char *t) { return (*t & PIXEL_QUEUED) == PIXEL_QUEUED; }
356 static inline bool is_pixel_paintability_checked(unsigned char *t) {
357   return !((*t & PIXEL_PAINTABLE) == 0) && ((*t & PIXEL_NOT_PAINTABLE) == 0);
359 static inline bool is_pixel_paintable(unsigned char *t) { return (*t & PIXEL_PAINTABLE) == PIXEL_PAINTABLE; }
360 static inline bool is_pixel_colored(unsigned char *t) { return (*t & PIXEL_COLORED) == PIXEL_COLORED; }
362 static inline void mark_pixel_checked(unsigned char *t) { *t |= PIXEL_CHECKED; }
363 static inline void mark_pixel_unchecked(unsigned char *t) { *t ^= PIXEL_CHECKED; }
364 static inline void mark_pixel_queued(unsigned char *t) { *t |= PIXEL_QUEUED; }
365 static inline void mark_pixel_paintable(unsigned char *t) { *t |= PIXEL_PAINTABLE; *t ^= PIXEL_NOT_PAINTABLE; }
366 static inline void mark_pixel_not_paintable(unsigned char *t) { *t |= PIXEL_NOT_PAINTABLE; *t ^= PIXEL_PAINTABLE; }
367 static inline void mark_pixel_colored(unsigned char *t) { *t |= PIXEL_COLORED; }
369 static inline void clear_pixel_paintability(unsigned char *t) { *t ^= PIXEL_PAINTABLE; *t ^= PIXEL_NOT_PAINTABLE; }
371 struct bitmap_coords_info {
372     bool is_left;
373     unsigned int x;
374     unsigned int y;
375     int y_limit;
376     unsigned int width;
377     unsigned int height;
378     unsigned int threshold;
379     unsigned int radius;
380     PaintBucketChannels method;
381     unsigned char *dtc;
382     unsigned char *merged_orig_pixel;
383     NR::Rect bbox;
384     NR::Rect screen;
385     unsigned int max_queue_size;
386     unsigned int current_step;
387 };
389 /**
390  * \brief Check if a pixel can be included in the fill.
391  * \param px The rendered pixel buffer to check.
392  * \param trace_t The pixel in the trace pixel buffer to check or mark.
393  * \param x The X coordinate.
394  * \param y The y coordinate.
395  * \param orig_color The original selected pixel to use as the fill target color.
396  * \param bci The bitmap_coords_info structure.
397  */
398 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) {
399     if (is_pixel_paintability_checked(trace_t)) {
400         return is_pixel_paintable(trace_t);
401     } else {
402         unsigned char *t = get_pixel(px, x, y, bci.width);
403         if (compare_pixels(t, orig_color, bci.merged_orig_pixel, bci.dtc, bci.threshold, bci.method)) {
404             mark_pixel_paintable(trace_t);
405             return true;
406         } else {
407             mark_pixel_not_paintable(trace_t);
408             return false;
409         }
410     }
413 /**
414  * \brief Perform the bitmap-to-vector tracing and place the traced path onto the document.
415  * \param px The trace pixel buffer to trace to SVG.
416  * \param desktop The desktop on which to place the final SVG path.
417  * \param transform The transform to apply to the final SVG path.
418  * \param union_with_selection If true, merge the final SVG path with the current selection.
419  */
420 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) {
421     SPDocument *document = sp_desktop_document(desktop);
423     unsigned char *trace_t;
425     GrayMap *gray_map = GrayMapCreate((max_x - min_x + 1), (max_y - min_y + 1));
426     unsigned int gray_map_y = 0;
427     for (unsigned int y = min_y; y <= max_y; y++) {
428         unsigned long *gray_map_t = gray_map->rows[gray_map_y];
430         trace_t = get_trace_pixel(trace_px, min_x, y, bci.width);
431         for (unsigned int x = min_x; x <= max_x; x++) {
432             *gray_map_t = is_pixel_colored(trace_t) ? GRAYMAP_BLACK : GRAYMAP_WHITE;
433             gray_map_t++;
434             trace_t++;
435         }
436         gray_map_y++;
437     }
439     Inkscape::Trace::Potrace::PotraceTracingEngine pte;
440     std::vector<Inkscape::Trace::TracingEngineResult> results = pte.traceGrayMap(gray_map);
441     gray_map->destroy(gray_map);
443     Inkscape::XML::Node *layer_repr = SP_GROUP(desktop->currentLayer())->repr;
444     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
446     long totalNodeCount = 0L;
448     double offset = prefs_get_double_attribute("tools.paintbucket", "offset", 0.0);
450     for (unsigned int i=0 ; i<results.size() ; i++) {
451         Inkscape::Trace::TracingEngineResult result = results[i];
452         totalNodeCount += result.getNodeCount();
454         Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path");
455         /* Set style */
456         sp_desktop_apply_style_tool (desktop, pathRepr, "tools.paintbucket", false);
458         Geom::PathVector pathv = sp_svg_read_pathv(result.getPathData().c_str());
459         Path *path = new Path;
460         path->LoadPathVector(pathv);
462         if (offset != 0) {
463         
464             Shape *path_shape = new Shape();
465         
466             path->ConvertWithBackData(0.03);
467             path->Fill(path_shape, 0);
468             delete path;
469         
470             Shape *expanded_path_shape = new Shape();
471         
472             expanded_path_shape->ConvertToShape(path_shape, fill_nonZero);
473             path_shape->MakeOffset(expanded_path_shape, offset * desktop->current_zoom(), join_round, 4);
474             expanded_path_shape->ConvertToShape(path_shape, fill_positive);
476             Path *expanded_path = new Path();
477         
478             expanded_path->Reset();
479             expanded_path_shape->ConvertToForme(expanded_path);
480             expanded_path->ConvertEvenLines(1.0);
481             expanded_path->Simplify(1.0);
482         
483             delete path_shape;
484             delete expanded_path_shape;
485         
486             gchar *str = expanded_path->svg_dump_path();
487             if (str && *str) {
488                 pathRepr->setAttribute("d", str);
489                 g_free(str);
490             } else {
491                 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Too much inset</b>, the result is empty."));
492                 Inkscape::GC::release(pathRepr);
493                 g_free(str);
494                 return;
495             }
497             delete expanded_path;
499         } else {
500             gchar *str = path->svg_dump_path();
501             delete path;
502             pathRepr->setAttribute("d", str);
503             g_free(str);
504         }
506         layer_repr->addChild(pathRepr, NULL);
508         SPObject *reprobj = document->getObjectByRepr(pathRepr);
509         if (reprobj) {
510             sp_item_write_transform(SP_ITEM(reprobj), pathRepr, transform, NULL);
511             
512             // premultiply the item transform by the accumulated parent transform in the paste layer
513             NR::Matrix local (sp_item_i2doc_affine(SP_GROUP(desktop->currentLayer())));
514             if (!local.test_identity()) {
515                 gchar const *t_str = pathRepr->attribute("transform");
516                 NR::Matrix item_t (NR::identity());
517                 if (t_str)
518                     sp_svg_transform_read(t_str, &item_t);
519                 item_t *= local.inverse();
520                 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
521                 gchar *affinestr=sp_svg_transform_write(item_t);
522                 pathRepr->setAttribute("transform", affinestr);
523                 g_free(affinestr);
524             }
526             Inkscape::Selection *selection = sp_desktop_selection(desktop);
528             pathRepr->setPosition(-1);
530             if (union_with_selection) {
531                 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)));
532                 selection->add(reprobj);
533                 sp_selected_path_union_skip_undo();
534             } else {
535                 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)));
536                 selection->set(reprobj);
537             }
539         }
541         Inkscape::GC::release(pathRepr);
543     }
546 /**
547  * \brief The possible return states of perform_bitmap_scanline_check()
548  */
549 enum ScanlineCheckResult {
550     SCANLINE_CHECK_OK,
551     SCANLINE_CHECK_ABORTED,
552     SCANLINE_CHECK_BOUNDARY
553 };
555 /**
556  * \brief Determine if the provided coordinates are within the pixel buffer limits.
557  * \param x The X coordinate.
558  * \param y The Y coordinate.
559  * \param bci The bitmap_coords_info structure.
560  */
561 inline static bool coords_in_range(unsigned int x, unsigned int y, bitmap_coords_info bci) {
562     return (x < bci.width) &&
563            (y < bci.height);
566 #define PAINT_DIRECTION_LEFT 1
567 #define PAINT_DIRECTION_RIGHT 2
568 #define PAINT_DIRECTION_UP 4
569 #define PAINT_DIRECTION_DOWN 8
570 #define PAINT_DIRECTION_ALL 15
572 /**
573  * \brief Paint a pixel or a square (if autogap is enabled) on the trace pixel buffer
574  * \param px The rendered pixel buffer to check.
575  * \param trace_px The trace pixel buffer.
576  * \param orig_color The original selected pixel to use as the fill target color.
577  * \param bci The bitmap_coords_info structure.
578  * \param original_point_trace_t The original pixel in the trace pixel buffer to check.
579  */
580 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) {
581     if (bci.radius == 0) {
582         mark_pixel_colored(original_point_trace_t); 
583         return PAINT_DIRECTION_ALL;
584     } else {
585         unsigned char *trace_t;
586   
587         bool can_paint_up = true;
588         bool can_paint_down = true;
589         bool can_paint_left = true;
590         bool can_paint_right = true;
591       
592         for (unsigned int ty = bci.y - bci.radius; ty <= bci.y + bci.radius; ty++) {
593             for (unsigned int tx = bci.x - bci.radius; tx <= bci.x + bci.radius; tx++) {
594                 if (coords_in_range(tx, ty, bci)) {
595                     trace_t = get_trace_pixel(trace_px, tx, ty, bci.width);
596                     if (!is_pixel_colored(trace_t)) {
597                         if (check_if_pixel_is_paintable(px, trace_t, tx, ty, orig_color, bci)) {
598                             mark_pixel_colored(trace_t); 
599                         } else {
600                             if (tx < bci.x) { can_paint_left = false; }
601                             if (tx > bci.x) { can_paint_right = false; }
602                             if (ty < bci.y) { can_paint_up = false; }
603                             if (ty > bci.y) { can_paint_down = false; }
604                         }
605                     }
606                 }
607             }
608         }
609     
610         unsigned int paint_directions = 0;
611         if (can_paint_left) { paint_directions += PAINT_DIRECTION_LEFT; }
612         if (can_paint_right) { paint_directions += PAINT_DIRECTION_RIGHT; }
613         if (can_paint_up) { paint_directions += PAINT_DIRECTION_UP; }
614         if (can_paint_down) { paint_directions += PAINT_DIRECTION_DOWN; }
615         
616         return paint_directions;
617     }
620 /**
621  * \brief Push a point to be checked onto the bottom of the rendered pixel buffer check queue.
622  * \param fill_queue The fill queue to add the point to.
623  * \param max_queue_size The maximum size of the fill queue.
624  * \param trace_t The trace pixel buffer pixel.
625  * \param x The X coordinate.
626  * \param y The Y coordinate.
627  */
628 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) {
629     if (!is_pixel_queued(trace_t)) {
630         if ((fill_queue->size() < max_queue_size)) {
631             fill_queue->push_back(NR::Point(x, y));
632             mark_pixel_queued(trace_t);
633         }
634     }
637 /**
638  * \brief Shift a point to be checked onto the top of the rendered pixel buffer check queue.
639  * \param fill_queue The fill queue to add the point to.
640  * \param max_queue_size The maximum size of the fill queue.
641  * \param trace_t The trace pixel buffer pixel.
642  * \param x The X coordinate.
643  * \param y The Y coordinate.
644  */
645 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) {
646     if (!is_pixel_queued(trace_t)) {
647         if ((fill_queue->size() < max_queue_size)) {
648             fill_queue->push_front(NR::Point(x, y));
649             mark_pixel_queued(trace_t);
650         }
651     }
654 /**
655  * \brief Scan a row in the rendered pixel buffer and add points to the fill queue as necessary.
656  * \param fill_queue The fill queue to add the point to.
657  * \param px The rendered pixel buffer.
658  * \param trace_px The trace pixel buffer.
659  * \param orig_color The original selected pixel to use as the fill target color.
660  * \param bci The bitmap_coords_info structure.
661  */
662 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) {
663     bool aborted = false;
664     bool reached_screen_boundary = false;
665     bool ok;
667     bool keep_tracing;
668     bool initial_paint = true;
670     unsigned char *current_trace_t = get_trace_pixel(trace_px, bci.x, bci.y, bci.width);
671     unsigned int paint_directions;
673     bool currently_painting_top = false;
674     bool currently_painting_bottom = false;
676     unsigned int top_ty = bci.y - 1;
677     unsigned int bottom_ty = bci.y + 1;
679     bool can_paint_top = (top_ty > 0);
680     bool can_paint_bottom = (bottom_ty < bci.height);
682     NR::Point t = fill_queue->front();
684     do {
685         ok = false;
686         if (bci.is_left) {
687             keep_tracing = (bci.x != 0);
688         } else {
689             keep_tracing = (bci.x < bci.width);
690         }
692         *min_x = MIN(*min_x, bci.x);
693         *max_x = MAX(*max_x, bci.x);
695         if (keep_tracing) {
696             if (check_if_pixel_is_paintable(px, current_trace_t, bci.x, bci.y, orig_color, bci)) {
697                 paint_directions = paint_pixel(px, trace_px, orig_color, bci, current_trace_t);
698                 if (bci.radius == 0) {
699                     mark_pixel_checked(current_trace_t);
700                     if ((t[NR::X] == bci.x) && (t[NR::Y] == bci.y)) {
701                         fill_queue->pop_front(); t = fill_queue->front();
702                     }
703                 }
705                 if (can_paint_top) {
706                     if (paint_directions & PAINT_DIRECTION_UP) { 
707                         unsigned char *trace_t = current_trace_t - bci.width;
708                         if (!is_pixel_queued(trace_t)) {
709                             bool ok_to_paint = check_if_pixel_is_paintable(px, trace_t, bci.x, top_ty, orig_color, bci);
711                             if (initial_paint) { currently_painting_top = !ok_to_paint; }
713                             if (ok_to_paint && (!currently_painting_top)) {
714                                 currently_painting_top = true;
715                                 push_point_onto_queue(fill_queue, bci.max_queue_size, trace_t, bci.x, top_ty);
716                             }
717                             if ((!ok_to_paint) && currently_painting_top) {
718                                 currently_painting_top = false;
719                             }
720                         }
721                     }
722                 }
724                 if (can_paint_bottom) {
725                     if (paint_directions & PAINT_DIRECTION_DOWN) { 
726                         unsigned char *trace_t = current_trace_t + bci.width;
727                         if (!is_pixel_queued(trace_t)) {
728                             bool ok_to_paint = check_if_pixel_is_paintable(px, trace_t, bci.x, bottom_ty, orig_color, bci);
730                             if (initial_paint) { currently_painting_bottom = !ok_to_paint; }
732                             if (ok_to_paint && (!currently_painting_bottom)) {
733                                 currently_painting_bottom = true;
734                                 push_point_onto_queue(fill_queue, bci.max_queue_size, trace_t, bci.x, bottom_ty);
735                             }
736                             if ((!ok_to_paint) && currently_painting_bottom) {
737                                 currently_painting_bottom = false;
738                             }
739                         }
740                     }
741                 }
743                 if (bci.is_left) {
744                     if (paint_directions & PAINT_DIRECTION_LEFT) {
745                         bci.x--; current_trace_t--;
746                         ok = true;
747                     }
748                 } else {
749                     if (paint_directions & PAINT_DIRECTION_RIGHT) {
750                         bci.x++; current_trace_t++;
751                         ok = true;
752                     }
753                 }
755                 initial_paint = false;
756             }
757         } else {
758             if (bci.bbox.min()[NR::X] > bci.screen.min()[NR::X]) {
759                 aborted = true; break;
760             } else {
761                 reached_screen_boundary = true;
762             }
763         }
764     } while (ok);
766     if (aborted) { return SCANLINE_CHECK_ABORTED; }
767     if (reached_screen_boundary) { return SCANLINE_CHECK_BOUNDARY; }
768     return SCANLINE_CHECK_OK;
771 /**
772  * \brief Sort the rendered pixel buffer check queue vertically.
773  */
774 static bool sort_fill_queue_vertical(NR::Point a, NR::Point b) {
775     return a[NR::Y] > b[NR::Y];
778 /**
779  * \brief Sort the rendered pixel buffer check queue horizontally.
780  */
781 static bool sort_fill_queue_horizontal(NR::Point a, NR::Point b) {
782     return a[NR::X] > b[NR::X];
785 /**
786  * \brief Perform a flood fill operation.
787  * \param event_context The event context for this tool.
788  * \param event The details of this event.
789  * \param union_with_selection If true, union the new fill with the current selection.
790  * \param is_point_fill If false, use the Rubberband "touch selection" to get the initial points for the fill.
791  * \param is_touch_fill If true, use only the initial contact point in the Rubberband "touch selection" as the fill target color.
792  */
793 static void sp_flood_do_flood_fill(SPEventContext *event_context, GdkEvent *event, bool union_with_selection, bool is_point_fill, bool is_touch_fill) {
794     SPDesktop *desktop = event_context->desktop;
795     SPDocument *document = sp_desktop_document(desktop);
797     /* Create new arena */
798     NRArena *arena = NRArena::create();
799     unsigned dkey = sp_item_display_key_new(1);
801     sp_document_ensure_up_to_date (document);
802     
803     SPItem *document_root = SP_ITEM(SP_DOCUMENT_ROOT(document));
804     boost::optional<NR::Rect> bbox = document_root->getBounds(NR::identity());
806     if (!bbox) {
807         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
808         return;
809     }
810     
811     double zoom_scale = desktop->current_zoom();
812     
813     // Render 160% of the physical display to the render pixel buffer, so that available
814     // fill areas off the screen can be included in the fill.
815     double padding = 1.6;
817     NR::Rect screen = desktop->get_display_area();
819     unsigned int width = (int)ceil(screen.extent(NR::X) * zoom_scale * padding);
820     unsigned int height = (int)ceil(screen.extent(NR::Y) * zoom_scale * padding);
822     NR::Point origin(screen.min()[NR::X],
823                      sp_document_height(document) - screen.extent(NR::Y) - screen.min()[NR::Y]);
824                     
825     origin[NR::X] = origin[NR::X] + (screen.extent(NR::X) * ((1 - padding) / 2));
826     origin[NR::Y] = origin[NR::Y] + (screen.extent(NR::Y) * ((1 - padding) / 2));
827     
828     NR::scale scale(zoom_scale, zoom_scale);
829     NR::Matrix affine = scale * NR::translate(-origin * scale);
830     
831     /* Create ArenaItems and set transform */
832     NRArenaItem *root = sp_item_invoke_show(SP_ITEM(sp_document_root(document)), arena, dkey, SP_ITEM_SHOW_DISPLAY);
833     nr_arena_item_set_transform(NR_ARENA_ITEM(root), affine);
835     NRGC gc(NULL);
836     gc.transform.set_identity();
837     
838     NRRectL final_bbox;
839     final_bbox.x0 = 0;
840     final_bbox.y0 = 0; //row;
841     final_bbox.x1 = width;
842     final_bbox.y1 = height; //row + num_rows;
843     
844     nr_arena_item_invoke_update(root, &final_bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
846     guchar *px = g_new(guchar, 4 * width * height);
847     
848     NRPixBlock B;
849     nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
850                               final_bbox.x0, final_bbox.y0, final_bbox.x1, final_bbox.y1,
851                               px, 4 * width, FALSE, FALSE );
852     
853     SPNamedView *nv = sp_desktop_namedview(desktop);
854     unsigned long bgcolor = nv->pagecolor;
855     
856     unsigned char dtc[4];
857     dtc[0] = NR_RGBA32_R(bgcolor);
858     dtc[1] = NR_RGBA32_G(bgcolor);
859     dtc[2] = NR_RGBA32_B(bgcolor);
860     dtc[3] = NR_RGBA32_A(bgcolor);
861     
862     for (unsigned int fy = 0; fy < height; fy++) {
863         guchar *p = NR_PIXBLOCK_PX(&B) + fy * B.rs;
864         for (unsigned int fx = 0; fx < width; fx++) {
865             for (int i = 0; i < 4; i++) { 
866                 *p++ = dtc[i];
867             }
868         }
869     }
871     nr_arena_item_invoke_render(NULL, root, &final_bbox, &B, NR_ARENA_ITEM_RENDER_NO_CACHE );
872     nr_pixblock_release(&B);
873     
874     // Hide items
875     sp_item_invoke_hide(SP_ITEM(sp_document_root(document)), dkey);
876     
877     nr_arena_item_unref(root);
878     nr_object_unref((NRObject *) arena);
879     
880     guchar *trace_px = g_new(guchar, width * height);
881     memset(trace_px, 0x00, width * height);
882     
883     std::deque<NR::Point> fill_queue;
884     std::queue<NR::Point> color_queue;
885     
886     std::vector<NR::Point> fill_points;
887     
888     bool aborted = false;
889     int y_limit = height - 1;
891     PaintBucketChannels method = (PaintBucketChannels)prefs_get_int_attribute("tools.paintbucket", "channels", 0);
892     int threshold = prefs_get_int_attribute_limited("tools.paintbucket", "threshold", 1, 0, 100);
894     switch(method) {
895         case FLOOD_CHANNELS_ALPHA:
896         case FLOOD_CHANNELS_RGB:
897         case FLOOD_CHANNELS_R:
898         case FLOOD_CHANNELS_G:
899         case FLOOD_CHANNELS_B:
900             threshold = (255 * threshold) / 100;
901             break;
902         case FLOOD_CHANNELS_H:
903         case FLOOD_CHANNELS_S:
904         case FLOOD_CHANNELS_L:
905             break;
906     }
908     bitmap_coords_info bci;
909     
910     bci.y_limit = y_limit;
911     bci.width = width;
912     bci.height = height;
913     bci.threshold = threshold;
914     bci.method = method;
915     bci.bbox = *bbox;
916     bci.screen = screen;
917     bci.dtc = dtc;
918     bci.radius = prefs_get_int_attribute_limited("tools.paintbucket", "autogap", 0, 0, 3);
919     bci.max_queue_size = (width * height) / 4;
920     bci.current_step = 0;
922     if (is_point_fill) {
923         fill_points.push_back(NR::Point(event->button.x, event->button.y));
924     } else {
925         Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
926         fill_points = r->getPoints();
927     }
929     for (unsigned int i = 0; i < fill_points.size(); i++) {
930         NR::Point pw = NR::Point(fill_points[i][NR::X] / zoom_scale, sp_document_height(document) + (fill_points[i][NR::Y] / zoom_scale)) * affine;
932         pw[NR::X] = (int)MIN(width - 1, MAX(0, pw[NR::X]));
933         pw[NR::Y] = (int)MIN(height - 1, MAX(0, pw[NR::Y]));
935         if (is_touch_fill) {
936             if (i == 0) {
937                 color_queue.push(pw);
938             } else {
939                 unsigned char *trace_t = get_trace_pixel(trace_px, (int)pw[NR::X], (int)pw[NR::Y], width);
940                 push_point_onto_queue(&fill_queue, bci.max_queue_size, trace_t, (int)pw[NR::X], (int)pw[NR::Y]);
941             }
942         } else {
943             color_queue.push(pw);
944         }
945     }
947     bool reached_screen_boundary = false;
949     bool first_run = true;
951     unsigned long sort_size_threshold = 5;
953     unsigned int min_y = height;
954     unsigned int max_y = 0;
955     unsigned int min_x = width;
956     unsigned int max_x = 0;
958     while (!color_queue.empty() && !aborted) {
959         NR::Point color_point = color_queue.front();
960         color_queue.pop();
962         int cx = (int)color_point[NR::X];
963         int cy = (int)color_point[NR::Y];
965         unsigned char *orig_px = get_pixel(px, cx, cy, width);
966         unsigned char orig_color[4];
967         for (int i = 0; i < 4; i++) { orig_color[i] = orig_px[i]; }
969         unsigned char merged_orig[3];
971         merge_pixel_with_background(orig_color, dtc, merged_orig);
973         bci.merged_orig_pixel = merged_orig;
975         unsigned char *trace_t = get_trace_pixel(trace_px, cx, cy, width);
976         if (!is_pixel_checked(trace_t) && !is_pixel_colored(trace_t)) {
977             if (check_if_pixel_is_paintable(px, trace_px, cx, cy, orig_color, bci)) {
978                 shift_point_onto_queue(&fill_queue, bci.max_queue_size, trace_t, cx, cy);
980                 if (!first_run) {
981                     for (unsigned int y = 0; y < height; y++) {
982                         trace_t = get_trace_pixel(trace_px, 0, y, width);
983                         for (unsigned int x = 0; x < width; x++) {
984                             clear_pixel_paintability(trace_t);
985                             trace_t++;
986                         }
987                     }
988                 }
989                 first_run = false;
990             }
991         }
993         unsigned long old_fill_queue_size = fill_queue.size();
995         while (!fill_queue.empty() && !aborted) {
996             NR::Point cp = fill_queue.front();
998             if (bci.radius == 0) {
999                 unsigned long new_fill_queue_size = fill_queue.size();
1001                 /*
1002                  * To reduce the number of points in the fill queue, periodically
1003                  * resort all of the points in the queue so that scanline checks
1004                  * can complete more quickly.  A point cannot be checked twice
1005                  * in a normal scanline checks, so forcing scanline checks to start
1006                  * from one corner of the rendered area as often as possible
1007                  * will reduce the number of points that need to be checked and queued.
1008                  */
1009                 if (new_fill_queue_size > sort_size_threshold) {
1010                     if (new_fill_queue_size > old_fill_queue_size) {
1011                         std::sort(fill_queue.begin(), fill_queue.end(), sort_fill_queue_vertical);
1013                         std::deque<NR::Point>::iterator start_sort = fill_queue.begin();
1014                         std::deque<NR::Point>::iterator end_sort = fill_queue.begin();
1015                         unsigned int sort_y = (unsigned int)cp[NR::Y];
1016                         unsigned int current_y = sort_y;
1017                         
1018                         for (std::deque<NR::Point>::iterator i = fill_queue.begin(); i != fill_queue.end(); i++) {
1019                             NR::Point current = *i;
1020                             current_y = (unsigned int)current[NR::Y];
1021                             if (current_y != sort_y) {
1022                                 if (start_sort != end_sort) {
1023                                     std::sort(start_sort, end_sort, sort_fill_queue_horizontal);
1024                                 }
1025                                 sort_y = current_y;
1026                                 start_sort = i;
1027                             }
1028                             end_sort = i;
1029                         }
1030                         if (start_sort != end_sort) {
1031                             std::sort(start_sort, end_sort, sort_fill_queue_horizontal);
1032                         }
1033                         
1034                         cp = fill_queue.front();
1035                     }
1036                 }
1038                 old_fill_queue_size = new_fill_queue_size;
1039             }
1041             fill_queue.pop_front();
1043             int x = (int)cp[NR::X];
1044             int y = (int)cp[NR::Y];
1046             min_y = MIN((unsigned int)y, min_y);
1047             max_y = MAX((unsigned int)y, max_y);
1049             unsigned char *trace_t = get_trace_pixel(trace_px, x, y, width);
1050             if (!is_pixel_checked(trace_t)) {
1051                 mark_pixel_checked(trace_t);
1053                 if (y == 0) {
1054                     if (bbox->min()[NR::Y] > screen.min()[NR::Y]) {
1055                         aborted = true; break;
1056                     } else {
1057                         reached_screen_boundary = true;
1058                     }
1059                 }
1061                 if (y == y_limit) {
1062                     if (bbox->max()[NR::Y] < screen.max()[NR::Y]) {
1063                         aborted = true; break;
1064                     } else {
1065                         reached_screen_boundary = true;
1066                     }
1067                 }
1069                 bci.is_left = true;
1070                 bci.x = x;
1071                 bci.y = y;
1073                 ScanlineCheckResult result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci, &min_x, &max_x);
1075                 switch (result) {
1076                     case SCANLINE_CHECK_ABORTED:
1077                         aborted = true;
1078                         break;
1079                     case SCANLINE_CHECK_BOUNDARY:
1080                         reached_screen_boundary = true;
1081                         break;
1082                     default:
1083                         break;
1084                 }
1086                 if (bci.x < width) {
1087                     trace_t++;
1088                     if (!is_pixel_checked(trace_t) && !is_pixel_queued(trace_t)) {
1089                         mark_pixel_checked(trace_t);
1090                         bci.is_left = false;
1091                         bci.x = x + 1;
1093                         result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci, &min_x, &max_x);
1095                         switch (result) {
1096                             case SCANLINE_CHECK_ABORTED:
1097                                 aborted = true;
1098                                 break;
1099                             case SCANLINE_CHECK_BOUNDARY:
1100                                 reached_screen_boundary = true;
1101                                 break;
1102                             default:
1103                                 break;
1104                         }
1105                     }
1106                 }
1107             }
1109             bci.current_step++;
1111             if (bci.current_step > bci.max_queue_size) {
1112                 aborted = true;
1113             }
1114         }
1115     }
1116     
1117     g_free(px);
1118     
1119     if (aborted) {
1120         g_free(trace_px);
1121         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
1122         return;
1123     }
1124     
1125     if (reached_screen_boundary) {
1126         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.")); 
1127     }
1129     unsigned int trace_padding = bci.radius + 1;
1130     if (min_y > trace_padding) { min_y -= trace_padding; }
1131     if (max_y < (y_limit - trace_padding)) { max_y += trace_padding; }
1132     if (min_x > trace_padding) { min_x -= trace_padding; }
1133     if (max_x < (width - 1 - trace_padding)) { max_x += trace_padding; }
1135     NR::Point min_start = NR::Point(min_x, min_y);
1136     
1137     affine = scale * NR::translate(-origin * scale - min_start);
1138     NR::Matrix inverted_affine = NR::Matrix(affine).inverse();
1139     
1140     do_trace(bci, trace_px, desktop, inverted_affine, min_x, max_x, min_y, max_y, union_with_selection);
1142     g_free(trace_px);
1143     
1144     sp_document_done(document, SP_VERB_CONTEXT_PAINTBUCKET, _("Fill bounded area"));
1147 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
1149     gint ret = FALSE;
1151     SPDesktop *desktop = event_context->desktop;
1153     switch (event->type) {
1154     case GDK_BUTTON_PRESS:
1155         if ((event->button.state & GDK_CONTROL_MASK) && event->button.button == 1 && !event_context->space_panning) {
1156             NR::Point const button_w(event->button.x,
1157                                     event->button.y);
1158             
1159             SPItem *item = sp_event_context_find_item (desktop, button_w, TRUE, TRUE);
1160             
1161             Inkscape::XML::Node *pathRepr = SP_OBJECT_REPR(item);
1162             /* Set style */
1163             sp_desktop_apply_style_tool (desktop, pathRepr, "tools.paintbucket", false);
1164             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET, _("Set style on object"));
1165             ret = TRUE;
1166         }
1167         break;
1168     default:
1169         break;
1170     }
1172     if (((SPEventContextClass *) parent_class)->item_handler) {
1173         ret = ((SPEventContextClass *) parent_class)->item_handler(event_context, item, event);
1174     }
1176     return ret;
1179 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event)
1181     static bool dragging;
1182     
1183     gint ret = FALSE;
1184     SPDesktop *desktop = event_context->desktop;
1186     switch (event->type) {
1187     case GDK_BUTTON_PRESS:
1188         if (event->button.button == 1 && !event_context->space_panning) {
1189             if (!(event->button.state & GDK_CONTROL_MASK)) {
1190                 NR::Point const button_w(event->button.x,
1191                                         event->button.y);
1192     
1193                 if (Inkscape::have_viable_layer(desktop, event_context->defaultMessageContext())) {
1194                     // save drag origin
1195                     event_context->xp = (gint) button_w[NR::X];
1196                     event_context->yp = (gint) button_w[NR::Y];
1197                     event_context->within_tolerance = true;
1198                       
1199                     dragging = true;
1200                     
1201                     NR::Point const p(desktop->w2d(button_w));
1202                     Inkscape::Rubberband::get()->setMode(RUBBERBAND_MODE_TOUCHPATH);
1203                     Inkscape::Rubberband::get()->start(desktop, p);
1204                 }
1205             }
1206         }
1207     case GDK_MOTION_NOTIFY:
1208         if ( dragging
1209              && ( event->motion.state & GDK_BUTTON1_MASK ) && !event_context->space_panning)
1210         {
1211             if ( event_context->within_tolerance
1212                  && ( abs( (gint) event->motion.x - event_context->xp ) < event_context->tolerance )
1213                  && ( abs( (gint) event->motion.y - event_context->yp ) < event_context->tolerance ) ) {
1214                 break; // do not drag if we're within tolerance from origin
1215             }
1216             
1217             event_context->within_tolerance = false;
1218             
1219             NR::Point const motion_pt(event->motion.x, event->motion.y);
1220             NR::Point const p(desktop->w2d(motion_pt));
1221             if (Inkscape::Rubberband::get()->is_started()) {
1222                 Inkscape::Rubberband::get()->move(p);
1223                 event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Draw over</b> areas to add to fill, hold <b>Alt</b> for touch fill"));
1224                 gobble_motion_events(GDK_BUTTON1_MASK);
1225             }
1226         }
1227         break;
1229     case GDK_BUTTON_RELEASE:
1230         if (event->button.button == 1 && !event_context->space_panning) {
1231             Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
1232             if (r->is_started()) {
1233                 // set "busy" cursor
1234                 desktop->setWaitingCursor();
1236                 if (SP_IS_EVENT_CONTEXT(event_context)) { 
1237                     // Since setWaitingCursor runs main loop iterations, we may have already left this tool!
1238                     // So check if the tool is valid before doing anything
1239                     dragging = false;
1241                     bool is_point_fill = event_context->within_tolerance;
1242                     bool is_touch_fill = event->button.state & GDK_MOD1_MASK;
1243                     
1244                     sp_flood_do_flood_fill(event_context, event, event->button.state & GDK_SHIFT_MASK, is_point_fill, is_touch_fill);
1245                     
1246                     desktop->clearWaitingCursor();
1247                     // restore cursor when done; note that it may already be different if e.g. user 
1248                     // switched to another tool during interruptible tracing or drawing, in which case do nothing
1250                     ret = TRUE;
1251                 }
1253                 r->stop();
1255                 if (SP_IS_EVENT_CONTEXT(event_context)) {
1256                     event_context->defaultMessageContext()->clear();
1257                 }
1258             }
1259         }
1260         break;
1261     case GDK_KEY_PRESS:
1262         switch (get_group0_keyval (&event->key)) {
1263         case GDK_Up:
1264         case GDK_Down:
1265         case GDK_KP_Up:
1266         case GDK_KP_Down:
1267             // prevent the zoom field from activation
1268             if (!MOD__CTRL_ONLY)
1269                 ret = TRUE;
1270             break;
1271         default:
1272             break;
1273         }
1274         break;
1275     default:
1276         break;
1277     }
1279     if (!ret) {
1280         if (((SPEventContextClass *) parent_class)->root_handler) {
1281             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1282         }
1283     }
1285     return ret;
1289 static void sp_flood_finish(SPFloodContext *rc)
1291     rc->_message_context->clear();
1293     if ( rc->item != NULL ) {
1294         SPDesktop * desktop;
1296         desktop = SP_EVENT_CONTEXT_DESKTOP(rc);
1298         SP_OBJECT(rc->item)->updateRepr();
1300         sp_canvas_end_forced_full_redraws(desktop->canvas);
1302         sp_desktop_selection(desktop)->set(rc->item);
1303         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET,
1304                         _("Fill bounded area"));
1306         rc->item = NULL;
1307     }
1310 void flood_channels_set_channels( gint channels )
1312     prefs_set_int_attribute("tools.paintbucket", "channels", channels);
1315 /*
1316   Local Variables:
1317   mode:c++
1318   c-file-style:"stroustrup"
1319   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1320   indent-tabs-mode:nil
1321   fill-column:99
1322   End:
1323 */
1324 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :