Code

Fix retrieving of initial point color for paint bucket fill
[inkscape.git] / src / flood-context.cpp
1 #define __SP_FLOOD_CONTEXT_C__
3 /*
4 * Flood fill drawing context
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>
23 #include "macros.h"
24 #include "display/sp-canvas.h"
25 #include "document.h"
26 #include "sp-namedview.h"
27 #include "sp-object.h"
28 #include "sp-rect.h"
29 #include "selection.h"
30 #include "selection-chemistry.h"
31 #include "desktop-handles.h"
32 #include "snap.h"
33 #include "desktop.h"
34 #include "desktop-style.h"
35 #include "message-stack.h"
36 #include "message-context.h"
37 #include "pixmaps/cursor-paintbucket.xpm"
38 #include "flood-context.h"
39 #include "sp-metrics.h"
40 #include <glibmm/i18n.h>
41 #include "object-edit.h"
42 #include "xml/repr.h"
43 #include "xml/node-event-vector.h"
44 #include "prefs-utils.h"
45 #include "context-fns.h"
46 #include "rubberband.h"
48 #include "display/nr-arena-item.h"
49 #include "display/nr-arena.h"
50 #include "display/nr-arena-image.h"
51 #include "display/canvas-arena.h"
52 #include "libnr/nr-pixops.h"
53 #include "libnr/nr-matrix-rotate-ops.h"
54 #include "libnr/nr-matrix-translate-ops.h"
55 #include "libnr/nr-rotate-fns.h"
56 #include "libnr/nr-scale-ops.h"
57 #include "libnr/nr-scale-translate-ops.h"
58 #include "libnr/nr-translate-matrix-ops.h"
59 #include "libnr/nr-translate-scale-ops.h"
60 #include "libnr/nr-matrix-ops.h"
61 #include "sp-item.h"
62 #include "sp-root.h"
63 #include "sp-defs.h"
64 #include "sp-path.h"
65 #include "splivarot.h"
66 #include "livarot/Path.h"
67 #include "livarot/Shape.h"
68 #include "libnr/n-art-bpath.h"
69 #include "svg/svg.h"
70 #include "color.h"
72 #include "trace/trace.h"
73 #include "trace/potrace/inkscape-potrace.h"
75 static void sp_flood_context_class_init(SPFloodContextClass *klass);
76 static void sp_flood_context_init(SPFloodContext *flood_context);
77 static void sp_flood_context_dispose(GObject *object);
79 static void sp_flood_context_setup(SPEventContext *ec);
81 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event);
82 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event);
84 static void sp_flood_finish(SPFloodContext *rc);
86 static SPEventContextClass *parent_class;
89 GtkType sp_flood_context_get_type()
90 {
91     static GType type = 0;
92     if (!type) {
93         GTypeInfo info = {
94             sizeof(SPFloodContextClass),
95             NULL, NULL,
96             (GClassInitFunc) sp_flood_context_class_init,
97             NULL, NULL,
98             sizeof(SPFloodContext),
99             4,
100             (GInstanceInitFunc) sp_flood_context_init,
101             NULL,    /* value_table */
102         };
103         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPFloodContext", &info, (GTypeFlags) 0);
104     }
105     return type;
108 static void sp_flood_context_class_init(SPFloodContextClass *klass)
110     GObjectClass *object_class = (GObjectClass *) klass;
111     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
113     parent_class = (SPEventContextClass *) g_type_class_peek_parent(klass);
115     object_class->dispose = sp_flood_context_dispose;
117     event_context_class->setup = sp_flood_context_setup;
118     event_context_class->root_handler  = sp_flood_context_root_handler;
119     event_context_class->item_handler  = sp_flood_context_item_handler;
122 static void sp_flood_context_init(SPFloodContext *flood_context)
124     SPEventContext *event_context = SP_EVENT_CONTEXT(flood_context);
126     event_context->cursor_shape = cursor_paintbucket_xpm;
127     event_context->hot_x = 11;
128     event_context->hot_y = 30;
129     event_context->xp = 0;
130     event_context->yp = 0;
131     event_context->tolerance = 0;
132     event_context->within_tolerance = false;
133     event_context->item_to_select = NULL;
135     event_context->shape_repr = NULL;
136     event_context->shape_knot_holder = NULL;
138     flood_context->item = NULL;
140     new (&flood_context->sel_changed_connection) sigc::connection();
143 static void sp_flood_context_dispose(GObject *object)
145     SPFloodContext *rc = SP_FLOOD_CONTEXT(object);
146     SPEventContext *ec = SP_EVENT_CONTEXT(object);
148     rc->sel_changed_connection.disconnect();
149     rc->sel_changed_connection.~connection();
151     /* fixme: This is necessary because we do not grab */
152     if (rc->item) {
153         sp_flood_finish(rc);
154     }
156     if (ec->shape_repr) { // remove old listener
157         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
158         Inkscape::GC::release(ec->shape_repr);
159         ec->shape_repr = 0;
160     }
162     if (rc->_message_context) {
163         delete rc->_message_context;
164     }
166     G_OBJECT_CLASS(parent_class)->dispose(object);
169 static Inkscape::XML::NodeEventVector ec_shape_repr_events = {
170     NULL, /* child_added */
171     NULL, /* child_removed */
172     ec_shape_event_attr_changed,
173     NULL, /* content_changed */
174     NULL  /* order_changed */
175 };
177 /**
178 \brief  Callback that processes the "changed" signal on the selection;
179 destroys old and creates new knotholder
180 */
181 void sp_flood_context_selection_changed(Inkscape::Selection *selection, gpointer data)
183     SPFloodContext *rc = SP_FLOOD_CONTEXT(data);
184     SPEventContext *ec = SP_EVENT_CONTEXT(rc);
186     if (ec->shape_repr) { // remove old listener
187         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
188         Inkscape::GC::release(ec->shape_repr);
189         ec->shape_repr = 0;
190     }
192     SPItem *item = selection->singleItem();
193     if (item) {
194         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
195         if (shape_repr) {
196             ec->shape_repr = shape_repr;
197             Inkscape::GC::anchor(shape_repr);
198             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
199         }
200     }
203 static void sp_flood_context_setup(SPEventContext *ec)
205     SPFloodContext *rc = SP_FLOOD_CONTEXT(ec);
207     if (((SPEventContextClass *) parent_class)->setup) {
208         ((SPEventContextClass *) parent_class)->setup(ec);
209     }
211     SPItem *item = sp_desktop_selection(ec->desktop)->singleItem();
212     if (item) {
213         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
214         if (shape_repr) {
215             ec->shape_repr = shape_repr;
216             Inkscape::GC::anchor(shape_repr);
217             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
218         }
219     }
221     rc->sel_changed_connection.disconnect();
222     rc->sel_changed_connection = sp_desktop_selection(ec->desktop)->connectChanged(
223         sigc::bind(sigc::ptr_fun(&sp_flood_context_selection_changed), (gpointer)rc)
224     );
226     rc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
229 static void
230 merge_pixel_with_background (unsigned char *orig, unsigned char *bg,
231            unsigned char *base)
233     for (int i = 0; i < 3; i++) {
234         base[i] = (255 * (255 - bg[3])) / 255 + (bg[i] * bg[3]) / 255;
235         base[i] = (base[i] * (255 - orig[3])) / 255 + (orig[i] * orig[3]) / 255;
236     }
237     base[3] = 255;
240 inline unsigned char * get_pixel(guchar *px, int x, int y, int width) {
241     return px + (x + y * width) * 4;
244 enum PaintBucketChannels {
245     FLOOD_CHANNELS_RGB,
246     FLOOD_CHANNELS_R,
247     FLOOD_CHANNELS_G,
248     FLOOD_CHANNELS_B,
249     FLOOD_CHANNELS_H,
250     FLOOD_CHANNELS_S,
251     FLOOD_CHANNELS_L,
252     FLOOD_CHANNELS_ALPHA
253 };
255 GList * flood_channels_dropdown_items_list() {
256     GList *glist = NULL;
258     glist = g_list_append (glist, _("Visible Colors"));
259     glist = g_list_append (glist, _("Red"));
260     glist = g_list_append (glist, _("Green"));
261     glist = g_list_append (glist, _("Blue"));
262     glist = g_list_append (glist, _("Hue"));
263     glist = g_list_append (glist, _("Saturation"));
264     glist = g_list_append (glist, _("Lightness"));
265     glist = g_list_append (glist, _("Alpha"));
267     return glist;
270 static bool compare_pixels(unsigned char *check, unsigned char *orig, unsigned char *dtc, int threshold, PaintBucketChannels method) {
271     int diff = 0;
272     float hsl_check[3], hsl_orig[3];
273     
274     if ((method == FLOOD_CHANNELS_H) ||
275         (method == FLOOD_CHANNELS_S) ||
276         (method == FLOOD_CHANNELS_L)) {
277         sp_color_rgb_to_hsl_floatv(hsl_check, check[0] / 255.0, check[1] / 255.0, check[2] / 255.0);
278         sp_color_rgb_to_hsl_floatv(hsl_orig, orig[0] / 255.0, orig[1] / 255.0, orig[2] / 255.0);
279     }
280     
281     switch (method) {
282         case FLOOD_CHANNELS_ALPHA:
283             return ((int)abs(check[3] - orig[3]) <= threshold);
284         case FLOOD_CHANNELS_R:
285             return ((int)abs(check[0] - orig[0]) <= threshold);
286         case FLOOD_CHANNELS_G:
287             return ((int)abs(check[1] - orig[1]) <= threshold);
288         case FLOOD_CHANNELS_B:
289             return ((int)abs(check[2] - orig[2]) <= threshold);
290         case FLOOD_CHANNELS_RGB:
291             unsigned char merged_orig[4];
292             unsigned char merged_check[4];
293             
294             merge_pixel_with_background(orig, dtc, merged_orig);
295             merge_pixel_with_background(check, dtc, merged_check);
296             
297             for (int i = 0; i < 3; i++) {
298               diff += (int)abs(merged_check[i] - merged_orig[i]);
299             }
300             return ((diff / 3) <= ((threshold * 3) / 4));
301         
302         case FLOOD_CHANNELS_H:
303             return ((int)(fabs(hsl_check[0] - hsl_orig[0]) * 100.0) <= threshold);
304         case FLOOD_CHANNELS_S:
305             return ((int)(fabs(hsl_check[1] - hsl_orig[1]) * 100.0) <= threshold);
306         case FLOOD_CHANNELS_L:
307             return ((int)(fabs(hsl_check[2] - hsl_orig[2]) * 100.0) <= threshold);
308     }
309     
310     return false;
313 static bool try_add_to_queue(std::queue<NR::Point> *fill_queue, guchar *px, guchar *trace_px, unsigned char *orig, unsigned char *dtc, int x, int y, int width, int threshold, PaintBucketChannels method, bool fill_switch) {
314     unsigned char *t = get_pixel(px, x, y, width);
315     if (compare_pixels(t, orig, dtc, threshold, method)) {
316         unsigned char *trace_t = get_pixel(trace_px, x, y, width);
317         if (trace_t[3] != 255 && trace_t[0] != 255) {
318             if (fill_switch) {
319                 fill_queue->push(NR::Point(x, y));
320                 trace_t[0] = 255;
321             }
322         }
323         return false;
324     }
325     return true;
328 static void do_trace(GdkPixbuf *px, SPDesktop *desktop, NR::Matrix transform, bool union_with_selection) {
329     SPDocument *document = sp_desktop_document(desktop);
330     
331     Inkscape::Trace::Potrace::PotraceTracingEngine pte;
332         
333     pte.setTraceType(Inkscape::Trace::Potrace::TRACE_BRIGHTNESS);
334     pte.setInvert(false);
336     Glib::RefPtr<Gdk::Pixbuf> pixbuf = Glib::wrap(px, true);
337     
338     std::vector<Inkscape::Trace::TracingEngineResult> results = pte.trace(pixbuf);
339     
340     Inkscape::XML::Node *layer_repr = SP_GROUP(desktop->currentLayer())->repr;
341     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
343     long totalNodeCount = 0L;
345     double offset = prefs_get_double_attribute("tools.paintbucket", "offset", 0.0);
347     for (unsigned int i=0 ; i<results.size() ; i++) {
348         Inkscape::Trace::TracingEngineResult result = results[i];
349         totalNodeCount += result.getNodeCount();
351         Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path");
352         /* Set style */
353         sp_desktop_apply_style_tool (desktop, pathRepr, "tools.paintbucket", false);
355         NArtBpath *bpath = sp_svg_read_path(result.getPathData().c_str());
356         Path *path = bpath_to_Path(bpath);
357         g_free(bpath);
359         if (offset != 0) {
360         
361             Shape *path_shape = new Shape();
362         
363             path->ConvertWithBackData(0.03);
364             path->Fill(path_shape, 0);
365             delete path;
366         
367             Shape *expanded_path_shape = new Shape();
368         
369             expanded_path_shape->ConvertToShape(path_shape, fill_nonZero);
370             path_shape->MakeOffset(expanded_path_shape, offset * desktop->current_zoom(), join_round, 4);
371             expanded_path_shape->ConvertToShape(path_shape, fill_positive);
373             Path *expanded_path = new Path();
374         
375             expanded_path->Reset();
376             expanded_path_shape->ConvertToForme(expanded_path);
377             expanded_path->ConvertEvenLines(1.0);
378             expanded_path->Simplify(1.0);
379         
380             delete path_shape;
381             delete expanded_path_shape;
382         
383             gchar *str = expanded_path->svg_dump_path();
384             if (str && *str) {
385                 pathRepr->setAttribute("d", str);
386                 g_free(str);
387             } else {
388                 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Too much inset</b>, the result is empty."));
389                 Inkscape::GC::release(pathRepr);
390                 g_free(str);
391                 return;
392             }
394             delete expanded_path;
396         } else {
397             gchar *str = path->svg_dump_path();
398             delete path;
399             pathRepr->setAttribute("d", str);
400             g_free(str);
401         }
403         layer_repr->addChild(pathRepr, NULL);
405         SPObject *reprobj = document->getObjectByRepr(pathRepr);
406         if (reprobj) {
407             sp_item_write_transform(SP_ITEM(reprobj), pathRepr, transform, NULL);
408             
409             // premultiply the item transform by the accumulated parent transform in the paste layer
410             NR::Matrix local = sp_item_i2doc_affine(SP_GROUP(desktop->currentLayer()));
411             if (!local.test_identity()) {
412                 gchar const *t_str = pathRepr->attribute("transform");
413                 NR::Matrix item_t (NR::identity());
414                 if (t_str)
415                     sp_svg_transform_read(t_str, &item_t);
416                 item_t *= local.inverse();
417                 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
418                 gchar *affinestr=sp_svg_transform_write(item_t);
419                 pathRepr->setAttribute("transform", affinestr);
420                 g_free(affinestr);
421             }
423             Inkscape::Selection *selection = sp_desktop_selection(desktop);
425             pathRepr->setPosition(-1);
427             if (union_with_selection) {
428                 desktop->messageStack()->flashF(Inkscape::WARNING_MESSAGE, _("Area filled, path with <b>%d</b> nodes created and unioned with selection."), sp_nodes_in_path(SP_PATH(reprobj)));
429                 selection->add(reprobj);
430                 sp_selected_path_union_skip_undo();
431             } else {
432                 desktop->messageStack()->flashF(Inkscape::WARNING_MESSAGE, _("Area filled, path with <b>%d</b> nodes created."), sp_nodes_in_path(SP_PATH(reprobj)));
433                 selection->set(reprobj);
434             }
436         }
438         Inkscape::GC::release(pathRepr);
440     }
443 struct bitmap_coords_info {
444     bool is_left;
445     int x;
446     int y;
447     int y_limit;
448     int width;
449     int threshold;
450     PaintBucketChannels method;
451     unsigned char *dtc;
452     bool top_fill;
453     bool bottom_fill;
454     NR::Rect bbox;
455     NR::Rect screen;
456 };
458 enum ScanlineCheckResult {
459     SCANLINE_CHECK_OK,
460     SCANLINE_CHECK_ABORTED,
461     SCANLINE_CHECK_BOUNDARY
462 };
464 static ScanlineCheckResult perform_bitmap_scanline_check(std::queue<NR::Point> *fill_queue, guchar *px, guchar *trace_px, unsigned char *orig_color, bitmap_coords_info bci) {
465     bool aborted = false;
466     bool reached_screen_boundary = false;
467     bool ok;
468   
469     bool keep_tracing;
470     unsigned char *t, *trace_t;
471   
472     do {
473         ok = false;
474         if (bci.is_left) {
475             keep_tracing = (bci.x >= 0);
476         } else {
477             keep_tracing = (bci.x < bci.width);
478         }
479         
480         if (keep_tracing) {
481             t = get_pixel(px, bci.x, bci.y, bci.width);
482             if (compare_pixels(t, orig_color, bci.dtc, bci.threshold, bci.method)) {
483                 for (int i = 0; i < 4; i++) { t[i] = 255 - t[i]; }
484                 trace_t = get_pixel(trace_px, bci.x, bci.y, bci.width);
485                 trace_t[3] = 255; 
486                 if (bci.y > 0) { 
487                     bci.top_fill = try_add_to_queue(fill_queue, px, trace_px, orig_color, bci.dtc, bci.x, bci.y - 1, bci.width, bci.threshold, bci.method, bci.top_fill);
488                 }
489                 if (bci.y < bci.y_limit) { 
490                     bci.bottom_fill = try_add_to_queue(fill_queue, px, trace_px, orig_color, bci.dtc, bci.x, bci.y + 1, bci.width, bci.threshold, bci.method, bci.bottom_fill);
491                 }
492                 if (bci.is_left) {
493                     bci.x--;
494                 } else {
495                     bci.x++;
496                 }
497                 ok = true;
498             }
499         } else {
500             if (bci.bbox.min()[NR::X] > bci.screen.min()[NR::X]) {
501                 aborted = true; break;
502             } else {
503                 reached_screen_boundary = true;
504             }
505         }
506     } while (ok);
507     
508     if (aborted) { return SCANLINE_CHECK_ABORTED; }
509     if (reached_screen_boundary) { return SCANLINE_CHECK_BOUNDARY; }
510     return SCANLINE_CHECK_OK;
513 static void sp_flood_do_flood_fill(SPEventContext *event_context, GdkEvent *event, bool union_with_selection, bool use_rubberband_points) {
514     SPDesktop *desktop = event_context->desktop;
515     SPDocument *document = sp_desktop_document(desktop);
517     /* Create new arena */
518     NRArena *arena = NRArena::create();
519     unsigned dkey = sp_item_display_key_new(1);
521     sp_document_ensure_up_to_date (document);
522     
523     SPItem *document_root = SP_ITEM(SP_DOCUMENT_ROOT(document));
524     NR::Maybe<NR::Rect> bbox = document_root->getBounds(NR::identity());
526     if (!bbox) {
527         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
528         return;
529     }
530     
531     double zoom_scale = desktop->current_zoom();
532     double padding = 1.6;
534     NR::Rect screen = desktop->get_display_area();
536     int width = (int)ceil(screen.extent(NR::X) * zoom_scale * padding);
537     int height = (int)ceil(screen.extent(NR::Y) * zoom_scale * padding);
539     NR::Point origin(screen.min()[NR::X],
540                      sp_document_height(document) - screen.extent(NR::Y) - screen.min()[NR::Y]);
541                     
542     origin[NR::X] = origin[NR::X] + (screen.extent(NR::X) * ((1 - padding) / 2));
543     origin[NR::Y] = origin[NR::Y] + (screen.extent(NR::Y) * ((1 - padding) / 2));
544     
545     NR::scale scale(zoom_scale, zoom_scale);
546     NR::Matrix affine = scale * NR::translate(-origin * scale);
547     
548     /* Create ArenaItems and set transform */
549     NRArenaItem *root = sp_item_invoke_show(SP_ITEM(sp_document_root(document)), arena, dkey, SP_ITEM_SHOW_DISPLAY);
550     nr_arena_item_set_transform(NR_ARENA_ITEM(root), affine);
552     NRGC gc(NULL);
553     nr_matrix_set_identity(&gc.transform);
554     
555     NRRectL final_bbox;
556     final_bbox.x0 = 0;
557     final_bbox.y0 = 0;//row;
558     final_bbox.x1 = width;
559     final_bbox.y1 = height;//row + num_rows;
560     
561     nr_arena_item_invoke_update(root, &final_bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
563     guchar *px = g_new(guchar, 4 * width * height);
564     //memset(px, 0x00, 4 * width * height);
565     
566     NRPixBlock B;
567     nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
568                               final_bbox.x0, final_bbox.y0, final_bbox.x1, final_bbox.y1,
569                               px, 4 * width, FALSE, FALSE );
570     
571     SPNamedView *nv = sp_desktop_namedview(desktop);
572     unsigned long bgcolor = nv->pagecolor;
573     
574     unsigned char dtc[4];
575     dtc[0] = NR_RGBA32_R(bgcolor);
576     dtc[1] = NR_RGBA32_G(bgcolor);
577     dtc[2] = NR_RGBA32_B(bgcolor);
578     dtc[3] = NR_RGBA32_A(bgcolor);
579     
580     for (int fy = 0; fy < height; fy++) {
581         guchar *p = NR_PIXBLOCK_PX(&B) + fy * B.rs;
582         for (int fx = 0; fx < width; fx++) {
583             for (int i = 0; i < 4; i++) { 
584                 *p++ = dtc[i];
585             }
586           }
587       }
589     nr_arena_item_invoke_render(NULL, root, &final_bbox, &B, NR_ARENA_ITEM_RENDER_NO_CACHE );
590     nr_pixblock_release(&B);
591     
592     // Hide items
593     sp_item_invoke_hide(SP_ITEM(sp_document_root(document)), dkey);
594     
595     nr_arena_item_unref(root);
596     nr_object_unref((NRObject *) arena);
597     
598     guchar *trace_px = g_new(guchar, 4 * width * height);
599     memset(trace_px, 0x00, 4 * width * height);
600     
601     std::queue<NR::Point> fill_queue;
602     
603     
604     std::vector<NR::Point> points;
605     
606     if (use_rubberband_points) {
607         Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
608         points = r->getPoints();
609     } else {
610         points.push_back(NR::Point(event->button.x, event->button.y));
611     }
613     for (unsigned int i = 0; i < points.size(); i++) {
614         NR::Point pw = NR::Point(points[i][NR::X] / zoom_scale, sp_document_height(document) + (points[i][NR::Y] / zoom_scale)) * affine;
615         
616         pw[NR::X] = (int)MIN(width - 1, MAX(0, pw[NR::X]));
617         pw[NR::Y] = (int)MIN(height - 1, MAX(0, pw[NR::Y]));
618         
619         fill_queue.push(pw);
620     }
622     NR::Point first_point = NR::Point(points[0][NR::X] / zoom_scale, sp_document_height(document) + (points[0][NR::Y] / zoom_scale)) * affine;
623     
624     unsigned char *orig_px  = get_pixel(px, (int)first_point[NR::X], (int)first_point[NR::Y], width);
625     unsigned char orig_color[4];
626     for (int i = 0; i < 4; i++) { orig_color[i] = orig_px[i]; }
627     
628     bool aborted = false;
629     int y_limit = height - 1;
631     unsigned char merged_orig[4];
633     merge_pixel_with_background(orig_color, dtc, merged_orig);
634     
635     PaintBucketChannels method = (PaintBucketChannels)prefs_get_int_attribute("tools.paintbucket", "channels", 0);
636     int threshold = prefs_get_int_attribute_limited("tools.paintbucket", "threshold", 1, 0, 100);
638     switch(method) {
639         case FLOOD_CHANNELS_ALPHA:
640         case FLOOD_CHANNELS_RGB:
641         case FLOOD_CHANNELS_R:
642         case FLOOD_CHANNELS_G:
643         case FLOOD_CHANNELS_B:
644             threshold = (255 * threshold) / 100;
645             break;
646         case FLOOD_CHANNELS_H:
647         case FLOOD_CHANNELS_S:
648         case FLOOD_CHANNELS_L:
649             break;
650       }
652     bool reached_screen_boundary = false;
654     bitmap_coords_info bci;
655     
656     bci.y_limit = y_limit;
657     bci.width = width;
658     bci.threshold = threshold;
659     bci.method = method;
660     bci.bbox = *bbox;
661     bci.screen = screen;
662     bci.dtc = dtc;
664     while (!fill_queue.empty() && !aborted) {
665         NR::Point cp = fill_queue.front();
666         fill_queue.pop();
667         unsigned char *s = get_pixel(px, (int)cp[NR::X], (int)cp[NR::Y], width);
668         
669         // same color at this point
670         if (compare_pixels(s, orig_color, dtc, threshold, method)) {
671             int x = (int)cp[NR::X];
672             int y = (int)cp[NR::Y];
673             
674             bool top_fill = true;
675             bool bottom_fill = true;
676             
677             if (y > 0) { 
678                 top_fill = try_add_to_queue(&fill_queue, px, trace_px, orig_color, dtc, x, y - 1, width, threshold, method, top_fill);
679             } else {
680                 if (bbox->min()[NR::Y] > screen.min()[NR::Y]) {
681                     aborted = true; break;
682                 } else {
683                     reached_screen_boundary = true;
684                 }
685             }
686             if (y < y_limit) { 
687                 bottom_fill = try_add_to_queue(&fill_queue, px, trace_px, orig_color, dtc, x, y + 1, width, threshold, method, bottom_fill);
688               } else {
689                   if (bbox->max()[NR::Y] < screen.max()[NR::Y]) {
690                       aborted = true; break;
691                   } else {
692                       reached_screen_boundary = true;
693                   }
694             }
695             
696             bci.is_left = true;
697             bci.x = x;
698             bci.y = y;
699             bci.top_fill = top_fill;
700             bci.bottom_fill = bottom_fill;
701             
702             ScanlineCheckResult result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci);
703             
704             switch (result) {
705                 case SCANLINE_CHECK_ABORTED:
706                     aborted = true;
707                     break;
708                 case SCANLINE_CHECK_BOUNDARY:
709                     reached_screen_boundary = true;
710                     break;
711                 default:
712                     break;
713             }
714             
715             bci.is_left = false;
716             bci.x = x + 1;
717             bci.y = y;
718             bci.top_fill = top_fill;
719             bci.bottom_fill = bottom_fill;
720             
721             result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci);
722             
723             switch (result) {
724                 case SCANLINE_CHECK_ABORTED:
725                     aborted = true;
726                     break;
727                 case SCANLINE_CHECK_BOUNDARY:
728                     reached_screen_boundary = true;
729                     break;
730                 default:
731                     break;
732             }
733         }
734     }
735     
736     g_free(px);
737     
738     if (aborted) {
739         g_free(trace_px);
740         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
741         return;
742     }
743     
744     if (reached_screen_boundary) {
745         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.")); 
746     }
747     
748     GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(trace_px,
749                                       GDK_COLORSPACE_RGB,
750                                       TRUE,
751                                       8, width, height, width * 4,
752                                       (GdkPixbufDestroyNotify)g_free,
753                                       NULL);
755     NR::Matrix inverted_affine = NR::Matrix(affine).inverse();
756     
757     do_trace(pixbuf, desktop, inverted_affine, union_with_selection);
759     g_free(trace_px);
760     
761     sp_document_done(document, SP_VERB_CONTEXT_PAINTBUCKET, _("Fill bounded area"));
764 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
766     gint ret = FALSE;
768     SPDesktop *desktop = event_context->desktop;
770     switch (event->type) {
771     case GDK_BUTTON_PRESS:
772         if (event->button.state & GDK_CONTROL_MASK) {
773             NR::Point const button_w(event->button.x,
774                                     event->button.y);
775             
776             SPItem *item = sp_event_context_find_item (desktop, button_w, TRUE, TRUE);
777             
778             Inkscape::XML::Node *pathRepr = SP_OBJECT_REPR(item);
779             /* Set style */
780             sp_desktop_apply_style_tool (desktop, pathRepr, "tools.paintbucket", false);
781             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET, _("Set style on object"));
782             ret = TRUE;
783         }
784         break;
785     default:
786         break;
787     }
789     if (((SPEventContextClass *) parent_class)->item_handler) {
790         ret = ((SPEventContextClass *) parent_class)->item_handler(event_context, item, event);
791     }
793     return ret;
796 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event)
798     gint ret = FALSE;
799     SPDesktop *desktop = event_context->desktop;
801     switch (event->type) {
802     case GDK_BUTTON_PRESS:
803         if ( event->button.button == 1 ) {
804             if (!(event->button.state & GDK_CONTROL_MASK)) {
805                 if (event->button.state & GDK_MOD1_MASK) {
806                     NR::Point const button_pt(event->button.x, event->button.y);
807                     NR::Point const p(desktop->w2d(button_pt));
808                     Inkscape::Rubberband::get()->setMode(RUBBERBAND_MODE_TOUCHPATH);
809                     Inkscape::Rubberband::get()->start(desktop, p);
810                 } else {
811                     // set "busy" cursor
812                     desktop->setWaitingCursor();
813     
814                     if (SP_IS_EVENT_CONTEXT(event_context)) { 
815                         // Since setWaitingCursor runs main loop iterations, we may have already left this tool!
816                         // So check if the tool is valid before doing anything
817     
818                         sp_flood_do_flood_fill(event_context, event, event->button.state & GDK_SHIFT_MASK, false);
819                         
820                         // restore cursor when done; note that it may already be different if e.g. user 
821                         // switched to another tool during interruptible tracing or drawing, in which case do nothing
822                         desktop->clearWaitingCursor();
823         
824                         ret = TRUE;
825                     }
826                 }
827             }
828         }
829     case GDK_MOTION_NOTIFY:
830         if (event->motion.state & GDK_BUTTON1_MASK) {
831             NR::Point const motion_pt(event->motion.x, event->motion.y);
832             NR::Point const p(desktop->w2d(motion_pt));
833             if (Inkscape::Rubberband::get()->is_started()) {
834                 Inkscape::Rubberband::get()->move(p);
835                 event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Draw over</b> areas to add to fill"));
836                 gobble_motion_events(GDK_BUTTON1_MASK);
837             }
838         }
839         break;
841     case GDK_BUTTON_RELEASE:
842         if ( event->button.button == 1 ) {
843             Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
844             if (r->is_started()) {
845                 // set "busy" cursor
846                 desktop->setWaitingCursor();
848                 if (SP_IS_EVENT_CONTEXT(event_context)) { 
849                     // Since setWaitingCursor runs main loop iterations, we may have already left this tool!
850                     // So check if the tool is valid before doing anything
852                     sp_flood_do_flood_fill(event_context, event, event->button.state & GDK_SHIFT_MASK, true);
853                     
854                     // restore cursor when done; note that it may already be different if e.g. user 
855                     // switched to another tool during interruptible tracing or drawing, in which case do nothing
856                     desktop->clearWaitingCursor();
857     
858                     ret = TRUE;
859                 }
860                 r->stop();
861             }
862         }
863         break;
864     case GDK_KEY_PRESS:
865         switch (get_group0_keyval (&event->key)) {
866         case GDK_Up:
867         case GDK_Down:
868         case GDK_KP_Up:
869         case GDK_KP_Down:
870             // prevent the zoom field from activation
871             if (!MOD__CTRL_ONLY)
872                 ret = TRUE;
873             break;
874         default:
875             break;
876         }
877         break;
878     default:
879         break;
880     }
882     if (!ret) {
883         if (((SPEventContextClass *) parent_class)->root_handler) {
884             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
885         }
886     }
888     return ret;
892 static void sp_flood_finish(SPFloodContext *rc)
894     rc->_message_context->clear();
896     if ( rc->item != NULL ) {
897         SPDesktop * desktop;
899         desktop = SP_EVENT_CONTEXT_DESKTOP(rc);
901         SP_OBJECT(rc->item)->updateRepr();
903         sp_canvas_end_forced_full_redraws(desktop->canvas);
905         sp_desktop_selection(desktop)->set(rc->item);
906         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET,
907                         _("Fill bounded area"));
909         rc->item = NULL;
910     }
913 void flood_channels_set_channels( gint channels )
915     prefs_set_int_attribute("tools.paintbucket", "channels", channels);
918 /*
919   Local Variables:
920   mode:c++
921   c-file-style:"stroustrup"
922   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
923   indent-tabs-mode:nil
924   fill-column:99
925   End:
926 */
927 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :