Code

Merge and cleanup of GSoC C++-ification project.
[inkscape.git] / src / flood-context.cpp
1 /** @file
2  * @brief Bucket fill drawing context, works by bitmap filling an area on a rendered version
3  * of the current display and then tracing the result using potrace.
4  */
5 /* Author:
6  *   Lauris Kaplinski <lauris@kaplinski.com>
7  *   bulia byak <buliabyak@users.sf.net>
8  *   John Bintz <jcoswell@coswellproductions.org>
9  *   Jon A. Cruz <jon@joncruz.org>
10  *   Abhishek Sharma
11  *
12  * Copyright (C) 2006      Johan Engelen <johan@shouraizou.nl>
13  * Copyright (C) 2000-2005 authors
14  * Copyright (C) 2000-2001 Ximian, Inc.
15  *
16  * Released under GNU GPL, read the file 'COPYING' for more information
17  */
19 #ifdef HAVE_CONFIG_H
20 #include "config.h"
21 #endif
23 #include <gdk/gdkkeysyms.h>
24 #include <queue>
25 #include <deque>
27 #include "macros.h"
28 #include "display/sp-canvas.h"
29 #include "document.h"
30 #include "sp-namedview.h"
31 #include "sp-object.h"
32 #include "sp-rect.h"
33 #include "selection.h"
34 #include "desktop-handles.h"
35 #include "desktop.h"
36 #include "desktop-style.h"
37 #include "message-stack.h"
38 #include "message-context.h"
39 #include "pixmaps/cursor-paintbucket.xpm"
40 #include "flood-context.h"
41 #include "sp-metrics.h"
42 #include <glibmm/i18n.h>
43 #include "object-edit.h"
44 #include "xml/repr.h"
45 #include "xml/node-event-vector.h"
46 #include "preferences.h"
47 #include "context-fns.h"
48 #include "rubberband.h"
49 #include "shape-editor.h"
51 #include "display/nr-arena-item.h"
52 #include "display/nr-arena.h"
53 #include "display/nr-arena-image.h"
54 #include "display/canvas-arena.h"
55 #include "libnr/nr-pixops.h"
56 #include "libnr/nr-matrix-translate-ops.h"
57 #include "libnr/nr-scale-ops.h"
58 #include "libnr/nr-scale-translate-ops.h"
59 #include "libnr/nr-translate-matrix-ops.h"
60 #include "libnr/nr-translate-scale-ops.h"
61 #include "libnr/nr-matrix-ops.h"
62 #include <2geom/pathvector.h>
63 #include "sp-item.h"
64 #include "sp-root.h"
65 #include "sp-defs.h"
66 #include "sp-path.h"
67 #include "splivarot.h"
68 #include "livarot/Path.h"
69 #include "livarot/Shape.h"
70 #include "svg/svg.h"
71 #include "color.h"
73 #include "trace/trace.h"
74 #include "trace/imagemap.h"
75 #include "trace/potrace/inkscape-potrace.h"
77 using Inkscape::DocumentUndo;
79 static void sp_flood_context_class_init(SPFloodContextClass *klass);
80 static void sp_flood_context_init(SPFloodContext *flood_context);
81 static void sp_flood_context_dispose(GObject *object);
83 static void sp_flood_context_setup(SPEventContext *ec);
85 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event);
86 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event);
88 static void sp_flood_finish(SPFloodContext *rc);
90 static SPEventContextClass *parent_class;
93 GtkType sp_flood_context_get_type()
94 {
95     static GType type = 0;
96     if (!type) {
97         GTypeInfo info = {
98             sizeof(SPFloodContextClass),
99             NULL, NULL,
100             (GClassInitFunc) sp_flood_context_class_init,
101             NULL, NULL,
102             sizeof(SPFloodContext),
103             4,
104             (GInstanceInitFunc) sp_flood_context_init,
105             NULL,    /* value_table */
106         };
107         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPFloodContext", &info, (GTypeFlags) 0);
108     }
109     return type;
112 static void sp_flood_context_class_init(SPFloodContextClass *klass)
114     GObjectClass *object_class = (GObjectClass *) klass;
115     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
117     parent_class = (SPEventContextClass *) g_type_class_peek_parent(klass);
119     object_class->dispose = sp_flood_context_dispose;
121     event_context_class->setup = sp_flood_context_setup;
122     event_context_class->root_handler  = sp_flood_context_root_handler;
123     event_context_class->item_handler  = sp_flood_context_item_handler;
126 static void sp_flood_context_init(SPFloodContext *flood_context)
128     SPEventContext *event_context = SP_EVENT_CONTEXT(flood_context);
130     event_context->cursor_shape = cursor_paintbucket_xpm;
131     event_context->hot_x = 11;
132     event_context->hot_y = 30;
133     event_context->xp = 0;
134     event_context->yp = 0;
135     event_context->tolerance = 4;
136     event_context->within_tolerance = false;
137     event_context->item_to_select = NULL;
139     flood_context->item = NULL;
141     new (&flood_context->sel_changed_connection) sigc::connection();
144 static void sp_flood_context_dispose(GObject *object)
146     SPFloodContext *rc = SP_FLOOD_CONTEXT(object);
147     SPEventContext *ec = SP_EVENT_CONTEXT(object);
149     rc->sel_changed_connection.disconnect();
150     rc->sel_changed_connection.~connection();
152     delete ec->shape_editor;
153     ec->shape_editor = NULL;
155     /* fixme: This is necessary because we do not grab */
156     if (rc->item) {
157         sp_flood_finish(rc);
158     }
160     if (rc->_message_context) {
161         delete rc->_message_context;
162     }
164     G_OBJECT_CLASS(parent_class)->dispose(object);
167 /**
168 \brief  Callback that processes the "changed" signal on the selection;
169 destroys old and creates new knotholder
170 */
171 void sp_flood_context_selection_changed(Inkscape::Selection *selection, gpointer data)
173     SPFloodContext *rc = SP_FLOOD_CONTEXT(data);
174     SPEventContext *ec = SP_EVENT_CONTEXT(rc);
176     ec->shape_editor->unset_item(SH_KNOTHOLDER);
177     SPItem *item = selection->singleItem(); 
178     ec->shape_editor->set_item(item, SH_KNOTHOLDER);
181 static void sp_flood_context_setup(SPEventContext *ec)
183     SPFloodContext *rc = SP_FLOOD_CONTEXT(ec);
185     if (((SPEventContextClass *) parent_class)->setup) {
186         ((SPEventContextClass *) parent_class)->setup(ec);
187     }
189     ec->shape_editor = new ShapeEditor(ec->desktop);
191     SPItem *item = sp_desktop_selection(ec->desktop)->singleItem();
192     if (item) {
193         ec->shape_editor->set_item(item, SH_KNOTHOLDER);
194     }
196     rc->sel_changed_connection.disconnect();
197     rc->sel_changed_connection = sp_desktop_selection(ec->desktop)->connectChanged(
198         sigc::bind(sigc::ptr_fun(&sp_flood_context_selection_changed), (gpointer)rc)
199     );
201     rc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
203     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
204     if (prefs->getBool("/tools/paintbucket/selcue")) {
205         rc->enableSelectionCue();
206     }
209 /**
210  * \brief Merge a pixel with the background color.
211  * \param orig The pixel to merge with the background.
212  * \param bg The background color.
213  * \param base The pixel to merge the original and background into.
214  */
215 inline static void
216 merge_pixel_with_background (unsigned char *orig, unsigned char *bg,
217            unsigned char *base)
219     int precalc_bg_alpha = (255 * (255 - bg[3])) / 255;
220     
221     for (int i = 0; i < 3; i++) {
222         base[i] = precalc_bg_alpha + (bg[i] * bg[3]) / 255;
223         base[i] = (base[i] * (255 - orig[3])) / 255 + (orig[i] * orig[3]) / 255;
224     }
227 /**
228  * \brief Get the pointer to a pixel in a pixel buffer.
229  * \param px The pixel buffer.
230  * \param x The X coordinate.
231  * \param y The Y coordinate.
232  * \param width The width of the pixel buffer.
233  */
234 inline unsigned char * get_pixel(guchar *px, int x, int y, int width) {
235     return px + (x + y * width) * 4;
238 inline unsigned char * get_trace_pixel(guchar *trace_px, int x, int y, int width) {
239     return trace_px + (x + y * width);
242 /**
243  * \brief Generate the list of trace channel selection entries.
244  */
245 GList * flood_channels_dropdown_items_list() {
246     GList *glist = NULL;
248     glist = g_list_append (glist, _("Visible Colors"));
249     glist = g_list_append (glist, _("Red"));
250     glist = g_list_append (glist, _("Green"));
251     glist = g_list_append (glist, _("Blue"));
252     glist = g_list_append (glist, _("Hue"));
253     glist = g_list_append (glist, _("Saturation"));
254     glist = g_list_append (glist, _("Lightness"));
255     glist = g_list_append (glist, _("Alpha"));
257     return glist;
260 /**
261  * \brief Generate the list of autogap selection entries.
262  */
263 GList * flood_autogap_dropdown_items_list() {
264     GList *glist = NULL;
266     glist = g_list_append (glist, (void*) C_("Flood autogap", "None"));
267     glist = g_list_append (glist, (void*) C_("Flood autogap", "Small"));
268     glist = g_list_append (glist, (void*) C_("Flood autogap", "Medium"));
269     glist = g_list_append (glist, (void*) C_("Flood autogap", "Large"));
271     return glist;
274 /**
275  * \brief Compare a pixel in a pixel buffer with another pixel to determine if a point should be included in the fill operation.
276  * \param check The pixel in the pixel buffer to check.
277  * \param orig The original selected pixel to use as the fill target color.
278  * \param merged_orig_pixel The original pixel merged with the background.
279  * \param dtc The desktop background color.
280  * \param threshold The fill threshold.
281  * \param method The fill method to use as defined in PaintBucketChannels.
282  */
283 static bool compare_pixels(unsigned char *check, unsigned char *orig, unsigned char *merged_orig_pixel, unsigned char *dtc, int threshold, PaintBucketChannels method) {
284     int diff = 0;
285     float hsl_check[3], hsl_orig[3];
286     
287     if ((method == FLOOD_CHANNELS_H) ||
288         (method == FLOOD_CHANNELS_S) ||
289         (method == FLOOD_CHANNELS_L)) {
290         sp_color_rgb_to_hsl_floatv(hsl_check, check[0] / 255.0, check[1] / 255.0, check[2] / 255.0);
291         sp_color_rgb_to_hsl_floatv(hsl_orig, orig[0] / 255.0, orig[1] / 255.0, orig[2] / 255.0);
292     }
293     
294     switch (method) {
295         case FLOOD_CHANNELS_ALPHA:
296             return ((int)abs(check[3] - orig[3]) <= threshold);
297         case FLOOD_CHANNELS_R:
298             return ((int)abs(check[0] - orig[0]) <= threshold);
299         case FLOOD_CHANNELS_G:
300             return ((int)abs(check[1] - orig[1]) <= threshold);
301         case FLOOD_CHANNELS_B:
302             return ((int)abs(check[2] - orig[2]) <= threshold);
303         case FLOOD_CHANNELS_RGB:
304             unsigned char merged_check[3];
305             
306             merge_pixel_with_background(check, dtc, merged_check);
307             
308             for (int i = 0; i < 3; i++) {
309               diff += (int)abs(merged_check[i] - merged_orig_pixel[i]);
310             }
311             return ((diff / 3) <= ((threshold * 3) / 4));
312         
313         case FLOOD_CHANNELS_H:
314             return ((int)(fabs(hsl_check[0] - hsl_orig[0]) * 100.0) <= threshold);
315         case FLOOD_CHANNELS_S:
316             return ((int)(fabs(hsl_check[1] - hsl_orig[1]) * 100.0) <= threshold);
317         case FLOOD_CHANNELS_L:
318             return ((int)(fabs(hsl_check[2] - hsl_orig[2]) * 100.0) <= threshold);
319     }
320     
321     return false;
324 enum {
325   PIXEL_CHECKED = 1,
326   PIXEL_QUEUED  = 2,
327   PIXEL_PAINTABLE = 4,
328   PIXEL_NOT_PAINTABLE = 8,
329   PIXEL_COLORED = 16
330 };
332 static inline bool is_pixel_checked(unsigned char *t) { return (*t & PIXEL_CHECKED) == PIXEL_CHECKED; }
333 static inline bool is_pixel_queued(unsigned char *t) { return (*t & PIXEL_QUEUED) == PIXEL_QUEUED; }
334 static inline bool is_pixel_paintability_checked(unsigned char *t) {
335   return !((*t & PIXEL_PAINTABLE) == 0) && ((*t & PIXEL_NOT_PAINTABLE) == 0);
337 static inline bool is_pixel_paintable(unsigned char *t) { return (*t & PIXEL_PAINTABLE) == PIXEL_PAINTABLE; }
338 static inline bool is_pixel_colored(unsigned char *t) { return (*t & PIXEL_COLORED) == PIXEL_COLORED; }
340 static inline void mark_pixel_checked(unsigned char *t) { *t |= PIXEL_CHECKED; }
341 static inline void mark_pixel_unchecked(unsigned char *t) { *t ^= PIXEL_CHECKED; }
342 static inline void mark_pixel_queued(unsigned char *t) { *t |= PIXEL_QUEUED; }
343 static inline void mark_pixel_paintable(unsigned char *t) { *t |= PIXEL_PAINTABLE; *t ^= PIXEL_NOT_PAINTABLE; }
344 static inline void mark_pixel_not_paintable(unsigned char *t) { *t |= PIXEL_NOT_PAINTABLE; *t ^= PIXEL_PAINTABLE; }
345 static inline void mark_pixel_colored(unsigned char *t) { *t |= PIXEL_COLORED; }
347 static inline void clear_pixel_paintability(unsigned char *t) { *t ^= PIXEL_PAINTABLE; *t ^= PIXEL_NOT_PAINTABLE; }
349 struct bitmap_coords_info {
350     bool is_left;
351     unsigned int x;
352     unsigned int y;
353     int y_limit;
354     unsigned int width;
355     unsigned int height;
356     unsigned int threshold;
357     unsigned int radius;
358     PaintBucketChannels method;
359     unsigned char *dtc;
360     unsigned char *merged_orig_pixel;
361     Geom::Rect bbox;
362     Geom::Rect screen;
363     unsigned int max_queue_size;
364     unsigned int current_step;
365 };
367 /**
368  * \brief Check if a pixel can be included in the fill.
369  * \param px The rendered pixel buffer to check.
370  * \param trace_t The pixel in the trace pixel buffer to check or mark.
371  * \param x The X coordinate.
372  * \param y The y coordinate.
373  * \param orig_color The original selected pixel to use as the fill target color.
374  * \param bci The bitmap_coords_info structure.
375  */
376 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) {
377     if (is_pixel_paintability_checked(trace_t)) {
378         return is_pixel_paintable(trace_t);
379     } else {
380         unsigned char *t = get_pixel(px, x, y, bci.width);
381         if (compare_pixels(t, orig_color, bci.merged_orig_pixel, bci.dtc, bci.threshold, bci.method)) {
382             mark_pixel_paintable(trace_t);
383             return true;
384         } else {
385             mark_pixel_not_paintable(trace_t);
386             return false;
387         }
388     }
391 /**
392  * \brief Perform the bitmap-to-vector tracing and place the traced path onto the document.
393  * \param px The trace pixel buffer to trace to SVG.
394  * \param desktop The desktop on which to place the final SVG path.
395  * \param transform The transform to apply to the final SVG path.
396  * \param union_with_selection If true, merge the final SVG path with the current selection.
397  */
398 static void do_trace(bitmap_coords_info bci, guchar *trace_px, SPDesktop *desktop, Geom::Matrix transform, unsigned int min_x, unsigned int max_x, unsigned int min_y, unsigned int max_y, bool union_with_selection) {
399     SPDocument *document = sp_desktop_document(desktop);
401     unsigned char *trace_t;
403     GrayMap *gray_map = GrayMapCreate((max_x - min_x + 1), (max_y - min_y + 1));
404     unsigned int gray_map_y = 0;
405     for (unsigned int y = min_y; y <= max_y; y++) {
406         unsigned long *gray_map_t = gray_map->rows[gray_map_y];
408         trace_t = get_trace_pixel(trace_px, min_x, y, bci.width);
409         for (unsigned int x = min_x; x <= max_x; x++) {
410             *gray_map_t = is_pixel_colored(trace_t) ? GRAYMAP_BLACK : GRAYMAP_WHITE;
411             gray_map_t++;
412             trace_t++;
413         }
414         gray_map_y++;
415     }
417     Inkscape::Trace::Potrace::PotraceTracingEngine pte;
418     pte.keepGoing = 1;
419     std::vector<Inkscape::Trace::TracingEngineResult> results = pte.traceGrayMap(gray_map);
420     gray_map->destroy(gray_map);
422     //XML Tree being used here directly while it shouldn't be...."
423     Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc();
425     long totalNodeCount = 0L;
427     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
428     double offset = prefs->getDouble("/tools/paintbucket/offset", 0.0);
430     for (unsigned int i=0 ; i<results.size() ; i++) {
431         Inkscape::Trace::TracingEngineResult result = results[i];
432         totalNodeCount += result.getNodeCount();
434         Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path");
435         /* Set style */
436         sp_desktop_apply_style_tool (desktop, pathRepr, "/tools/paintbucket", false);
438         Geom::PathVector pathv = sp_svg_read_pathv(result.getPathData().c_str());
439         Path *path = new Path;
440         path->LoadPathVector(pathv);
442         if (offset != 0) {
443         
444             Shape *path_shape = new Shape();
445         
446             path->ConvertWithBackData(0.03);
447             path->Fill(path_shape, 0);
448             delete path;
449         
450             Shape *expanded_path_shape = new Shape();
451         
452             expanded_path_shape->ConvertToShape(path_shape, fill_nonZero);
453             path_shape->MakeOffset(expanded_path_shape, offset * desktop->current_zoom(), join_round, 4);
454             expanded_path_shape->ConvertToShape(path_shape, fill_positive);
456             Path *expanded_path = new Path();
457         
458             expanded_path->Reset();
459             expanded_path_shape->ConvertToForme(expanded_path);
460             expanded_path->ConvertEvenLines(1.0);
461             expanded_path->Simplify(1.0);
462         
463             delete path_shape;
464             delete expanded_path_shape;
465         
466             gchar *str = expanded_path->svg_dump_path();
467             if (str && *str) {
468                 pathRepr->setAttribute("d", str);
469                 g_free(str);
470             } else {
471                 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Too much inset</b>, the result is empty."));
472                 Inkscape::GC::release(pathRepr);
473                 g_free(str);
474                 return;
475             }
477             delete expanded_path;
479         } else {
480             gchar *str = path->svg_dump_path();
481             delete path;
482             pathRepr->setAttribute("d", str);
483             g_free(str);
484         }
486         desktop->currentLayer()->addChild(pathRepr,NULL);
488         SPObject *reprobj = document->getObjectByRepr(pathRepr);
489         if (reprobj) {
490             SP_ITEM(reprobj)->doWriteTransform(pathRepr, transform, NULL);
491             
492             // premultiply the item transform by the accumulated parent transform in the paste layer
493             Geom::Matrix local (SP_GROUP(desktop->currentLayer())->i2doc_affine());
494             if (!local.isIdentity()) {
495                 gchar const *t_str = pathRepr->attribute("transform");
496                 Geom::Matrix item_t (Geom::identity());
497                 if (t_str)
498                     sp_svg_transform_read(t_str, &item_t);
499                 item_t *= local.inverse();
500                 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
501                 gchar *affinestr=sp_svg_transform_write(item_t);
502                 pathRepr->setAttribute("transform", affinestr);
503                 g_free(affinestr);
504             }
506             Inkscape::Selection *selection = sp_desktop_selection(desktop);
508             pathRepr->setPosition(-1);
510             if (union_with_selection) {
511                 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)));
512                 selection->add(reprobj);
513                 sp_selected_path_union_skip_undo(desktop);
514             } else {
515                 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)));
516                 selection->set(reprobj);
517             }
519         }
521         Inkscape::GC::release(pathRepr);
523     }
526 /**
527  * \brief The possible return states of perform_bitmap_scanline_check()
528  */
529 enum ScanlineCheckResult {
530     SCANLINE_CHECK_OK,
531     SCANLINE_CHECK_ABORTED,
532     SCANLINE_CHECK_BOUNDARY
533 };
535 /**
536  * \brief Determine if the provided coordinates are within the pixel buffer limits.
537  * \param x The X coordinate.
538  * \param y The Y coordinate.
539  * \param bci The bitmap_coords_info structure.
540  */
541 inline static bool coords_in_range(unsigned int x, unsigned int y, bitmap_coords_info bci) {
542     return (x < bci.width) &&
543            (y < bci.height);
546 #define PAINT_DIRECTION_LEFT 1
547 #define PAINT_DIRECTION_RIGHT 2
548 #define PAINT_DIRECTION_UP 4
549 #define PAINT_DIRECTION_DOWN 8
550 #define PAINT_DIRECTION_ALL 15
552 /**
553  * \brief Paint a pixel or a square (if autogap is enabled) on the trace pixel buffer
554  * \param px The rendered pixel buffer to check.
555  * \param trace_px The trace pixel buffer.
556  * \param orig_color The original selected pixel to use as the fill target color.
557  * \param bci The bitmap_coords_info structure.
558  * \param original_point_trace_t The original pixel in the trace pixel buffer to check.
559  */
560 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) {
561     if (bci.radius == 0) {
562         mark_pixel_colored(original_point_trace_t); 
563         return PAINT_DIRECTION_ALL;
564     } else {
565         unsigned char *trace_t;
566   
567         bool can_paint_up = true;
568         bool can_paint_down = true;
569         bool can_paint_left = true;
570         bool can_paint_right = true;
571       
572         for (unsigned int ty = bci.y - bci.radius; ty <= bci.y + bci.radius; ty++) {
573             for (unsigned int tx = bci.x - bci.radius; tx <= bci.x + bci.radius; tx++) {
574                 if (coords_in_range(tx, ty, bci)) {
575                     trace_t = get_trace_pixel(trace_px, tx, ty, bci.width);
576                     if (!is_pixel_colored(trace_t)) {
577                         if (check_if_pixel_is_paintable(px, trace_t, tx, ty, orig_color, bci)) {
578                             mark_pixel_colored(trace_t); 
579                         } else {
580                             if (tx < bci.x) { can_paint_left = false; }
581                             if (tx > bci.x) { can_paint_right = false; }
582                             if (ty < bci.y) { can_paint_up = false; }
583                             if (ty > bci.y) { can_paint_down = false; }
584                         }
585                     }
586                 }
587             }
588         }
589     
590         unsigned int paint_directions = 0;
591         if (can_paint_left) { paint_directions += PAINT_DIRECTION_LEFT; }
592         if (can_paint_right) { paint_directions += PAINT_DIRECTION_RIGHT; }
593         if (can_paint_up) { paint_directions += PAINT_DIRECTION_UP; }
594         if (can_paint_down) { paint_directions += PAINT_DIRECTION_DOWN; }
595         
596         return paint_directions;
597     }
600 /**
601  * \brief Push a point to be checked onto the bottom of the rendered pixel buffer check queue.
602  * \param fill_queue The fill queue to add the point to.
603  * \param max_queue_size The maximum size of the fill queue.
604  * \param trace_t The trace pixel buffer pixel.
605  * \param x The X coordinate.
606  * \param y The Y coordinate.
607  */
608 static void push_point_onto_queue(std::deque<Geom::Point> *fill_queue, unsigned int max_queue_size, unsigned char *trace_t, unsigned int x, unsigned int y) {
609     if (!is_pixel_queued(trace_t)) {
610         if ((fill_queue->size() < max_queue_size)) {
611             fill_queue->push_back(Geom::Point(x, y));
612             mark_pixel_queued(trace_t);
613         }
614     }
617 /**
618  * \brief Shift a point to be checked onto the top of the rendered pixel buffer check queue.
619  * \param fill_queue The fill queue to add the point to.
620  * \param max_queue_size The maximum size of the fill queue.
621  * \param trace_t The trace pixel buffer pixel.
622  * \param x The X coordinate.
623  * \param y The Y coordinate.
624  */
625 static void shift_point_onto_queue(std::deque<Geom::Point> *fill_queue, unsigned int max_queue_size, unsigned char *trace_t, unsigned int x, unsigned int y) {
626     if (!is_pixel_queued(trace_t)) {
627         if ((fill_queue->size() < max_queue_size)) {
628             fill_queue->push_front(Geom::Point(x, y));
629             mark_pixel_queued(trace_t);
630         }
631     }
634 /**
635  * \brief Scan a row in the rendered pixel buffer and add points to the fill queue as necessary.
636  * \param fill_queue The fill queue to add the point to.
637  * \param px The rendered pixel buffer.
638  * \param trace_px The trace pixel buffer.
639  * \param orig_color The original selected pixel to use as the fill target color.
640  * \param bci The bitmap_coords_info structure.
641  */
642 static ScanlineCheckResult perform_bitmap_scanline_check(std::deque<Geom::Point> *fill_queue, guchar *px, guchar *trace_px, unsigned char *orig_color, bitmap_coords_info bci, unsigned int *min_x, unsigned int *max_x) {
643     bool aborted = false;
644     bool reached_screen_boundary = false;
645     bool ok;
647     bool keep_tracing;
648     bool initial_paint = true;
650     unsigned char *current_trace_t = get_trace_pixel(trace_px, bci.x, bci.y, bci.width);
651     unsigned int paint_directions;
653     bool currently_painting_top = false;
654     bool currently_painting_bottom = false;
656     unsigned int top_ty = bci.y - 1;
657     unsigned int bottom_ty = bci.y + 1;
659     bool can_paint_top = (top_ty > 0);
660     bool can_paint_bottom = (bottom_ty < bci.height);
662     Geom::Point t = fill_queue->front();
664     do {
665         ok = false;
666         if (bci.is_left) {
667             keep_tracing = (bci.x != 0);
668         } else {
669             keep_tracing = (bci.x < bci.width);
670         }
672         *min_x = MIN(*min_x, bci.x);
673         *max_x = MAX(*max_x, bci.x);
675         if (keep_tracing) {
676             if (check_if_pixel_is_paintable(px, current_trace_t, bci.x, bci.y, orig_color, bci)) {
677                 paint_directions = paint_pixel(px, trace_px, orig_color, bci, current_trace_t);
678                 if (bci.radius == 0) {
679                     mark_pixel_checked(current_trace_t);
680                     if ((t[Geom::X] == bci.x) && (t[Geom::Y] == bci.y)) {
681                         fill_queue->pop_front(); t = fill_queue->front();
682                     }
683                 }
685                 if (can_paint_top) {
686                     if (paint_directions & PAINT_DIRECTION_UP) { 
687                         unsigned char *trace_t = current_trace_t - bci.width;
688                         if (!is_pixel_queued(trace_t)) {
689                             bool ok_to_paint = check_if_pixel_is_paintable(px, trace_t, bci.x, top_ty, orig_color, bci);
691                             if (initial_paint) { currently_painting_top = !ok_to_paint; }
693                             if (ok_to_paint && (!currently_painting_top)) {
694                                 currently_painting_top = true;
695                                 push_point_onto_queue(fill_queue, bci.max_queue_size, trace_t, bci.x, top_ty);
696                             }
697                             if ((!ok_to_paint) && currently_painting_top) {
698                                 currently_painting_top = false;
699                             }
700                         }
701                     }
702                 }
704                 if (can_paint_bottom) {
705                     if (paint_directions & PAINT_DIRECTION_DOWN) { 
706                         unsigned char *trace_t = current_trace_t + bci.width;
707                         if (!is_pixel_queued(trace_t)) {
708                             bool ok_to_paint = check_if_pixel_is_paintable(px, trace_t, bci.x, bottom_ty, orig_color, bci);
710                             if (initial_paint) { currently_painting_bottom = !ok_to_paint; }
712                             if (ok_to_paint && (!currently_painting_bottom)) {
713                                 currently_painting_bottom = true;
714                                 push_point_onto_queue(fill_queue, bci.max_queue_size, trace_t, bci.x, bottom_ty);
715                             }
716                             if ((!ok_to_paint) && currently_painting_bottom) {
717                                 currently_painting_bottom = false;
718                             }
719                         }
720                     }
721                 }
723                 if (bci.is_left) {
724                     if (paint_directions & PAINT_DIRECTION_LEFT) {
725                         bci.x--; current_trace_t--;
726                         ok = true;
727                     }
728                 } else {
729                     if (paint_directions & PAINT_DIRECTION_RIGHT) {
730                         bci.x++; current_trace_t++;
731                         ok = true;
732                     }
733                 }
735                 initial_paint = false;
736             }
737         } else {
738             if (bci.bbox.min()[Geom::X] > bci.screen.min()[Geom::X]) {
739                 aborted = true; break;
740             } else {
741                 reached_screen_boundary = true;
742             }
743         }
744     } while (ok);
746     if (aborted) { return SCANLINE_CHECK_ABORTED; }
747     if (reached_screen_boundary) { return SCANLINE_CHECK_BOUNDARY; }
748     return SCANLINE_CHECK_OK;
751 /**
752  * \brief Sort the rendered pixel buffer check queue vertically.
753  */
754 static bool sort_fill_queue_vertical(Geom::Point a, Geom::Point b) {
755     return a[Geom::Y] > b[Geom::Y];
758 /**
759  * \brief Sort the rendered pixel buffer check queue horizontally.
760  */
761 static bool sort_fill_queue_horizontal(Geom::Point a, Geom::Point b) {
762     return a[Geom::X] > b[Geom::X];
765 /**
766  * \brief Perform a flood fill operation.
767  * \param event_context The event context for this tool.
768  * \param event The details of this event.
769  * \param union_with_selection If true, union the new fill with the current selection.
770  * \param is_point_fill If false, use the Rubberband "touch selection" to get the initial points for the fill.
771  * \param is_touch_fill If true, use only the initial contact point in the Rubberband "touch selection" as the fill target color.
772  */
773 static void sp_flood_do_flood_fill(SPEventContext *event_context, GdkEvent *event, bool union_with_selection, bool is_point_fill, bool is_touch_fill) {
774     SPDesktop *desktop = event_context->desktop;
775     SPDocument *document = sp_desktop_document(desktop);
777     /* Create new arena */
778     NRArena *arena = NRArena::create();
779     unsigned dkey = SPItem::display_key_new(1);
781     document->ensureUpToDate();
782     
783     SPItem *document_root = SP_ITEM(document->getRoot());
784     Geom::OptRect bbox = document_root->getBounds(Geom::identity());
786     if (!bbox) {
787         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
788         return;
789     }
790     
791     double zoom_scale = desktop->current_zoom();
792     
793     // Render 160% of the physical display to the render pixel buffer, so that available
794     // fill areas off the screen can be included in the fill.
795     double padding = 1.6;
797     Geom::Rect screen = desktop->get_display_area();
799     unsigned int width = (int)ceil(screen.width() * zoom_scale * padding);
800     unsigned int height = (int)ceil(screen.height() * zoom_scale * padding);
802     Geom::Point origin(screen.min()[Geom::X],
803                        document->getHeight() - screen.height() - screen.min()[Geom::Y]);
804                     
805     origin[Geom::X] = origin[Geom::X] + (screen.width() * ((1 - padding) / 2));
806     origin[Geom::Y] = origin[Geom::Y] + (screen.height() * ((1 - padding) / 2));
807     
808     Geom::Scale scale(zoom_scale, zoom_scale);
809     Geom::Matrix affine = scale * Geom::Translate(-origin * scale);
810     
811     /* Create ArenaItems and set transform */
812     NRArenaItem *root = SP_ITEM(document->getRoot())->invoke_show( arena, dkey, SP_ITEM_SHOW_DISPLAY);
813     nr_arena_item_set_transform(NR_ARENA_ITEM(root), affine);
815     NRGC gc(NULL);
816     gc.transform.setIdentity();
817     
818     NRRectL final_bbox;
819     final_bbox.x0 = 0;
820     final_bbox.y0 = 0; //row;
821     final_bbox.x1 = width;
822     final_bbox.y1 = height; //row + num_rows;
823     
824     nr_arena_item_invoke_update(root, &final_bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
826     guchar *px = g_new(guchar, 4 * width * height);
827     
828     NRPixBlock B;
829     nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
830                               final_bbox.x0, final_bbox.y0, final_bbox.x1, final_bbox.y1,
831                               px, 4 * width, FALSE, FALSE );
832     
833     SPNamedView *nv = sp_desktop_namedview(desktop);
834     unsigned long bgcolor = nv->pagecolor;
835     
836     unsigned char dtc[4];
837     dtc[0] = NR_RGBA32_R(bgcolor);
838     dtc[1] = NR_RGBA32_G(bgcolor);
839     dtc[2] = NR_RGBA32_B(bgcolor);
840     dtc[3] = NR_RGBA32_A(bgcolor);
841     
842     for (unsigned int fy = 0; fy < height; fy++) {
843         guchar *p = NR_PIXBLOCK_PX(&B) + fy * B.rs;
844         for (unsigned int fx = 0; fx < width; fx++) {
845             for (int i = 0; i < 4; i++) { 
846                 *p++ = dtc[i];
847             }
848         }
849     }
851     nr_arena_item_invoke_render(NULL, root, &final_bbox, &B, NR_ARENA_ITEM_RENDER_NO_CACHE );
852     nr_pixblock_release(&B);
853     
854     // Hide items
855     SP_ITEM(document->getRoot())->invoke_hide(dkey);
856     
857     nr_object_unref((NRObject *) arena);
858     
859     guchar *trace_px = g_new(guchar, width * height);
860     memset(trace_px, 0x00, width * height);
861     
862     std::deque<Geom::Point> fill_queue;
863     std::queue<Geom::Point> color_queue;
864     
865     std::vector<Geom::Point> fill_points;
866     
867     bool aborted = false;
868     int y_limit = height - 1;
870     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
871     PaintBucketChannels method = (PaintBucketChannels) prefs->getInt("/tools/paintbucket/channels", 0);
872     int threshold = prefs->getIntLimited("/tools/paintbucket/threshold", 1, 0, 100);
874     switch(method) {
875         case FLOOD_CHANNELS_ALPHA:
876         case FLOOD_CHANNELS_RGB:
877         case FLOOD_CHANNELS_R:
878         case FLOOD_CHANNELS_G:
879         case FLOOD_CHANNELS_B:
880             threshold = (255 * threshold) / 100;
881             break;
882         case FLOOD_CHANNELS_H:
883         case FLOOD_CHANNELS_S:
884         case FLOOD_CHANNELS_L:
885             break;
886     }
888     bitmap_coords_info bci;
889     
890     bci.y_limit = y_limit;
891     bci.width = width;
892     bci.height = height;
893     bci.threshold = threshold;
894     bci.method = method;
895     bci.bbox = *bbox;
896     bci.screen = screen;
897     bci.dtc = dtc;
898     bci.radius = prefs->getIntLimited("/tools/paintbucket/autogap", 0, 0, 3);
899     bci.max_queue_size = (width * height) / 4;
900     bci.current_step = 0;
902     if (is_point_fill) {
903         fill_points.push_back(Geom::Point(event->button.x, event->button.y));
904     } else {
905         Inkscape::Rubberband *r = Inkscape::Rubberband::get(desktop);
906         fill_points = r->getPoints();
907     }
909     for (unsigned int i = 0; i < fill_points.size(); i++) {
910         Geom::Point pw = Geom::Point(fill_points[i][Geom::X] / zoom_scale, document->getHeight() + (fill_points[i][Geom::Y] / zoom_scale)) * affine;
912         pw[Geom::X] = (int)MIN(width - 1, MAX(0, pw[Geom::X]));
913         pw[Geom::Y] = (int)MIN(height - 1, MAX(0, pw[Geom::Y]));
915         if (is_touch_fill) {
916             if (i == 0) {
917                 color_queue.push(pw);
918             } else {
919                 unsigned char *trace_t = get_trace_pixel(trace_px, (int)pw[Geom::X], (int)pw[Geom::Y], width);
920                 push_point_onto_queue(&fill_queue, bci.max_queue_size, trace_t, (int)pw[Geom::X], (int)pw[Geom::Y]);
921             }
922         } else {
923             color_queue.push(pw);
924         }
925     }
927     bool reached_screen_boundary = false;
929     bool first_run = true;
931     unsigned long sort_size_threshold = 5;
933     unsigned int min_y = height;
934     unsigned int max_y = 0;
935     unsigned int min_x = width;
936     unsigned int max_x = 0;
938     while (!color_queue.empty() && !aborted) {
939         Geom::Point color_point = color_queue.front();
940         color_queue.pop();
942         int cx = (int)color_point[Geom::X];
943         int cy = (int)color_point[Geom::Y];
945         unsigned char *orig_px = get_pixel(px, cx, cy, width);
946         unsigned char orig_color[4];
947         for (int i = 0; i < 4; i++) { orig_color[i] = orig_px[i]; }
949         unsigned char merged_orig[3];
951         merge_pixel_with_background(orig_color, dtc, merged_orig);
953         bci.merged_orig_pixel = merged_orig;
955         unsigned char *trace_t = get_trace_pixel(trace_px, cx, cy, width);
956         if (!is_pixel_checked(trace_t) && !is_pixel_colored(trace_t)) {
957             if (check_if_pixel_is_paintable(px, trace_px, cx, cy, orig_color, bci)) {
958                 shift_point_onto_queue(&fill_queue, bci.max_queue_size, trace_t, cx, cy);
960                 if (!first_run) {
961                     for (unsigned int y = 0; y < height; y++) {
962                         trace_t = get_trace_pixel(trace_px, 0, y, width);
963                         for (unsigned int x = 0; x < width; x++) {
964                             clear_pixel_paintability(trace_t);
965                             trace_t++;
966                         }
967                     }
968                 }
969                 first_run = false;
970             }
971         }
973         unsigned long old_fill_queue_size = fill_queue.size();
975         while (!fill_queue.empty() && !aborted) {
976             Geom::Point cp = fill_queue.front();
978             if (bci.radius == 0) {
979                 unsigned long new_fill_queue_size = fill_queue.size();
981                 /*
982                  * To reduce the number of points in the fill queue, periodically
983                  * resort all of the points in the queue so that scanline checks
984                  * can complete more quickly.  A point cannot be checked twice
985                  * in a normal scanline checks, so forcing scanline checks to start
986                  * from one corner of the rendered area as often as possible
987                  * will reduce the number of points that need to be checked and queued.
988                  */
989                 if (new_fill_queue_size > sort_size_threshold) {
990                     if (new_fill_queue_size > old_fill_queue_size) {
991                         std::sort(fill_queue.begin(), fill_queue.end(), sort_fill_queue_vertical);
993                         std::deque<Geom::Point>::iterator start_sort = fill_queue.begin();
994                         std::deque<Geom::Point>::iterator end_sort = fill_queue.begin();
995                         unsigned int sort_y = (unsigned int)cp[Geom::Y];
996                         unsigned int current_y = sort_y;
997                         
998                         for (std::deque<Geom::Point>::iterator i = fill_queue.begin(); i != fill_queue.end(); i++) {
999                             Geom::Point current = *i;
1000                             current_y = (unsigned int)current[Geom::Y];
1001                             if (current_y != sort_y) {
1002                                 if (start_sort != end_sort) {
1003                                     std::sort(start_sort, end_sort, sort_fill_queue_horizontal);
1004                                 }
1005                                 sort_y = current_y;
1006                                 start_sort = i;
1007                             }
1008                             end_sort = i;
1009                         }
1010                         if (start_sort != end_sort) {
1011                             std::sort(start_sort, end_sort, sort_fill_queue_horizontal);
1012                         }
1013                         
1014                         cp = fill_queue.front();
1015                     }
1016                 }
1018                 old_fill_queue_size = new_fill_queue_size;
1019             }
1021             fill_queue.pop_front();
1023             int x = (int)cp[Geom::X];
1024             int y = (int)cp[Geom::Y];
1026             min_y = MIN((unsigned int)y, min_y);
1027             max_y = MAX((unsigned int)y, max_y);
1029             unsigned char *trace_t = get_trace_pixel(trace_px, x, y, width);
1030             if (!is_pixel_checked(trace_t)) {
1031                 mark_pixel_checked(trace_t);
1033                 if (y == 0) {
1034                     if (bbox->min()[Geom::Y] > screen.min()[Geom::Y]) {
1035                         aborted = true; break;
1036                     } else {
1037                         reached_screen_boundary = true;
1038                     }
1039                 }
1041                 if (y == y_limit) {
1042                     if (bbox->max()[Geom::Y] < screen.max()[Geom::Y]) {
1043                         aborted = true; break;
1044                     } else {
1045                         reached_screen_boundary = true;
1046                     }
1047                 }
1049                 bci.is_left = true;
1050                 bci.x = x;
1051                 bci.y = y;
1053                 ScanlineCheckResult result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci, &min_x, &max_x);
1055                 switch (result) {
1056                     case SCANLINE_CHECK_ABORTED:
1057                         aborted = true;
1058                         break;
1059                     case SCANLINE_CHECK_BOUNDARY:
1060                         reached_screen_boundary = true;
1061                         break;
1062                     default:
1063                         break;
1064                 }
1066                 if (bci.x < width) {
1067                     trace_t++;
1068                     if (!is_pixel_checked(trace_t) && !is_pixel_queued(trace_t)) {
1069                         mark_pixel_checked(trace_t);
1070                         bci.is_left = false;
1071                         bci.x = x + 1;
1073                         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                         }
1085                     }
1086                 }
1087             }
1089             bci.current_step++;
1091             if (bci.current_step > bci.max_queue_size) {
1092                 aborted = true;
1093             }
1094         }
1095     }
1096     
1097     g_free(px);
1098     
1099     if (aborted) {
1100         g_free(trace_px);
1101         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
1102         return;
1103     }
1104     
1105     if (reached_screen_boundary) {
1106         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.")); 
1107     }
1109     unsigned int trace_padding = bci.radius + 1;
1110     if (min_y > trace_padding) { min_y -= trace_padding; }
1111     if (max_y < (y_limit - trace_padding)) { max_y += trace_padding; }
1112     if (min_x > trace_padding) { min_x -= trace_padding; }
1113     if (max_x < (width - 1 - trace_padding)) { max_x += trace_padding; }
1115     Geom::Point min_start = Geom::Point(min_x, min_y);
1116     
1117     affine = scale * Geom::Translate(-origin * scale - min_start);
1118     Geom::Matrix inverted_affine = Geom::Matrix(affine).inverse();
1119     
1120     do_trace(bci, trace_px, desktop, inverted_affine, min_x, max_x, min_y, max_y, union_with_selection);
1122     g_free(trace_px);
1123     
1124     DocumentUndo::done(document, SP_VERB_CONTEXT_PAINTBUCKET, _("Fill bounded area"));
1127 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
1129     gint ret = FALSE;
1131     SPDesktop *desktop = event_context->desktop;
1133     switch (event->type) {
1134     case GDK_BUTTON_PRESS:
1135         if ((event->button.state & GDK_CONTROL_MASK) && event->button.button == 1 && !event_context->space_panning) {
1136             Geom::Point const button_w(event->button.x,
1137                                        event->button.y);
1138             
1139             SPItem *item = sp_event_context_find_item (desktop, button_w, TRUE, TRUE);
1140             
1141             // Set style
1142             desktop->applyCurrentOrToolStyle(item, "/tools/paintbucket", false);
1143             DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET, _("Set style on object"));
1144             ret = TRUE;
1145         }
1146         break;
1147     default:
1148         break;
1149     }
1151     if (((SPEventContextClass *) parent_class)->item_handler) {
1152         ret = ((SPEventContextClass *) parent_class)->item_handler(event_context, item, event);
1153     }
1155     return ret;
1158 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event)
1160     static bool dragging;
1161     
1162     gint ret = FALSE;
1163     SPDesktop *desktop = event_context->desktop;
1165     switch (event->type) {
1166     case GDK_BUTTON_PRESS:
1167         if (event->button.button == 1 && !event_context->space_panning) {
1168             if (!(event->button.state & GDK_CONTROL_MASK)) {
1169                 Geom::Point const button_w(event->button.x,
1170                                            event->button.y);
1171     
1172                 if (Inkscape::have_viable_layer(desktop, event_context->defaultMessageContext())) {
1173                     // save drag origin
1174                     event_context->xp = (gint) button_w[Geom::X];
1175                     event_context->yp = (gint) button_w[Geom::Y];
1176                     event_context->within_tolerance = true;
1177                       
1178                     dragging = true;
1179                     
1180                     Geom::Point const p(desktop->w2d(button_w));
1181                     Inkscape::Rubberband::get(desktop)->setMode(RUBBERBAND_MODE_TOUCHPATH);
1182                     Inkscape::Rubberband::get(desktop)->start(desktop, p);
1183                 }
1184             }
1185         }
1186     case GDK_MOTION_NOTIFY:
1187         if ( dragging
1188              && ( event->motion.state & GDK_BUTTON1_MASK ) && !event_context->space_panning)
1189         {
1190             if ( event_context->within_tolerance
1191                  && ( abs( (gint) event->motion.x - event_context->xp ) < event_context->tolerance )
1192                  && ( abs( (gint) event->motion.y - event_context->yp ) < event_context->tolerance ) ) {
1193                 break; // do not drag if we're within tolerance from origin
1194             }
1195             
1196             event_context->within_tolerance = false;
1197             
1198             Geom::Point const motion_pt(event->motion.x, event->motion.y);
1199             Geom::Point const p(desktop->w2d(motion_pt));
1200             if (Inkscape::Rubberband::get(desktop)->is_started()) {
1201                 Inkscape::Rubberband::get(desktop)->move(p);
1202                 event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Draw over</b> areas to add to fill, hold <b>Alt</b> for touch fill"));
1203                 gobble_motion_events(GDK_BUTTON1_MASK);
1204             }
1205         }
1206         break;
1208     case GDK_BUTTON_RELEASE:
1209         if (event->button.button == 1 && !event_context->space_panning) {
1210             Inkscape::Rubberband *r = Inkscape::Rubberband::get(desktop);
1211             if (r->is_started()) {
1212                 // set "busy" cursor
1213                 desktop->setWaitingCursor();
1215                 if (SP_IS_EVENT_CONTEXT(event_context)) { 
1216                     // Since setWaitingCursor runs main loop iterations, we may have already left this tool!
1217                     // So check if the tool is valid before doing anything
1218                     dragging = false;
1220                     bool is_point_fill = event_context->within_tolerance;
1221                     bool is_touch_fill = event->button.state & GDK_MOD1_MASK;
1222                     
1223                     sp_flood_do_flood_fill(event_context, event, event->button.state & GDK_SHIFT_MASK, is_point_fill, is_touch_fill);
1224                     
1225                     desktop->clearWaitingCursor();
1226                     // restore cursor when done; note that it may already be different if e.g. user 
1227                     // switched to another tool during interruptible tracing or drawing, in which case do nothing
1229                     ret = TRUE;
1230                 }
1232                 r->stop();
1234                 if (SP_IS_EVENT_CONTEXT(event_context)) {
1235                     event_context->defaultMessageContext()->clear();
1236                 }
1237             }
1238         }
1239         break;
1240     case GDK_KEY_PRESS:
1241         switch (get_group0_keyval (&event->key)) {
1242         case GDK_Up:
1243         case GDK_Down:
1244         case GDK_KP_Up:
1245         case GDK_KP_Down:
1246             // prevent the zoom field from activation
1247             if (!MOD__CTRL_ONLY)
1248                 ret = TRUE;
1249             break;
1250         default:
1251             break;
1252         }
1253         break;
1254     default:
1255         break;
1256     }
1258     if (!ret) {
1259         if (((SPEventContextClass *) parent_class)->root_handler) {
1260             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1261         }
1262     }
1264     return ret;
1268 static void sp_flood_finish(SPFloodContext *rc)
1270     rc->_message_context->clear();
1272     if ( rc->item != NULL ) {
1273         SPDesktop * desktop;
1275         desktop = SP_EVENT_CONTEXT_DESKTOP(rc);
1277         SP_OBJECT(rc->item)->updateRepr();
1279         sp_canvas_end_forced_full_redraws(desktop->canvas);
1281         sp_desktop_selection(desktop)->set(rc->item);
1282         DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET,
1283                         _("Fill bounded area"));
1285         rc->item = NULL;
1286     }
1289 void flood_channels_set_channels( gint channels )
1291     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1292     prefs->setInt("/tools/paintbucket/channels", channels);
1295 /*
1296   Local Variables:
1297   mode:c++
1298   c-file-style:"stroustrup"
1299   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1300   indent-tabs-mode:nil
1301   fill-column:99
1302   End:
1303 */
1304 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :