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>
22 #include <deque>
24 #include "macros.h"
25 #include "display/sp-canvas.h"
26 #include "document.h"
27 #include "sp-namedview.h"
28 #include "sp-object.h"
29 #include "sp-rect.h"
30 #include "selection.h"
31 #include "desktop-handles.h"
32 #include "desktop.h"
33 #include "desktop-style.h"
34 #include "message-stack.h"
35 #include "message-context.h"
36 #include "pixmaps/cursor-paintbucket.xpm"
37 #include "flood-context.h"
38 #include "sp-metrics.h"
39 #include <glibmm/i18n.h>
40 #include "object-edit.h"
41 #include "xml/repr.h"
42 #include "xml/node-event-vector.h"
43 #include "prefs-utils.h"
44 #include "context-fns.h"
45 #include "rubberband.h"
47 #include "display/nr-arena-item.h"
48 #include "display/nr-arena.h"
49 #include "display/nr-arena-image.h"
50 #include "display/canvas-arena.h"
51 #include "libnr/nr-pixops.h"
52 #include "libnr/nr-matrix-translate-ops.h"
53 #include "libnr/nr-scale-ops.h"
54 #include "libnr/nr-scale-translate-ops.h"
55 #include "libnr/nr-translate-matrix-ops.h"
56 #include "libnr/nr-translate-scale-ops.h"
57 #include "libnr/nr-matrix-ops.h"
58 #include "sp-item.h"
59 #include "sp-root.h"
60 #include "sp-defs.h"
61 #include "sp-path.h"
62 #include "splivarot.h"
63 #include "livarot/Path.h"
64 #include "livarot/Shape.h"
65 #include "libnr/n-art-bpath.h"
66 #include "svg/svg.h"
67 #include "color.h"
69 #include "trace/trace.h"
70 #include "trace/potrace/inkscape-potrace.h"
72 static void sp_flood_context_class_init(SPFloodContextClass *klass);
73 static void sp_flood_context_init(SPFloodContext *flood_context);
74 static void sp_flood_context_dispose(GObject *object);
76 static void sp_flood_context_setup(SPEventContext *ec);
78 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event);
79 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event);
81 static void sp_flood_finish(SPFloodContext *rc);
83 static SPEventContextClass *parent_class;
86 GtkType sp_flood_context_get_type()
87 {
88 static GType type = 0;
89 if (!type) {
90 GTypeInfo info = {
91 sizeof(SPFloodContextClass),
92 NULL, NULL,
93 (GClassInitFunc) sp_flood_context_class_init,
94 NULL, NULL,
95 sizeof(SPFloodContext),
96 4,
97 (GInstanceInitFunc) sp_flood_context_init,
98 NULL, /* value_table */
99 };
100 type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPFloodContext", &info, (GTypeFlags) 0);
101 }
102 return type;
103 }
105 static void sp_flood_context_class_init(SPFloodContextClass *klass)
106 {
107 GObjectClass *object_class = (GObjectClass *) klass;
108 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
110 parent_class = (SPEventContextClass *) g_type_class_peek_parent(klass);
112 object_class->dispose = sp_flood_context_dispose;
114 event_context_class->setup = sp_flood_context_setup;
115 event_context_class->root_handler = sp_flood_context_root_handler;
116 event_context_class->item_handler = sp_flood_context_item_handler;
117 }
119 static void sp_flood_context_init(SPFloodContext *flood_context)
120 {
121 SPEventContext *event_context = SP_EVENT_CONTEXT(flood_context);
123 event_context->cursor_shape = cursor_paintbucket_xpm;
124 event_context->hot_x = 11;
125 event_context->hot_y = 30;
126 event_context->xp = 0;
127 event_context->yp = 0;
128 event_context->tolerance = 4;
129 event_context->within_tolerance = false;
130 event_context->item_to_select = NULL;
132 event_context->shape_repr = NULL;
133 event_context->shape_knot_holder = NULL;
135 flood_context->item = NULL;
137 new (&flood_context->sel_changed_connection) sigc::connection();
138 }
140 static void sp_flood_context_dispose(GObject *object)
141 {
142 SPFloodContext *rc = SP_FLOOD_CONTEXT(object);
143 SPEventContext *ec = SP_EVENT_CONTEXT(object);
145 rc->sel_changed_connection.disconnect();
146 rc->sel_changed_connection.~connection();
148 /* fixme: This is necessary because we do not grab */
149 if (rc->item) {
150 sp_flood_finish(rc);
151 }
153 if (ec->shape_repr) { // remove old listener
154 sp_repr_remove_listener_by_data(ec->shape_repr, ec);
155 Inkscape::GC::release(ec->shape_repr);
156 ec->shape_repr = 0;
157 }
159 if (rc->_message_context) {
160 delete rc->_message_context;
161 }
163 G_OBJECT_CLASS(parent_class)->dispose(object);
164 }
166 static Inkscape::XML::NodeEventVector ec_shape_repr_events = {
167 NULL, /* child_added */
168 NULL, /* child_removed */
169 ec_shape_event_attr_changed,
170 NULL, /* content_changed */
171 NULL /* order_changed */
172 };
174 /**
175 \brief Callback that processes the "changed" signal on the selection;
176 destroys old and creates new knotholder
177 */
178 void sp_flood_context_selection_changed(Inkscape::Selection *selection, gpointer data)
179 {
180 SPFloodContext *rc = SP_FLOOD_CONTEXT(data);
181 SPEventContext *ec = SP_EVENT_CONTEXT(rc);
183 if (ec->shape_repr) { // remove old listener
184 sp_repr_remove_listener_by_data(ec->shape_repr, ec);
185 Inkscape::GC::release(ec->shape_repr);
186 ec->shape_repr = 0;
187 }
189 SPItem *item = selection->singleItem();
190 if (item) {
191 Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
192 if (shape_repr) {
193 ec->shape_repr = shape_repr;
194 Inkscape::GC::anchor(shape_repr);
195 sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
196 }
197 }
198 }
200 static void sp_flood_context_setup(SPEventContext *ec)
201 {
202 SPFloodContext *rc = SP_FLOOD_CONTEXT(ec);
204 if (((SPEventContextClass *) parent_class)->setup) {
205 ((SPEventContextClass *) parent_class)->setup(ec);
206 }
208 SPItem *item = sp_desktop_selection(ec->desktop)->singleItem();
209 if (item) {
210 Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
211 if (shape_repr) {
212 ec->shape_repr = shape_repr;
213 Inkscape::GC::anchor(shape_repr);
214 sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
215 }
216 }
218 rc->sel_changed_connection.disconnect();
219 rc->sel_changed_connection = sp_desktop_selection(ec->desktop)->connectChanged(
220 sigc::bind(sigc::ptr_fun(&sp_flood_context_selection_changed), (gpointer)rc)
221 );
223 rc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
224 }
226 static void
227 merge_pixel_with_background (unsigned char *orig, unsigned char *bg,
228 unsigned char *base)
229 {
230 for (int i = 0; i < 3; i++) {
231 base[i] = (255 * (255 - bg[3])) / 255 + (bg[i] * bg[3]) / 255;
232 base[i] = (base[i] * (255 - orig[3])) / 255 + (orig[i] * orig[3]) / 255;
233 }
234 base[3] = 255;
235 }
237 inline unsigned char * get_pixel(guchar *px, int x, int y, int width) {
238 return px + (x + y * width) * 4;
239 }
241 GList * flood_channels_dropdown_items_list() {
242 GList *glist = NULL;
244 glist = g_list_append (glist, _("Visible Colors"));
245 glist = g_list_append (glist, _("Red"));
246 glist = g_list_append (glist, _("Green"));
247 glist = g_list_append (glist, _("Blue"));
248 glist = g_list_append (glist, _("Hue"));
249 glist = g_list_append (glist, _("Saturation"));
250 glist = g_list_append (glist, _("Lightness"));
251 glist = g_list_append (glist, _("Alpha"));
253 return glist;
254 }
256 GList * flood_autogap_dropdown_items_list() {
257 GList *glist = NULL;
259 glist = g_list_append (glist, _("None"));
260 glist = g_list_append (glist, _("Small"));
261 glist = g_list_append (glist, _("Medium"));
262 glist = g_list_append (glist, _("Large"));
264 return glist;
265 }
267 static bool compare_pixels(unsigned char *check, unsigned char *orig, unsigned char *dtc, int threshold, PaintBucketChannels method) {
268 int diff = 0;
269 float hsl_check[3], hsl_orig[3];
271 if ((method == FLOOD_CHANNELS_H) ||
272 (method == FLOOD_CHANNELS_S) ||
273 (method == FLOOD_CHANNELS_L)) {
274 sp_color_rgb_to_hsl_floatv(hsl_check, check[0] / 255.0, check[1] / 255.0, check[2] / 255.0);
275 sp_color_rgb_to_hsl_floatv(hsl_orig, orig[0] / 255.0, orig[1] / 255.0, orig[2] / 255.0);
276 }
278 switch (method) {
279 case FLOOD_CHANNELS_ALPHA:
280 return ((int)abs(check[3] - orig[3]) <= threshold);
281 case FLOOD_CHANNELS_R:
282 return ((int)abs(check[0] - orig[0]) <= threshold);
283 case FLOOD_CHANNELS_G:
284 return ((int)abs(check[1] - orig[1]) <= threshold);
285 case FLOOD_CHANNELS_B:
286 return ((int)abs(check[2] - orig[2]) <= threshold);
287 case FLOOD_CHANNELS_RGB:
288 unsigned char merged_orig[4];
289 unsigned char merged_check[4];
291 merge_pixel_with_background(orig, dtc, merged_orig);
292 merge_pixel_with_background(check, dtc, merged_check);
294 for (int i = 0; i < 3; i++) {
295 diff += (int)abs(merged_check[i] - merged_orig[i]);
296 }
297 return ((diff / 3) <= ((threshold * 3) / 4));
299 case FLOOD_CHANNELS_H:
300 return ((int)(fabs(hsl_check[0] - hsl_orig[0]) * 100.0) <= threshold);
301 case FLOOD_CHANNELS_S:
302 return ((int)(fabs(hsl_check[1] - hsl_orig[1]) * 100.0) <= threshold);
303 case FLOOD_CHANNELS_L:
304 return ((int)(fabs(hsl_check[2] - hsl_orig[2]) * 100.0) <= threshold);
305 }
307 return false;
308 }
310 static bool try_add_to_queue(std::deque<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, unsigned int max_queue_size) {
311 unsigned char *t = get_pixel(px, x, y, width);
312 if (compare_pixels(t, orig, dtc, threshold, method)) {
313 unsigned char *trace_t = get_pixel(trace_px, x, y, width);
314 if (trace_t[3] != 255 && trace_t[0] != 255) {
315 if (fill_switch && (fill_queue->size() < max_queue_size)) {
316 fill_queue->push_back(NR::Point(x, y));
317 trace_t[0] = 255;
318 }
319 }
320 return false;
321 }
322 return true;
323 }
325 static void do_trace(GdkPixbuf *px, SPDesktop *desktop, NR::Matrix transform, bool union_with_selection) {
326 SPDocument *document = sp_desktop_document(desktop);
328 Inkscape::Trace::Potrace::PotraceTracingEngine pte;
330 pte.setTraceType(Inkscape::Trace::Potrace::TRACE_BRIGHTNESS);
331 pte.setInvert(false);
333 Glib::RefPtr<Gdk::Pixbuf> pixbuf = Glib::wrap(px, true);
335 std::vector<Inkscape::Trace::TracingEngineResult> results = pte.trace(pixbuf);
337 Inkscape::XML::Node *layer_repr = SP_GROUP(desktop->currentLayer())->repr;
338 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
340 long totalNodeCount = 0L;
342 double offset = prefs_get_double_attribute("tools.paintbucket", "offset", 0.0);
344 for (unsigned int i=0 ; i<results.size() ; i++) {
345 Inkscape::Trace::TracingEngineResult result = results[i];
346 totalNodeCount += result.getNodeCount();
348 Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path");
349 /* Set style */
350 sp_desktop_apply_style_tool (desktop, pathRepr, "tools.paintbucket", false);
352 NArtBpath *bpath = sp_svg_read_path(result.getPathData().c_str());
353 Path *path = bpath_to_Path(bpath);
354 g_free(bpath);
356 if (offset != 0) {
358 Shape *path_shape = new Shape();
360 path->ConvertWithBackData(0.03);
361 path->Fill(path_shape, 0);
362 delete path;
364 Shape *expanded_path_shape = new Shape();
366 expanded_path_shape->ConvertToShape(path_shape, fill_nonZero);
367 path_shape->MakeOffset(expanded_path_shape, offset * desktop->current_zoom(), join_round, 4);
368 expanded_path_shape->ConvertToShape(path_shape, fill_positive);
370 Path *expanded_path = new Path();
372 expanded_path->Reset();
373 expanded_path_shape->ConvertToForme(expanded_path);
374 expanded_path->ConvertEvenLines(1.0);
375 expanded_path->Simplify(1.0);
377 delete path_shape;
378 delete expanded_path_shape;
380 gchar *str = expanded_path->svg_dump_path();
381 if (str && *str) {
382 pathRepr->setAttribute("d", str);
383 g_free(str);
384 } else {
385 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Too much inset</b>, the result is empty."));
386 Inkscape::GC::release(pathRepr);
387 g_free(str);
388 return;
389 }
391 delete expanded_path;
393 } else {
394 gchar *str = path->svg_dump_path();
395 delete path;
396 pathRepr->setAttribute("d", str);
397 g_free(str);
398 }
400 layer_repr->addChild(pathRepr, NULL);
402 SPObject *reprobj = document->getObjectByRepr(pathRepr);
403 if (reprobj) {
404 sp_item_write_transform(SP_ITEM(reprobj), pathRepr, transform, NULL);
406 // premultiply the item transform by the accumulated parent transform in the paste layer
407 NR::Matrix local = sp_item_i2doc_affine(SP_GROUP(desktop->currentLayer()));
408 if (!local.test_identity()) {
409 gchar const *t_str = pathRepr->attribute("transform");
410 NR::Matrix item_t (NR::identity());
411 if (t_str)
412 sp_svg_transform_read(t_str, &item_t);
413 item_t *= local.inverse();
414 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
415 gchar *affinestr=sp_svg_transform_write(item_t);
416 pathRepr->setAttribute("transform", affinestr);
417 g_free(affinestr);
418 }
420 Inkscape::Selection *selection = sp_desktop_selection(desktop);
422 pathRepr->setPosition(-1);
424 if (union_with_selection) {
425 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)));
426 selection->add(reprobj);
427 sp_selected_path_union_skip_undo();
428 } else {
429 desktop->messageStack()->flashF(Inkscape::WARNING_MESSAGE, _("Area filled, path with <b>%d</b> nodes created."), sp_nodes_in_path(SP_PATH(reprobj)));
430 selection->set(reprobj);
431 }
433 }
435 Inkscape::GC::release(pathRepr);
437 }
438 }
440 struct bitmap_coords_info {
441 bool is_left;
442 int x;
443 int y;
444 int y_limit;
445 int width;
446 int height;
447 int threshold;
448 int radius;
449 PaintBucketChannels method;
450 unsigned char *dtc;
451 bool top_fill;
452 bool bottom_fill;
453 NR::Rect bbox;
454 NR::Rect screen;
455 };
457 enum ScanlineCheckResult {
458 SCANLINE_CHECK_OK,
459 SCANLINE_CHECK_ABORTED,
460 SCANLINE_CHECK_BOUNDARY
461 };
463 static void paint_pixel(guchar *px, guchar *trace_px, unsigned char *orig_color, bitmap_coords_info bci) {
464 unsigned char *t, *trace_t;
466 for (int r = 0; r <= bci.radius; r++) {
467 if (r == 0) {
468 t = get_pixel(px, bci.x, bci.y, bci.width);
469 if (compare_pixels(t, orig_color, bci.dtc, bci.threshold, bci.method)) {
470 for (int i = 0; i < 4; i++) { t[i] = 255 - t[i]; }
471 trace_t = get_pixel(trace_px, bci.x, bci.y, bci.width);
472 trace_t[3] = 255;
473 }
474 } else {
475 for (int y = -bci.radius; y <= bci.radius; y++) {
476 for (int x = -bci.radius; x <= bci.radius; x++) {
477 int tx = bci.x + x;
478 int ty = bci.y + y;
480 if ( (tx >= 0)
481 && (tx < bci.width)
482 && (ty >= 0)
483 && (ty < bci.height)) {
484 t = get_pixel(px, tx, ty, bci.width);
485 if (compare_pixels(t, orig_color, bci.dtc, bci.threshold, bci.method)) {
486 for (int i = 0; i < 4; i++) { t[i] = 255 - t[i]; }
487 trace_t = get_pixel(trace_px, tx, ty, bci.width);
488 trace_t[3] = 255;
489 }
490 }
491 }
492 }
493 }
494 }
495 }
497 static ScanlineCheckResult perform_bitmap_scanline_check(std::deque<NR::Point> *fill_queue, guchar *px, guchar *trace_px, unsigned char *orig_color, bitmap_coords_info bci) {
498 bool aborted = false;
499 bool reached_screen_boundary = false;
500 bool ok;
502 bool keep_tracing;
503 unsigned char *t;
505 unsigned int max_queue_size = bci.width * bci.height;
507 do {
508 ok = false;
509 if (bci.is_left) {
510 keep_tracing = (bci.x >= 0);
511 } else {
512 keep_tracing = (bci.x < bci.width);
513 }
515 if (keep_tracing) {
516 t = get_pixel(px, bci.x, bci.y, bci.width);
517 if (compare_pixels(t, orig_color, bci.dtc, bci.threshold, bci.method)) {
518 paint_pixel(px, trace_px, orig_color, bci);
519 if (bci.y > 0) {
520 bci.top_fill = try_add_to_queue(fill_queue, px, trace_px, orig_color, bci.dtc, bci.x, bci.y - (1 + bci.radius), bci.width, bci.threshold, bci.method, bci.top_fill, max_queue_size);
521 }
522 if (bci.y < bci.y_limit) {
523 bci.bottom_fill = try_add_to_queue(fill_queue, px, trace_px, orig_color, bci.dtc, bci.x, bci.y + (1 + bci.radius), bci.width, bci.threshold, bci.method, bci.bottom_fill, max_queue_size);
524 }
525 if (bci.is_left) {
526 bci.x -= (1 + bci.radius);
527 } else {
528 bci.x += (1 + bci.radius);
529 }
530 ok = true;
531 }
532 } else {
533 if (bci.bbox.min()[NR::X] > bci.screen.min()[NR::X]) {
534 aborted = true; break;
535 } else {
536 reached_screen_boundary = true;
537 }
538 }
539 } while (ok);
541 if (aborted) { return SCANLINE_CHECK_ABORTED; }
542 if (reached_screen_boundary) { return SCANLINE_CHECK_BOUNDARY; }
543 return SCANLINE_CHECK_OK;
544 }
546 static void sp_flood_do_flood_fill(SPEventContext *event_context, GdkEvent *event, bool union_with_selection, bool is_point_fill, bool is_touch_fill) {
547 SPDesktop *desktop = event_context->desktop;
548 SPDocument *document = sp_desktop_document(desktop);
550 /* Create new arena */
551 NRArena *arena = NRArena::create();
552 unsigned dkey = sp_item_display_key_new(1);
554 sp_document_ensure_up_to_date (document);
556 SPItem *document_root = SP_ITEM(SP_DOCUMENT_ROOT(document));
557 NR::Maybe<NR::Rect> bbox = document_root->getBounds(NR::identity());
559 if (!bbox) {
560 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
561 return;
562 }
564 double zoom_scale = desktop->current_zoom();
565 double padding = 1.6;
567 NR::Rect screen = desktop->get_display_area();
569 int width = (int)ceil(screen.extent(NR::X) * zoom_scale * padding);
570 int height = (int)ceil(screen.extent(NR::Y) * zoom_scale * padding);
572 NR::Point origin(screen.min()[NR::X],
573 sp_document_height(document) - screen.extent(NR::Y) - screen.min()[NR::Y]);
575 origin[NR::X] = origin[NR::X] + (screen.extent(NR::X) * ((1 - padding) / 2));
576 origin[NR::Y] = origin[NR::Y] + (screen.extent(NR::Y) * ((1 - padding) / 2));
578 NR::scale scale(zoom_scale, zoom_scale);
579 NR::Matrix affine = scale * NR::translate(-origin * scale);
581 /* Create ArenaItems and set transform */
582 NRArenaItem *root = sp_item_invoke_show(SP_ITEM(sp_document_root(document)), arena, dkey, SP_ITEM_SHOW_DISPLAY);
583 nr_arena_item_set_transform(NR_ARENA_ITEM(root), affine);
585 NRGC gc(NULL);
586 nr_matrix_set_identity(&gc.transform);
588 NRRectL final_bbox;
589 final_bbox.x0 = 0;
590 final_bbox.y0 = 0;//row;
591 final_bbox.x1 = width;
592 final_bbox.y1 = height;//row + num_rows;
594 nr_arena_item_invoke_update(root, &final_bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
596 guchar *px = g_new(guchar, 4 * width * height);
598 NRPixBlock B;
599 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
600 final_bbox.x0, final_bbox.y0, final_bbox.x1, final_bbox.y1,
601 px, 4 * width, FALSE, FALSE );
603 SPNamedView *nv = sp_desktop_namedview(desktop);
604 unsigned long bgcolor = nv->pagecolor;
606 unsigned char dtc[4];
607 dtc[0] = NR_RGBA32_R(bgcolor);
608 dtc[1] = NR_RGBA32_G(bgcolor);
609 dtc[2] = NR_RGBA32_B(bgcolor);
610 dtc[3] = NR_RGBA32_A(bgcolor);
612 for (int fy = 0; fy < height; fy++) {
613 guchar *p = NR_PIXBLOCK_PX(&B) + fy * B.rs;
614 for (int fx = 0; fx < width; fx++) {
615 for (int i = 0; i < 4; i++) {
616 *p++ = dtc[i];
617 }
618 }
619 }
621 nr_arena_item_invoke_render(NULL, root, &final_bbox, &B, NR_ARENA_ITEM_RENDER_NO_CACHE );
622 nr_pixblock_release(&B);
624 // Hide items
625 sp_item_invoke_hide(SP_ITEM(sp_document_root(document)), dkey);
627 nr_arena_item_unref(root);
628 nr_object_unref((NRObject *) arena);
630 guchar *trace_px = g_new(guchar, 4 * width * height);
631 memset(trace_px, 0x00, 4 * width * height);
633 std::deque<NR::Point> fill_queue;
634 std::queue<NR::Point> color_queue;
636 std::vector<NR::Point> fill_points;
638 if (is_point_fill) {
639 fill_points.push_back(NR::Point(event->button.x, event->button.y));
640 } else {
641 Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
642 fill_points = r->getPoints();
643 }
645 for (unsigned int i = 0; i < fill_points.size(); i++) {
646 NR::Point pw = NR::Point(fill_points[i][NR::X] / zoom_scale, sp_document_height(document) + (fill_points[i][NR::Y] / zoom_scale)) * affine;
648 pw[NR::X] = (int)MIN(width - 1, MAX(0, pw[NR::X]));
649 pw[NR::Y] = (int)MIN(height - 1, MAX(0, pw[NR::Y]));
651 if (is_touch_fill) {
652 if (i == 0) {
653 color_queue.push(pw);
654 } else {
655 fill_queue.push_back(pw);
656 }
657 } else {
658 color_queue.push(pw);
659 }
660 }
662 bool aborted = false;
663 int y_limit = height - 1;
665 PaintBucketChannels method = (PaintBucketChannels)prefs_get_int_attribute("tools.paintbucket", "channels", 0);
666 int threshold = prefs_get_int_attribute_limited("tools.paintbucket", "threshold", 1, 0, 100);
668 switch(method) {
669 case FLOOD_CHANNELS_ALPHA:
670 case FLOOD_CHANNELS_RGB:
671 case FLOOD_CHANNELS_R:
672 case FLOOD_CHANNELS_G:
673 case FLOOD_CHANNELS_B:
674 threshold = (255 * threshold) / 100;
675 break;
676 case FLOOD_CHANNELS_H:
677 case FLOOD_CHANNELS_S:
678 case FLOOD_CHANNELS_L:
679 break;
680 }
682 bool reached_screen_boundary = false;
684 bitmap_coords_info bci;
686 bci.y_limit = y_limit;
687 bci.width = width;
688 bci.height = height;
689 bci.threshold = threshold;
690 bci.method = method;
691 bci.bbox = *bbox;
692 bci.screen = screen;
693 bci.dtc = dtc;
694 bci.radius = prefs_get_int_attribute_limited("tools.paintbucket", "autogap", 0, 0, 3);
696 unsigned int max_queue_size = width * height;
698 while (!color_queue.empty() && !aborted) {
699 NR::Point color_point = color_queue.front();
700 color_queue.pop();
702 unsigned char *orig_px = get_pixel(px, (int)color_point[NR::X], (int)color_point[NR::Y], width);
703 unsigned char orig_color[4];
704 for (int i = 0; i < 4; i++) { orig_color[i] = orig_px[i]; }
706 unsigned char merged_orig[4];
708 merge_pixel_with_background(orig_color, dtc, merged_orig);
710 unsigned char *trace_t = get_pixel(trace_px, (int)color_point[NR::X], (int)color_point[NR::Y], width);
711 if ((trace_t[0] != 255) && (trace_t[3] != 255)) {
712 fill_queue.push_front(color_point);
713 }
715 while (!fill_queue.empty() && !aborted) {
716 NR::Point cp = fill_queue.front();
717 fill_queue.pop_front();
719 unsigned char *s = get_pixel(px, (int)cp[NR::X], (int)cp[NR::Y], width);
721 // same color at this point
722 if (compare_pixels(s, orig_color, dtc, threshold, method)) {
723 int x = (int)cp[NR::X];
724 int y = (int)cp[NR::Y];
726 bool top_fill = true;
727 bool bottom_fill = true;
729 if (y > 0) {
730 top_fill = try_add_to_queue(&fill_queue, px, trace_px, orig_color, dtc, x, y - (1 + bci.radius), width, threshold, method, top_fill, max_queue_size);
731 } else {
732 if (bbox->min()[NR::Y] > screen.min()[NR::Y]) {
733 aborted = true; break;
734 } else {
735 reached_screen_boundary = true;
736 }
737 }
738 if (y < y_limit) {
739 bottom_fill = try_add_to_queue(&fill_queue, px, trace_px, orig_color, dtc, x, y + (1 + bci.radius), width, threshold, method, bottom_fill, max_queue_size);
740 } else {
741 if (bbox->max()[NR::Y] < screen.max()[NR::Y]) {
742 aborted = true; break;
743 } else {
744 reached_screen_boundary = true;
745 }
746 }
748 bci.is_left = true;
749 bci.x = x;
750 bci.y = y;
751 bci.top_fill = top_fill;
752 bci.bottom_fill = bottom_fill;
754 ScanlineCheckResult result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci);
756 switch (result) {
757 case SCANLINE_CHECK_ABORTED:
758 aborted = true;
759 break;
760 case SCANLINE_CHECK_BOUNDARY:
761 reached_screen_boundary = true;
762 break;
763 default:
764 break;
765 }
767 bci.is_left = false;
768 bci.x = x + (1 + bci.radius);
769 bci.y = y;
770 bci.top_fill = top_fill;
771 bci.bottom_fill = bottom_fill;
773 result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci);
775 switch (result) {
776 case SCANLINE_CHECK_ABORTED:
777 aborted = true;
778 break;
779 case SCANLINE_CHECK_BOUNDARY:
780 reached_screen_boundary = true;
781 break;
782 default:
783 break;
784 }
785 }
786 }
787 }
789 g_free(px);
791 if (aborted) {
792 g_free(trace_px);
793 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
794 return;
795 }
797 if (reached_screen_boundary) {
798 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."));
799 }
801 GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(trace_px,
802 GDK_COLORSPACE_RGB,
803 TRUE,
804 8, width, height, width * 4,
805 (GdkPixbufDestroyNotify)g_free,
806 NULL);
808 NR::Matrix inverted_affine = NR::Matrix(affine).inverse();
810 do_trace(pixbuf, desktop, inverted_affine, union_with_selection);
812 g_free(trace_px);
814 sp_document_done(document, SP_VERB_CONTEXT_PAINTBUCKET, _("Fill bounded area"));
815 }
817 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
818 {
819 gint ret = FALSE;
821 SPDesktop *desktop = event_context->desktop;
823 switch (event->type) {
824 case GDK_BUTTON_PRESS:
825 if (event->button.state & GDK_CONTROL_MASK) {
826 NR::Point const button_w(event->button.x,
827 event->button.y);
829 SPItem *item = sp_event_context_find_item (desktop, button_w, TRUE, TRUE);
831 Inkscape::XML::Node *pathRepr = SP_OBJECT_REPR(item);
832 /* Set style */
833 sp_desktop_apply_style_tool (desktop, pathRepr, "tools.paintbucket", false);
834 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET, _("Set style on object"));
835 ret = TRUE;
836 }
837 break;
838 default:
839 break;
840 }
842 if (((SPEventContextClass *) parent_class)->item_handler) {
843 ret = ((SPEventContextClass *) parent_class)->item_handler(event_context, item, event);
844 }
846 return ret;
847 }
849 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event)
850 {
851 static bool dragging;
853 gint ret = FALSE;
854 SPDesktop *desktop = event_context->desktop;
856 switch (event->type) {
857 case GDK_BUTTON_PRESS:
858 if ( event->button.button == 1 ) {
859 if (!(event->button.state & GDK_CONTROL_MASK)) {
860 NR::Point const button_w(event->button.x,
861 event->button.y);
863 if (Inkscape::have_viable_layer(desktop, event_context->defaultMessageContext())) {
864 // save drag origin
865 event_context->xp = (gint) button_w[NR::X];
866 event_context->yp = (gint) button_w[NR::Y];
867 event_context->within_tolerance = true;
869 dragging = true;
871 NR::Point const p(desktop->w2d(button_w));
872 Inkscape::Rubberband::get()->setMode(RUBBERBAND_MODE_TOUCHPATH);
873 Inkscape::Rubberband::get()->start(desktop, p);
874 }
875 }
876 }
877 case GDK_MOTION_NOTIFY:
878 if ( dragging
879 && ( event->motion.state & GDK_BUTTON1_MASK ) )
880 {
881 if ( event_context->within_tolerance
882 && ( abs( (gint) event->motion.x - event_context->xp ) < event_context->tolerance )
883 && ( abs( (gint) event->motion.y - event_context->yp ) < event_context->tolerance ) ) {
884 break; // do not drag if we're within tolerance from origin
885 }
887 event_context->within_tolerance = false;
889 NR::Point const motion_pt(event->motion.x, event->motion.y);
890 NR::Point const p(desktop->w2d(motion_pt));
891 if (Inkscape::Rubberband::get()->is_started()) {
892 Inkscape::Rubberband::get()->move(p);
893 event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Draw over</b> areas to add to fill, hold <b>Alt</b> for touch fill"));
894 gobble_motion_events(GDK_BUTTON1_MASK);
895 }
896 }
897 break;
899 case GDK_BUTTON_RELEASE:
900 if ( event->button.button == 1 ) {
901 Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
902 if (r->is_started()) {
903 // set "busy" cursor
904 desktop->setWaitingCursor();
906 if (SP_IS_EVENT_CONTEXT(event_context)) {
907 // Since setWaitingCursor runs main loop iterations, we may have already left this tool!
908 // So check if the tool is valid before doing anything
909 dragging = false;
911 bool is_point_fill = event_context->within_tolerance;
912 bool is_touch_fill = event->button.state & GDK_MOD1_MASK;
914 sp_flood_do_flood_fill(event_context, event, event->button.state & GDK_SHIFT_MASK, is_point_fill, is_touch_fill);
916 desktop->clearWaitingCursor();
917 // restore cursor when done; note that it may already be different if e.g. user
918 // switched to another tool during interruptible tracing or drawing, in which case do nothing
920 ret = TRUE;
921 }
923 r->stop();
924 event_context->defaultMessageContext()->clear();
925 }
926 }
927 break;
928 case GDK_KEY_PRESS:
929 switch (get_group0_keyval (&event->key)) {
930 case GDK_Up:
931 case GDK_Down:
932 case GDK_KP_Up:
933 case GDK_KP_Down:
934 // prevent the zoom field from activation
935 if (!MOD__CTRL_ONLY)
936 ret = TRUE;
937 break;
938 default:
939 break;
940 }
941 break;
942 default:
943 break;
944 }
946 if (!ret) {
947 if (((SPEventContextClass *) parent_class)->root_handler) {
948 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
949 }
950 }
952 return ret;
953 }
956 static void sp_flood_finish(SPFloodContext *rc)
957 {
958 rc->_message_context->clear();
960 if ( rc->item != NULL ) {
961 SPDesktop * desktop;
963 desktop = SP_EVENT_CONTEXT_DESKTOP(rc);
965 SP_OBJECT(rc->item)->updateRepr();
967 sp_canvas_end_forced_full_redraws(desktop->canvas);
969 sp_desktop_selection(desktop)->set(rc->item);
970 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET,
971 _("Fill bounded area"));
973 rc->item = NULL;
974 }
975 }
977 void flood_channels_set_channels( gint channels )
978 {
979 prefs_set_int_attribute("tools.paintbucket", "channels", channels);
980 }
982 /*
983 Local Variables:
984 mode:c++
985 c-file-style:"stroustrup"
986 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
987 indent-tabs-mode:nil
988 fill-column:99
989 End:
990 */
991 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :