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 inline static void
227 merge_pixel_with_background (unsigned char *orig, unsigned char *bg,
228 unsigned char *base)
229 {
230 int precalc_bg_alpha = (255 * (255 - bg[3])) / 255;
232 for (int i = 0; i < 3; i++) {
233 base[i] = precalc_bg_alpha + (bg[i] * bg[3]) / 255;
234 base[i] = (base[i] * (255 - orig[3])) / 255 + (orig[i] * orig[3]) / 255;
235 }
236 }
238 inline unsigned char * get_pixel(guchar *px, int x, int y, int width) {
239 return px + (x + y * width) * 4;
240 }
242 GList * flood_channels_dropdown_items_list() {
243 GList *glist = NULL;
245 glist = g_list_append (glist, _("Visible Colors"));
246 glist = g_list_append (glist, _("Red"));
247 glist = g_list_append (glist, _("Green"));
248 glist = g_list_append (glist, _("Blue"));
249 glist = g_list_append (glist, _("Hue"));
250 glist = g_list_append (glist, _("Saturation"));
251 glist = g_list_append (glist, _("Lightness"));
252 glist = g_list_append (glist, _("Alpha"));
254 return glist;
255 }
257 GList * flood_autogap_dropdown_items_list() {
258 GList *glist = NULL;
260 glist = g_list_append (glist, _("None"));
261 glist = g_list_append (glist, _("Small"));
262 glist = g_list_append (glist, _("Medium"));
263 glist = g_list_append (glist, _("Large"));
265 return glist;
266 }
268 static bool compare_pixels(unsigned char *check, unsigned char *orig, unsigned char *merged_orig_pixel, unsigned char *dtc, int threshold, PaintBucketChannels method) {
269 int diff = 0;
270 float hsl_check[3], hsl_orig[3];
272 if ((method == FLOOD_CHANNELS_H) ||
273 (method == FLOOD_CHANNELS_S) ||
274 (method == FLOOD_CHANNELS_L)) {
275 sp_color_rgb_to_hsl_floatv(hsl_check, check[0] / 255.0, check[1] / 255.0, check[2] / 255.0);
276 sp_color_rgb_to_hsl_floatv(hsl_orig, orig[0] / 255.0, orig[1] / 255.0, orig[2] / 255.0);
277 }
279 switch (method) {
280 case FLOOD_CHANNELS_ALPHA:
281 return ((int)abs(check[3] - orig[3]) <= threshold);
282 case FLOOD_CHANNELS_R:
283 return ((int)abs(check[0] - orig[0]) <= threshold);
284 case FLOOD_CHANNELS_G:
285 return ((int)abs(check[1] - orig[1]) <= threshold);
286 case FLOOD_CHANNELS_B:
287 return ((int)abs(check[2] - orig[2]) <= threshold);
288 case FLOOD_CHANNELS_RGB:
289 unsigned char merged_check[3];
291 merge_pixel_with_background(check, dtc, merged_check);
293 for (int i = 0; i < 3; i++) {
294 diff += (int)abs(merged_check[i] - merged_orig_pixel[i]);
295 }
296 return ((diff / 3) <= ((threshold * 3) / 4));
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 }
306 return false;
307 }
309 static inline bool is_pixel_checked(unsigned char *t) { return t[0] == 1; }
310 static inline bool is_pixel_queued(unsigned char *t) { return t[1] == 1; }
311 static inline bool is_pixel_paintability_checked(unsigned char *t) { return t[2] != 0; }
312 static inline bool is_pixel_paintable(unsigned char *t) { return t[2] == 1; }
313 static inline bool is_pixel_colored(unsigned char *t) { return t[3] == 255; }
315 static inline void mark_pixel_checked(unsigned char *t) { t[0] = 1; }
316 static inline void mark_pixel_unchecked(unsigned char *t) { t[0] = 0; }
317 static inline void mark_pixel_queued(unsigned char *t) { t[1] = 1; }
318 static inline void mark_pixel_paintable(unsigned char *t) { t[2] = 1; }
319 static inline void mark_pixel_not_paintable(unsigned char *t) { t[2] = 2; }
320 static inline void mark_pixel_colored(unsigned char *t) { t[3] = 255; }
322 static inline void clear_pixel_paintability(unsigned char *t) { t[2] = 0; }
324 struct bitmap_coords_info {
325 bool is_left;
326 unsigned int x;
327 unsigned int y;
328 int y_limit;
329 unsigned int width;
330 unsigned int height;
331 unsigned int threshold;
332 unsigned int radius;
333 PaintBucketChannels method;
334 unsigned char *dtc;
335 unsigned char *merged_orig_pixel;
336 NR::Rect bbox;
337 NR::Rect screen;
338 unsigned int max_queue_size;
339 unsigned int current_step;
340 };
342 inline static bool check_if_pixel_is_paintable(guchar *px, unsigned char *trace_t, int x, int y, unsigned char *orig_color, bitmap_coords_info bci) {
343 if (is_pixel_paintability_checked(trace_t)) {
344 return is_pixel_paintable(trace_t);
345 } else {
346 unsigned char *t = get_pixel(px, x, y, bci.width);
347 if (compare_pixels(t, orig_color, bci.merged_orig_pixel, bci.dtc, bci.threshold, bci.method)) {
348 mark_pixel_paintable(trace_t);
349 return true;
350 } else {
351 mark_pixel_not_paintable(trace_t);
352 return false;
353 }
354 }
355 }
357 static void do_trace(GdkPixbuf *px, SPDesktop *desktop, NR::Matrix transform, bool union_with_selection) {
358 SPDocument *document = sp_desktop_document(desktop);
360 Inkscape::Trace::Potrace::PotraceTracingEngine pte;
362 pte.setTraceType(Inkscape::Trace::Potrace::TRACE_BRIGHTNESS);
363 pte.setInvert(false);
365 Glib::RefPtr<Gdk::Pixbuf> pixbuf = Glib::wrap(px, true);
367 std::vector<Inkscape::Trace::TracingEngineResult> results = pte.trace(pixbuf);
369 Inkscape::XML::Node *layer_repr = SP_GROUP(desktop->currentLayer())->repr;
370 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
372 long totalNodeCount = 0L;
374 double offset = prefs_get_double_attribute("tools.paintbucket", "offset", 0.0);
376 for (unsigned int i=0 ; i<results.size() ; i++) {
377 Inkscape::Trace::TracingEngineResult result = results[i];
378 totalNodeCount += result.getNodeCount();
380 Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path");
381 /* Set style */
382 sp_desktop_apply_style_tool (desktop, pathRepr, "tools.paintbucket", false);
384 NArtBpath *bpath = sp_svg_read_path(result.getPathData().c_str());
385 Path *path = bpath_to_Path(bpath);
386 g_free(bpath);
388 if (offset != 0) {
390 Shape *path_shape = new Shape();
392 path->ConvertWithBackData(0.03);
393 path->Fill(path_shape, 0);
394 delete path;
396 Shape *expanded_path_shape = new Shape();
398 expanded_path_shape->ConvertToShape(path_shape, fill_nonZero);
399 path_shape->MakeOffset(expanded_path_shape, offset * desktop->current_zoom(), join_round, 4);
400 expanded_path_shape->ConvertToShape(path_shape, fill_positive);
402 Path *expanded_path = new Path();
404 expanded_path->Reset();
405 expanded_path_shape->ConvertToForme(expanded_path);
406 expanded_path->ConvertEvenLines(1.0);
407 expanded_path->Simplify(1.0);
409 delete path_shape;
410 delete expanded_path_shape;
412 gchar *str = expanded_path->svg_dump_path();
413 if (str && *str) {
414 pathRepr->setAttribute("d", str);
415 g_free(str);
416 } else {
417 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Too much inset</b>, the result is empty."));
418 Inkscape::GC::release(pathRepr);
419 g_free(str);
420 return;
421 }
423 delete expanded_path;
425 } else {
426 gchar *str = path->svg_dump_path();
427 delete path;
428 pathRepr->setAttribute("d", str);
429 g_free(str);
430 }
432 layer_repr->addChild(pathRepr, NULL);
434 SPObject *reprobj = document->getObjectByRepr(pathRepr);
435 if (reprobj) {
436 sp_item_write_transform(SP_ITEM(reprobj), pathRepr, transform, NULL);
438 // premultiply the item transform by the accumulated parent transform in the paste layer
439 NR::Matrix local = sp_item_i2doc_affine(SP_GROUP(desktop->currentLayer()));
440 if (!local.test_identity()) {
441 gchar const *t_str = pathRepr->attribute("transform");
442 NR::Matrix item_t (NR::identity());
443 if (t_str)
444 sp_svg_transform_read(t_str, &item_t);
445 item_t *= local.inverse();
446 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
447 gchar *affinestr=sp_svg_transform_write(item_t);
448 pathRepr->setAttribute("transform", affinestr);
449 g_free(affinestr);
450 }
452 Inkscape::Selection *selection = sp_desktop_selection(desktop);
454 pathRepr->setPosition(-1);
456 if (union_with_selection) {
457 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)));
458 selection->add(reprobj);
459 sp_selected_path_union_skip_undo();
460 } else {
461 desktop->messageStack()->flashF(Inkscape::WARNING_MESSAGE, _("Area filled, path with <b>%d</b> nodes created."), sp_nodes_in_path(SP_PATH(reprobj)));
462 selection->set(reprobj);
463 }
465 }
467 Inkscape::GC::release(pathRepr);
469 }
470 }
472 enum ScanlineCheckResult {
473 SCANLINE_CHECK_OK,
474 SCANLINE_CHECK_ABORTED,
475 SCANLINE_CHECK_BOUNDARY
476 };
478 inline static bool coords_in_range(unsigned int x, unsigned int y, bitmap_coords_info bci) {
479 return (x < bci.width) &&
480 (y < bci.height);
481 }
483 #define PAINT_DIRECTION_LEFT 1
484 #define PAINT_DIRECTION_RIGHT 2
485 #define PAINT_DIRECTION_UP 4
486 #define PAINT_DIRECTION_DOWN 8
487 #define PAINT_DIRECTION_ALL 15
489 inline static unsigned int paint_pixel(guchar *px, guchar *trace_px, unsigned char *orig_color, bitmap_coords_info bci, unsigned char *original_point_trace_t) {
490 if (bci.radius == 0) {
491 mark_pixel_colored(original_point_trace_t);
492 return PAINT_DIRECTION_ALL;
493 } else {
494 unsigned char *trace_t;
496 bool can_paint_up = true;
497 bool can_paint_down = true;
498 bool can_paint_left = true;
499 bool can_paint_right = true;
501 for (unsigned int ty = bci.y - bci.radius; ty <= bci.y + bci.radius; ty++) {
502 for (unsigned int tx = bci.x - bci.radius; tx <= bci.x + bci.radius; tx++) {
503 if (coords_in_range(tx, ty, bci)) {
504 trace_t = get_pixel(trace_px, tx, ty, bci.width);
505 if (!is_pixel_colored(trace_t)) {
506 if (check_if_pixel_is_paintable(px, trace_t, tx, ty, orig_color, bci)) {
507 mark_pixel_colored(trace_t);
508 } else {
509 if (tx < bci.x) { can_paint_left = false; }
510 if (tx > bci.x) { can_paint_right = false; }
511 if (ty < bci.y) { can_paint_up = false; }
512 if (ty > bci.y) { can_paint_down = false; }
513 }
514 }
515 }
516 }
517 }
519 unsigned int paint_directions = 0;
520 if (can_paint_left) { paint_directions += PAINT_DIRECTION_LEFT; }
521 if (can_paint_right) { paint_directions += PAINT_DIRECTION_RIGHT; }
522 if (can_paint_up) { paint_directions += PAINT_DIRECTION_UP; }
523 if (can_paint_down) { paint_directions += PAINT_DIRECTION_DOWN; }
525 return paint_directions;
526 }
527 }
529 static void push_point_onto_queue(std::deque<NR::Point> *fill_queue, unsigned int max_queue_size, unsigned char *trace_t, unsigned int x, unsigned int y) {
530 if (!is_pixel_queued(trace_t)) {
531 if ((fill_queue->size() < max_queue_size)) {
532 fill_queue->push_back(NR::Point(x, y));
533 mark_pixel_queued(trace_t);
534 }
535 }
536 }
538 static void shift_point_onto_queue(std::deque<NR::Point> *fill_queue, unsigned int max_queue_size, unsigned char *trace_t, unsigned int x, unsigned int y) {
539 if (!is_pixel_queued(trace_t)) {
540 if ((fill_queue->size() < max_queue_size)) {
541 fill_queue->push_front(NR::Point(x, y));
542 mark_pixel_queued(trace_t);
543 }
544 }
545 }
547 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) {
548 bool aborted = false;
549 bool reached_screen_boundary = false;
550 bool ok;
552 bool keep_tracing;
553 bool initial_paint = true;
555 unsigned char *current_trace_t = get_pixel(trace_px, bci.x, bci.y, bci.width);
556 unsigned int paint_directions;
558 bool currently_painting_top = false;
559 bool currently_painting_bottom = false;
561 unsigned int pix_width = bci.width * 4;
563 unsigned int top_ty = bci.y - 1;
564 unsigned int bottom_ty = bci.y + 1;
566 bool can_paint_top = (top_ty > 0);
567 bool can_paint_bottom = (bottom_ty < bci.height);
569 NR::Point t = fill_queue->front();
571 do {
572 ok = false;
573 if (bci.is_left) {
574 keep_tracing = (bci.x != 0);
575 } else {
576 keep_tracing = (bci.x < bci.width);
577 }
579 if (keep_tracing) {
580 if (check_if_pixel_is_paintable(px, current_trace_t, bci.x, bci.y, orig_color, bci)) {
581 paint_directions = paint_pixel(px, trace_px, orig_color, bci, current_trace_t);
582 if (bci.radius == 0) {
583 mark_pixel_checked(current_trace_t);
584 if ((t[NR::X] == bci.x) && (t[NR::Y] == bci.y)) {
585 fill_queue->pop_front(); t = fill_queue->front();
586 }
587 }
589 if (can_paint_top) {
590 if (paint_directions & PAINT_DIRECTION_UP) {
591 unsigned char *trace_t = current_trace_t - pix_width;
592 if (!is_pixel_queued(trace_t)) {
593 bool ok_to_paint = check_if_pixel_is_paintable(px, trace_t, bci.x, top_ty, orig_color, bci);
595 if (initial_paint) { currently_painting_top = !ok_to_paint; }
597 if (ok_to_paint && (!currently_painting_top)) {
598 currently_painting_top = true;
599 push_point_onto_queue(fill_queue, bci.max_queue_size, trace_t, bci.x, top_ty);
600 }
601 if ((!ok_to_paint) && currently_painting_top) {
602 currently_painting_top = false;
603 }
604 }
605 }
606 }
608 if (can_paint_bottom) {
609 if (paint_directions & PAINT_DIRECTION_DOWN) {
610 unsigned char *trace_t = current_trace_t + pix_width;
611 if (!is_pixel_queued(trace_t)) {
612 bool ok_to_paint = check_if_pixel_is_paintable(px, trace_t, bci.x, bottom_ty, orig_color, bci);
614 if (initial_paint) { currently_painting_bottom = !ok_to_paint; }
616 if (ok_to_paint && (!currently_painting_bottom)) {
617 currently_painting_bottom = true;
618 push_point_onto_queue(fill_queue, bci.max_queue_size, trace_t, bci.x, bottom_ty);
619 }
620 if ((!ok_to_paint) && currently_painting_bottom) {
621 currently_painting_bottom = false;
622 }
623 }
624 }
625 }
627 if (bci.is_left) {
628 if (paint_directions & PAINT_DIRECTION_LEFT) {
629 bci.x -= 1; current_trace_t -= 4;
630 ok = true;
631 }
632 } else {
633 if (paint_directions & PAINT_DIRECTION_RIGHT) {
634 bci.x += 1; current_trace_t += 4;
635 ok = true;
636 }
637 }
639 initial_paint = false;
640 }
641 } else {
642 if (bci.bbox.min()[NR::X] > bci.screen.min()[NR::X]) {
643 aborted = true; break;
644 } else {
645 reached_screen_boundary = true;
646 }
647 }
648 } while (ok);
650 if (aborted) { return SCANLINE_CHECK_ABORTED; }
651 if (reached_screen_boundary) { return SCANLINE_CHECK_BOUNDARY; }
652 return SCANLINE_CHECK_OK;
653 }
655 static bool sort_fill_queue_vertical(NR::Point a, NR::Point b) {
656 return a[NR::Y] > b[NR::Y];
657 }
659 static bool sort_fill_queue_horizontal(NR::Point a, NR::Point b) {
660 return a[NR::X] > b[NR::X];
661 }
663 static void sp_flood_do_flood_fill(SPEventContext *event_context, GdkEvent *event, bool union_with_selection, bool is_point_fill, bool is_touch_fill) {
664 SPDesktop *desktop = event_context->desktop;
665 SPDocument *document = sp_desktop_document(desktop);
667 /* Create new arena */
668 NRArena *arena = NRArena::create();
669 unsigned dkey = sp_item_display_key_new(1);
671 sp_document_ensure_up_to_date (document);
673 SPItem *document_root = SP_ITEM(SP_DOCUMENT_ROOT(document));
674 NR::Maybe<NR::Rect> bbox = document_root->getBounds(NR::identity());
676 if (!bbox) {
677 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
678 return;
679 }
681 double zoom_scale = desktop->current_zoom();
682 double padding = 1.6;
684 NR::Rect screen = desktop->get_display_area();
686 unsigned int width = (int)ceil(screen.extent(NR::X) * zoom_scale * padding);
687 unsigned int height = (int)ceil(screen.extent(NR::Y) * zoom_scale * padding);
689 NR::Point origin(screen.min()[NR::X],
690 sp_document_height(document) - screen.extent(NR::Y) - screen.min()[NR::Y]);
692 origin[NR::X] = origin[NR::X] + (screen.extent(NR::X) * ((1 - padding) / 2));
693 origin[NR::Y] = origin[NR::Y] + (screen.extent(NR::Y) * ((1 - padding) / 2));
695 NR::scale scale(zoom_scale, zoom_scale);
696 NR::Matrix affine = scale * NR::translate(-origin * scale);
698 /* Create ArenaItems and set transform */
699 NRArenaItem *root = sp_item_invoke_show(SP_ITEM(sp_document_root(document)), arena, dkey, SP_ITEM_SHOW_DISPLAY);
700 nr_arena_item_set_transform(NR_ARENA_ITEM(root), affine);
702 NRGC gc(NULL);
703 nr_matrix_set_identity(&gc.transform);
705 NRRectL final_bbox;
706 final_bbox.x0 = 0;
707 final_bbox.y0 = 0;//row;
708 final_bbox.x1 = width;
709 final_bbox.y1 = height;//row + num_rows;
711 nr_arena_item_invoke_update(root, &final_bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
713 guchar *px = g_new(guchar, 4 * width * height);
715 NRPixBlock B;
716 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
717 final_bbox.x0, final_bbox.y0, final_bbox.x1, final_bbox.y1,
718 px, 4 * width, FALSE, FALSE );
720 SPNamedView *nv = sp_desktop_namedview(desktop);
721 unsigned long bgcolor = nv->pagecolor;
723 unsigned char dtc[4];
724 dtc[0] = NR_RGBA32_R(bgcolor);
725 dtc[1] = NR_RGBA32_G(bgcolor);
726 dtc[2] = NR_RGBA32_B(bgcolor);
727 dtc[3] = NR_RGBA32_A(bgcolor);
729 for (unsigned int fy = 0; fy < height; fy++) {
730 guchar *p = NR_PIXBLOCK_PX(&B) + fy * B.rs;
731 for (unsigned int fx = 0; fx < width; fx++) {
732 for (int i = 0; i < 4; i++) {
733 *p++ = dtc[i];
734 }
735 }
736 }
738 nr_arena_item_invoke_render(NULL, root, &final_bbox, &B, NR_ARENA_ITEM_RENDER_NO_CACHE );
739 nr_pixblock_release(&B);
741 // Hide items
742 sp_item_invoke_hide(SP_ITEM(sp_document_root(document)), dkey);
744 nr_arena_item_unref(root);
745 nr_object_unref((NRObject *) arena);
747 guchar *trace_px = g_new(guchar, 4 * width * height);
748 memset(trace_px, 0x00, 4 * width * height);
750 std::deque<NR::Point> fill_queue;
751 std::queue<NR::Point> color_queue;
753 std::vector<NR::Point> fill_points;
755 bool aborted = false;
756 int y_limit = height - 1;
758 PaintBucketChannels method = (PaintBucketChannels)prefs_get_int_attribute("tools.paintbucket", "channels", 0);
759 int threshold = prefs_get_int_attribute_limited("tools.paintbucket", "threshold", 1, 0, 100);
761 switch(method) {
762 case FLOOD_CHANNELS_ALPHA:
763 case FLOOD_CHANNELS_RGB:
764 case FLOOD_CHANNELS_R:
765 case FLOOD_CHANNELS_G:
766 case FLOOD_CHANNELS_B:
767 threshold = (255 * threshold) / 100;
768 break;
769 case FLOOD_CHANNELS_H:
770 case FLOOD_CHANNELS_S:
771 case FLOOD_CHANNELS_L:
772 break;
773 }
775 bitmap_coords_info bci;
777 bci.y_limit = y_limit;
778 bci.width = width;
779 bci.height = height;
780 bci.threshold = threshold;
781 bci.method = method;
782 bci.bbox = *bbox;
783 bci.screen = screen;
784 bci.dtc = dtc;
785 bci.radius = prefs_get_int_attribute_limited("tools.paintbucket", "autogap", 0, 0, 3);
786 bci.max_queue_size = (width * height) / 4;
787 bci.current_step = 0;
789 if (is_point_fill) {
790 fill_points.push_back(NR::Point(event->button.x, event->button.y));
791 } else {
792 Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
793 fill_points = r->getPoints();
794 }
796 for (unsigned int i = 0; i < fill_points.size(); i++) {
797 NR::Point pw = NR::Point(fill_points[i][NR::X] / zoom_scale, sp_document_height(document) + (fill_points[i][NR::Y] / zoom_scale)) * affine;
799 pw[NR::X] = (int)MIN(width - 1, MAX(0, pw[NR::X]));
800 pw[NR::Y] = (int)MIN(height - 1, MAX(0, pw[NR::Y]));
802 if (is_touch_fill) {
803 if (i == 0) {
804 color_queue.push(pw);
805 } else {
806 unsigned char *trace_t = get_pixel(trace_px, (int)pw[NR::X], (int)pw[NR::Y], width);
807 push_point_onto_queue(&fill_queue, bci.max_queue_size, trace_t, (int)pw[NR::X], (int)pw[NR::Y]);
808 }
809 } else {
810 color_queue.push(pw);
811 }
812 }
814 bool reached_screen_boundary = false;
816 bool first_run = true;
818 unsigned long sort_size_threshold = 5;
820 while (!color_queue.empty() && !aborted) {
821 NR::Point color_point = color_queue.front();
822 color_queue.pop();
824 int cx = (int)color_point[NR::X];
825 int cy = (int)color_point[NR::Y];
827 unsigned char *orig_px = get_pixel(px, cx, cy, width);
828 unsigned char orig_color[4];
829 for (int i = 0; i < 4; i++) { orig_color[i] = orig_px[i]; }
831 unsigned char merged_orig[3];
833 merge_pixel_with_background(orig_color, dtc, merged_orig);
835 bci.merged_orig_pixel = merged_orig;
837 unsigned char *trace_t = get_pixel(trace_px, cx, cy, width);
838 if (!is_pixel_checked(trace_t) && !is_pixel_colored(trace_t)) {
839 if (check_if_pixel_is_paintable(px, trace_px, cx, cy, orig_color, bci)) {
840 shift_point_onto_queue(&fill_queue, bci.max_queue_size, trace_t, cx, cy);
842 if (!first_run) {
843 for (unsigned int y = 0; y < height; y++) {
844 trace_t = get_pixel(trace_px, 0, y, width);
845 for (unsigned int x = 0; x < width; x++) {
846 clear_pixel_paintability(trace_t);
847 trace_t += 4;
848 }
849 }
850 }
851 first_run = false;
852 }
853 }
855 unsigned long old_fill_queue_size = fill_queue.size();
857 while (!fill_queue.empty() && !aborted) {
858 NR::Point cp = fill_queue.front();
860 if (bci.radius == 0) {
861 unsigned long new_fill_queue_size = fill_queue.size();
863 if (new_fill_queue_size > sort_size_threshold) {
864 if (new_fill_queue_size > old_fill_queue_size) {
865 std::sort(fill_queue.begin(), fill_queue.end(), sort_fill_queue_vertical);
867 std::deque<NR::Point>::iterator start_sort = fill_queue.begin();
868 std::deque<NR::Point>::iterator end_sort = fill_queue.begin();
869 unsigned int sort_y = (unsigned int)cp[NR::Y];
870 unsigned int current_y = sort_y;
872 for (std::deque<NR::Point>::iterator i = fill_queue.begin(); i != fill_queue.end(); i++) {
873 NR::Point current = *i;
874 current_y = (unsigned int)current[NR::Y];
875 if (current_y != sort_y) {
876 if (start_sort != end_sort) {
877 std::sort(start_sort, end_sort, sort_fill_queue_horizontal);
878 }
879 sort_y = current_y;
880 start_sort = i;
881 }
882 end_sort = i;
883 }
884 if (start_sort != end_sort) {
885 std::sort(start_sort, end_sort, sort_fill_queue_horizontal);
886 }
888 cp = fill_queue.front();
889 }
890 }
892 old_fill_queue_size = new_fill_queue_size;
893 }
895 fill_queue.pop_front();
897 int x = (int)cp[NR::X];
898 int y = (int)cp[NR::Y];
900 unsigned char *trace_t = get_pixel(trace_px, x, y, width);
901 if (!is_pixel_checked(trace_t)) {
902 mark_pixel_checked(trace_t);
904 if (y == 0) {
905 if (bbox->min()[NR::Y] > screen.min()[NR::Y]) {
906 aborted = true; break;
907 } else {
908 reached_screen_boundary = true;
909 }
910 }
912 if (y == y_limit) {
913 if (bbox->max()[NR::Y] < screen.max()[NR::Y]) {
914 aborted = true; break;
915 } else {
916 reached_screen_boundary = true;
917 }
918 }
920 bci.is_left = true;
921 bci.x = x;
922 bci.y = y;
924 ScanlineCheckResult result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci);
926 switch (result) {
927 case SCANLINE_CHECK_ABORTED:
928 aborted = true;
929 break;
930 case SCANLINE_CHECK_BOUNDARY:
931 reached_screen_boundary = true;
932 break;
933 default:
934 break;
935 }
937 if (bci.x < width) {
938 trace_t += 4;
939 if (!is_pixel_checked(trace_t) && !is_pixel_queued(trace_t)) {
940 mark_pixel_checked(trace_t);
941 bci.is_left = false;
942 bci.x = x + 1;
944 result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci);
946 switch (result) {
947 case SCANLINE_CHECK_ABORTED:
948 aborted = true;
949 break;
950 case SCANLINE_CHECK_BOUNDARY:
951 reached_screen_boundary = true;
952 break;
953 default:
954 break;
955 }
956 }
957 }
958 }
960 bci.current_step++;
962 if (bci.current_step > bci.max_queue_size) {
963 aborted = true;
964 }
965 }
966 }
968 g_free(px);
970 if (aborted) {
971 g_free(trace_px);
972 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
973 return;
974 }
976 if (reached_screen_boundary) {
977 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."));
978 }
980 GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(trace_px,
981 GDK_COLORSPACE_RGB,
982 TRUE,
983 8, width, height, width * 4,
984 (GdkPixbufDestroyNotify)g_free,
985 NULL);
987 NR::Matrix inverted_affine = NR::Matrix(affine).inverse();
989 do_trace(pixbuf, desktop, inverted_affine, union_with_selection);
991 g_free(trace_px);
993 sp_document_done(document, SP_VERB_CONTEXT_PAINTBUCKET, _("Fill bounded area"));
994 }
996 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
997 {
998 gint ret = FALSE;
1000 SPDesktop *desktop = event_context->desktop;
1002 switch (event->type) {
1003 case GDK_BUTTON_PRESS:
1004 if ((event->button.state & GDK_CONTROL_MASK) && event->button.button == 1 && !event_context->space_panning) {
1005 NR::Point const button_w(event->button.x,
1006 event->button.y);
1008 SPItem *item = sp_event_context_find_item (desktop, button_w, TRUE, TRUE);
1010 Inkscape::XML::Node *pathRepr = SP_OBJECT_REPR(item);
1011 /* Set style */
1012 sp_desktop_apply_style_tool (desktop, pathRepr, "tools.paintbucket", false);
1013 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET, _("Set style on object"));
1014 ret = TRUE;
1015 }
1016 break;
1017 default:
1018 break;
1019 }
1021 if (((SPEventContextClass *) parent_class)->item_handler) {
1022 ret = ((SPEventContextClass *) parent_class)->item_handler(event_context, item, event);
1023 }
1025 return ret;
1026 }
1028 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event)
1029 {
1030 static bool dragging;
1032 gint ret = FALSE;
1033 SPDesktop *desktop = event_context->desktop;
1035 switch (event->type) {
1036 case GDK_BUTTON_PRESS:
1037 if (event->button.button == 1 && !event_context->space_panning) {
1038 if (!(event->button.state & GDK_CONTROL_MASK)) {
1039 NR::Point const button_w(event->button.x,
1040 event->button.y);
1042 if (Inkscape::have_viable_layer(desktop, event_context->defaultMessageContext())) {
1043 // save drag origin
1044 event_context->xp = (gint) button_w[NR::X];
1045 event_context->yp = (gint) button_w[NR::Y];
1046 event_context->within_tolerance = true;
1048 dragging = true;
1050 NR::Point const p(desktop->w2d(button_w));
1051 Inkscape::Rubberband::get()->setMode(RUBBERBAND_MODE_TOUCHPATH);
1052 Inkscape::Rubberband::get()->start(desktop, p);
1053 }
1054 }
1055 }
1056 case GDK_MOTION_NOTIFY:
1057 if ( dragging
1058 && ( event->motion.state & GDK_BUTTON1_MASK ) && !event_context->space_panning)
1059 {
1060 if ( event_context->within_tolerance
1061 && ( abs( (gint) event->motion.x - event_context->xp ) < event_context->tolerance )
1062 && ( abs( (gint) event->motion.y - event_context->yp ) < event_context->tolerance ) ) {
1063 break; // do not drag if we're within tolerance from origin
1064 }
1066 event_context->within_tolerance = false;
1068 NR::Point const motion_pt(event->motion.x, event->motion.y);
1069 NR::Point const p(desktop->w2d(motion_pt));
1070 if (Inkscape::Rubberband::get()->is_started()) {
1071 Inkscape::Rubberband::get()->move(p);
1072 event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Draw over</b> areas to add to fill, hold <b>Alt</b> for touch fill"));
1073 gobble_motion_events(GDK_BUTTON1_MASK);
1074 }
1075 }
1076 break;
1078 case GDK_BUTTON_RELEASE:
1079 if (event->button.button == 1 && !event_context->space_panning) {
1080 Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
1081 if (r->is_started()) {
1082 // set "busy" cursor
1083 desktop->setWaitingCursor();
1085 if (SP_IS_EVENT_CONTEXT(event_context)) {
1086 // Since setWaitingCursor runs main loop iterations, we may have already left this tool!
1087 // So check if the tool is valid before doing anything
1088 dragging = false;
1090 bool is_point_fill = event_context->within_tolerance;
1091 bool is_touch_fill = event->button.state & GDK_MOD1_MASK;
1093 sp_flood_do_flood_fill(event_context, event, event->button.state & GDK_SHIFT_MASK, is_point_fill, is_touch_fill);
1095 desktop->clearWaitingCursor();
1096 // restore cursor when done; note that it may already be different if e.g. user
1097 // switched to another tool during interruptible tracing or drawing, in which case do nothing
1099 ret = TRUE;
1100 }
1102 r->stop();
1103 event_context->defaultMessageContext()->clear();
1104 }
1105 }
1106 break;
1107 case GDK_KEY_PRESS:
1108 switch (get_group0_keyval (&event->key)) {
1109 case GDK_Up:
1110 case GDK_Down:
1111 case GDK_KP_Up:
1112 case GDK_KP_Down:
1113 // prevent the zoom field from activation
1114 if (!MOD__CTRL_ONLY)
1115 ret = TRUE;
1116 break;
1117 default:
1118 break;
1119 }
1120 break;
1121 default:
1122 break;
1123 }
1125 if (!ret) {
1126 if (((SPEventContextClass *) parent_class)->root_handler) {
1127 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1128 }
1129 }
1131 return ret;
1132 }
1135 static void sp_flood_finish(SPFloodContext *rc)
1136 {
1137 rc->_message_context->clear();
1139 if ( rc->item != NULL ) {
1140 SPDesktop * desktop;
1142 desktop = SP_EVENT_CONTEXT_DESKTOP(rc);
1144 SP_OBJECT(rc->item)->updateRepr();
1146 sp_canvas_end_forced_full_redraws(desktop->canvas);
1148 sp_desktop_selection(desktop)->set(rc->item);
1149 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET,
1150 _("Fill bounded area"));
1152 rc->item = NULL;
1153 }
1154 }
1156 void flood_channels_set_channels( gint channels )
1157 {
1158 prefs_set_int_attribute("tools.paintbucket", "channels", channels);
1159 }
1161 /*
1162 Local Variables:
1163 mode:c++
1164 c-file-style:"stroustrup"
1165 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1166 indent-tabs-mode:nil
1167 fill-column:99
1168 End:
1169 */
1170 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :