Code

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