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 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_queued(unsigned char *t) { t[1] = 1; }
317 static inline void mark_pixel_paintable(unsigned char *t) { t[2] = 1; }
318 static inline void mark_pixel_not_paintable(unsigned char *t) { t[2] = 2; }
319 static inline void mark_pixel_colored(unsigned char *t) { t[3] = 255; }
321 static inline void clear_pixel_paintability(unsigned char *t) { t[2] = 0; }
323 struct bitmap_coords_info {
324 bool is_left;
325 int x;
326 int y;
327 int y_limit;
328 int width;
329 int height;
330 int threshold;
331 int radius;
332 PaintBucketChannels method;
333 unsigned char *dtc;
334 unsigned char *merged_orig_pixel;
335 NR::Rect bbox;
336 NR::Rect screen;
337 unsigned int max_queue_size;
338 unsigned int max_vertical_check;
339 };
341 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) {
342 if (is_pixel_paintability_checked(trace_t)) {
343 return is_pixel_paintable(trace_t);
344 } else {
345 unsigned char *t = get_pixel(px, x, y, bci.width);
346 if (compare_pixels(t, orig_color, bci.merged_orig_pixel, bci.dtc, bci.threshold, bci.method)) {
347 mark_pixel_paintable(trace_t);
348 return true;
349 } else {
350 mark_pixel_not_paintable(trace_t);
351 return false;
352 }
353 }
354 }
356 static bool try_add_to_queue(std::deque<NR::Point> *fill_queue, guchar *px, guchar *trace_px, unsigned char *orig, int x, int y, bitmap_coords_info bci) {
357 unsigned char *trace_t = get_pixel(trace_px, x, y, bci.width);
358 bool ok_to_add = false;
359 if (bci.radius == 0) {
360 if (!(is_pixel_queued(trace_t) || is_pixel_colored(trace_t))) {
361 ok_to_add = true;
362 }
363 } else {
364 if (!(is_pixel_checked(trace_t) || is_pixel_queued(trace_t))) {
365 ok_to_add = check_if_pixel_is_paintable(px, trace_t, x, y, orig, bci);
366 }
367 }
368 if (ok_to_add) {
369 if ((fill_queue->size() < bci.max_queue_size)) {
370 fill_queue->push_back(NR::Point(x, y));
371 mark_pixel_queued(trace_t);
372 return true;
373 }
375 }
376 return false;
377 }
379 static void do_trace(GdkPixbuf *px, SPDesktop *desktop, NR::Matrix transform, bool union_with_selection) {
380 SPDocument *document = sp_desktop_document(desktop);
382 Inkscape::Trace::Potrace::PotraceTracingEngine pte;
384 pte.setTraceType(Inkscape::Trace::Potrace::TRACE_BRIGHTNESS);
385 pte.setInvert(false);
387 Glib::RefPtr<Gdk::Pixbuf> pixbuf = Glib::wrap(px, true);
389 std::vector<Inkscape::Trace::TracingEngineResult> results = pte.trace(pixbuf);
391 Inkscape::XML::Node *layer_repr = SP_GROUP(desktop->currentLayer())->repr;
392 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
394 long totalNodeCount = 0L;
396 double offset = prefs_get_double_attribute("tools.paintbucket", "offset", 0.0);
398 for (unsigned int i=0 ; i<results.size() ; i++) {
399 Inkscape::Trace::TracingEngineResult result = results[i];
400 totalNodeCount += result.getNodeCount();
402 Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path");
403 /* Set style */
404 sp_desktop_apply_style_tool (desktop, pathRepr, "tools.paintbucket", false);
406 NArtBpath *bpath = sp_svg_read_path(result.getPathData().c_str());
407 Path *path = bpath_to_Path(bpath);
408 g_free(bpath);
410 if (offset != 0) {
412 Shape *path_shape = new Shape();
414 path->ConvertWithBackData(0.03);
415 path->Fill(path_shape, 0);
416 delete path;
418 Shape *expanded_path_shape = new Shape();
420 expanded_path_shape->ConvertToShape(path_shape, fill_nonZero);
421 path_shape->MakeOffset(expanded_path_shape, offset * desktop->current_zoom(), join_round, 4);
422 expanded_path_shape->ConvertToShape(path_shape, fill_positive);
424 Path *expanded_path = new Path();
426 expanded_path->Reset();
427 expanded_path_shape->ConvertToForme(expanded_path);
428 expanded_path->ConvertEvenLines(1.0);
429 expanded_path->Simplify(1.0);
431 delete path_shape;
432 delete expanded_path_shape;
434 gchar *str = expanded_path->svg_dump_path();
435 if (str && *str) {
436 pathRepr->setAttribute("d", str);
437 g_free(str);
438 } else {
439 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Too much inset</b>, the result is empty."));
440 Inkscape::GC::release(pathRepr);
441 g_free(str);
442 return;
443 }
445 delete expanded_path;
447 } else {
448 gchar *str = path->svg_dump_path();
449 delete path;
450 pathRepr->setAttribute("d", str);
451 g_free(str);
452 }
454 layer_repr->addChild(pathRepr, NULL);
456 SPObject *reprobj = document->getObjectByRepr(pathRepr);
457 if (reprobj) {
458 sp_item_write_transform(SP_ITEM(reprobj), pathRepr, transform, NULL);
460 // premultiply the item transform by the accumulated parent transform in the paste layer
461 NR::Matrix local = sp_item_i2doc_affine(SP_GROUP(desktop->currentLayer()));
462 if (!local.test_identity()) {
463 gchar const *t_str = pathRepr->attribute("transform");
464 NR::Matrix item_t (NR::identity());
465 if (t_str)
466 sp_svg_transform_read(t_str, &item_t);
467 item_t *= local.inverse();
468 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
469 gchar *affinestr=sp_svg_transform_write(item_t);
470 pathRepr->setAttribute("transform", affinestr);
471 g_free(affinestr);
472 }
474 Inkscape::Selection *selection = sp_desktop_selection(desktop);
476 pathRepr->setPosition(-1);
478 if (union_with_selection) {
479 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)));
480 selection->add(reprobj);
481 sp_selected_path_union_skip_undo();
482 } else {
483 desktop->messageStack()->flashF(Inkscape::WARNING_MESSAGE, _("Area filled, path with <b>%d</b> nodes created."), sp_nodes_in_path(SP_PATH(reprobj)));
484 selection->set(reprobj);
485 }
487 }
489 Inkscape::GC::release(pathRepr);
491 }
492 }
494 enum ScanlineCheckResult {
495 SCANLINE_CHECK_OK,
496 SCANLINE_CHECK_ABORTED,
497 SCANLINE_CHECK_BOUNDARY
498 };
500 static bool coords_in_range(int x, int y, bitmap_coords_info bci) {
501 return (x >= 0)
502 && (x < bci.width)
503 && (y >= 0)
504 && (y < bci.height);
505 }
507 #define PAINT_DIRECTION_LEFT 1
508 #define PAINT_DIRECTION_RIGHT 2
509 #define PAINT_DIRECTION_UP 4
510 #define PAINT_DIRECTION_DOWN 8
511 #define PAINT_DIRECTION_ALL 15
513 static unsigned int paint_pixel(guchar *px, guchar *trace_px, unsigned char *orig_color, bitmap_coords_info bci, unsigned char *original_point_trace_t) {
514 if (bci.radius == 0) {
515 mark_pixel_colored(original_point_trace_t);
516 return PAINT_DIRECTION_ALL;
517 } else {
518 unsigned char *trace_t;
520 bool can_paint_up = true;
521 bool can_paint_down = true;
522 bool can_paint_left = true;
523 bool can_paint_right = true;
525 for (int y = -bci.radius; y <= bci.radius; y++) {
526 int ty = bci.y + y;
527 for (int x = -bci.radius; x <= bci.radius; x++) {
528 int tx = bci.x + x;
530 if (coords_in_range(tx, ty, bci)) {
531 trace_t = get_pixel(trace_px, tx, ty, bci.width);
532 if (!is_pixel_colored(trace_t)) {
533 if (check_if_pixel_is_paintable(px, trace_t, tx, ty, orig_color, bci)) {
534 mark_pixel_colored(trace_t);
535 } else {
536 if (x < 0) { can_paint_left = false; }
537 if (x > 0) { can_paint_right = false; }
538 if (y < 0) { can_paint_up = false; }
539 if (y > 0) { can_paint_down = false; }
540 }
541 }
542 }
543 }
544 }
546 unsigned int paint_directions = 0;
547 if (can_paint_left) { paint_directions += PAINT_DIRECTION_LEFT; }
548 if (can_paint_right) { paint_directions += PAINT_DIRECTION_RIGHT; }
549 if (can_paint_up) { paint_directions += PAINT_DIRECTION_UP; }
550 if (can_paint_down) { paint_directions += PAINT_DIRECTION_DOWN; }
552 return paint_directions;
553 }
554 }
556 static unsigned int paint_leading_edge(guchar *px, guchar *trace_px, unsigned char *orig_color, bitmap_coords_info bci, unsigned int direction) {
557 unsigned char *trace_t;
559 if (bci.radius > 0) {
560 bool can_paint_up = true;
561 bool can_paint_down = true;
562 bool can_paint_left = true;
563 bool can_paint_right = true;
565 int tx = bci.x;
567 switch (direction) {
568 case PAINT_DIRECTION_LEFT:
569 tx = bci.x - bci.radius;
570 break;
571 case PAINT_DIRECTION_RIGHT:
572 tx = bci.x + bci.radius;
573 break;
574 }
576 for (int y = -bci.radius; y <= bci.radius; y++) {
577 int ty = bci.y + y;
578 if (coords_in_range(tx, ty, bci)) {
579 trace_t = get_pixel(trace_px, tx, ty, bci.width);
580 if (!is_pixel_colored(trace_t)) {
581 if (check_if_pixel_is_paintable(px, trace_t, tx, ty, orig_color, bci)) {
582 mark_pixel_colored(trace_t);
583 } else {
584 if (direction == PAINT_DIRECTION_LEFT) { can_paint_left = false; }
585 if (direction == PAINT_DIRECTION_RIGHT) { can_paint_right = false; }
586 if (y < 0) { can_paint_up = false; }
587 if (y > 0) { can_paint_down = false; }
588 }
589 }
590 }
591 }
593 unsigned int paint_directions = 0;
594 if (can_paint_left) { paint_directions += PAINT_DIRECTION_LEFT; }
595 if (can_paint_right) { paint_directions += PAINT_DIRECTION_RIGHT; }
596 if (can_paint_up) { paint_directions += PAINT_DIRECTION_UP; }
597 if (can_paint_down) { paint_directions += PAINT_DIRECTION_DOWN; }
599 return paint_directions;
600 } else {
601 return 0;
602 }
603 }
605 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) {
606 bool aborted = false;
607 bool reached_screen_boundary = false;
608 bool ok;
610 bool keep_tracing;
611 bool paint_single_pixel = true;
612 bool leading_edge_after_first_paint = (bci.radius == 0);
614 int vertical_check_count = 0;
616 unsigned char *current_trace_t = get_pixel(trace_px, bci.x, bci.y, bci.width);
617 unsigned int paint_directions;
619 do {
620 ok = false;
621 if (bci.is_left) {
622 keep_tracing = (bci.x >= 0);
623 } else {
624 keep_tracing = (bci.x < bci.width);
625 }
627 if (keep_tracing) {
628 if (check_if_pixel_is_paintable(px, current_trace_t, bci.x, bci.y, orig_color, bci)) {
629 if (paint_single_pixel) {
630 paint_directions = paint_pixel(px, trace_px, orig_color, bci, current_trace_t);
631 } else {
632 if (bci.is_left) {
633 paint_directions = paint_leading_edge(px, trace_px, orig_color, bci, PAINT_DIRECTION_LEFT);
634 } else {
635 paint_directions = paint_leading_edge(px, trace_px, orig_color, bci, PAINT_DIRECTION_RIGHT);
636 }
637 }
638 paint_single_pixel = leading_edge_after_first_paint;
640 if (vertical_check_count == 0) {
641 if (paint_directions & PAINT_DIRECTION_UP) {
642 try_add_to_queue(fill_queue, px, trace_px, orig_color, bci.x, bci.y - 1, bci);
643 }
644 if (paint_directions & PAINT_DIRECTION_DOWN) {
645 try_add_to_queue(fill_queue, px, trace_px, orig_color, bci.x, bci.y + 1, bci);
646 }
647 }
649 if (bci.max_vertical_check > 0) {
650 vertical_check_count = (vertical_check_count + 1) % bci.max_vertical_check;
651 }
653 if (bci.is_left) {
654 if (paint_directions & PAINT_DIRECTION_LEFT) {
655 bci.x -= 1; current_trace_t -= 4;
656 ok = true;
657 }
658 } else {
659 if (paint_directions & PAINT_DIRECTION_RIGHT) {
660 bci.x += 1; current_trace_t += 4;
661 ok = true;
662 }
663 }
664 }
665 } else {
666 if (bci.bbox.min()[NR::X] > bci.screen.min()[NR::X]) {
667 aborted = true; break;
668 } else {
669 reached_screen_boundary = true;
670 }
671 }
672 } while (ok);
674 if (aborted) { return SCANLINE_CHECK_ABORTED; }
675 if (reached_screen_boundary) { return SCANLINE_CHECK_BOUNDARY; }
676 return SCANLINE_CHECK_OK;
677 }
679 static void sp_flood_do_flood_fill(SPEventContext *event_context, GdkEvent *event, bool union_with_selection, bool is_point_fill, bool is_touch_fill) {
680 SPDesktop *desktop = event_context->desktop;
681 SPDocument *document = sp_desktop_document(desktop);
683 /* Create new arena */
684 NRArena *arena = NRArena::create();
685 unsigned dkey = sp_item_display_key_new(1);
687 sp_document_ensure_up_to_date (document);
689 SPItem *document_root = SP_ITEM(SP_DOCUMENT_ROOT(document));
690 NR::Maybe<NR::Rect> bbox = document_root->getBounds(NR::identity());
692 if (!bbox) {
693 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
694 return;
695 }
697 double zoom_scale = desktop->current_zoom();
698 double padding = 1.6;
700 NR::Rect screen = desktop->get_display_area();
702 int width = (int)ceil(screen.extent(NR::X) * zoom_scale * padding);
703 int height = (int)ceil(screen.extent(NR::Y) * zoom_scale * padding);
705 NR::Point origin(screen.min()[NR::X],
706 sp_document_height(document) - screen.extent(NR::Y) - screen.min()[NR::Y]);
708 origin[NR::X] = origin[NR::X] + (screen.extent(NR::X) * ((1 - padding) / 2));
709 origin[NR::Y] = origin[NR::Y] + (screen.extent(NR::Y) * ((1 - padding) / 2));
711 NR::scale scale(zoom_scale, zoom_scale);
712 NR::Matrix affine = scale * NR::translate(-origin * scale);
714 /* Create ArenaItems and set transform */
715 NRArenaItem *root = sp_item_invoke_show(SP_ITEM(sp_document_root(document)), arena, dkey, SP_ITEM_SHOW_DISPLAY);
716 nr_arena_item_set_transform(NR_ARENA_ITEM(root), affine);
718 NRGC gc(NULL);
719 nr_matrix_set_identity(&gc.transform);
721 NRRectL final_bbox;
722 final_bbox.x0 = 0;
723 final_bbox.y0 = 0;//row;
724 final_bbox.x1 = width;
725 final_bbox.y1 = height;//row + num_rows;
727 nr_arena_item_invoke_update(root, &final_bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
729 guchar *px = g_new(guchar, 4 * width * height);
731 NRPixBlock B;
732 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
733 final_bbox.x0, final_bbox.y0, final_bbox.x1, final_bbox.y1,
734 px, 4 * width, FALSE, FALSE );
736 SPNamedView *nv = sp_desktop_namedview(desktop);
737 unsigned long bgcolor = nv->pagecolor;
739 unsigned char dtc[4];
740 dtc[0] = NR_RGBA32_R(bgcolor);
741 dtc[1] = NR_RGBA32_G(bgcolor);
742 dtc[2] = NR_RGBA32_B(bgcolor);
743 dtc[3] = NR_RGBA32_A(bgcolor);
745 for (int fy = 0; fy < height; fy++) {
746 guchar *p = NR_PIXBLOCK_PX(&B) + fy * B.rs;
747 for (int fx = 0; fx < width; fx++) {
748 for (int i = 0; i < 4; i++) {
749 *p++ = dtc[i];
750 }
751 }
752 }
754 nr_arena_item_invoke_render(NULL, root, &final_bbox, &B, NR_ARENA_ITEM_RENDER_NO_CACHE );
755 nr_pixblock_release(&B);
757 // Hide items
758 sp_item_invoke_hide(SP_ITEM(sp_document_root(document)), dkey);
760 nr_arena_item_unref(root);
761 nr_object_unref((NRObject *) arena);
763 guchar *trace_px = g_new(guchar, 4 * width * height);
764 memset(trace_px, 0x00, 4 * width * height);
766 std::deque<NR::Point> fill_queue;
767 std::queue<NR::Point> color_queue;
769 std::vector<NR::Point> fill_points;
771 if (is_point_fill) {
772 fill_points.push_back(NR::Point(event->button.x, event->button.y));
773 } else {
774 Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
775 fill_points = r->getPoints();
776 }
778 for (unsigned int i = 0; i < fill_points.size(); i++) {
779 NR::Point pw = NR::Point(fill_points[i][NR::X] / zoom_scale, sp_document_height(document) + (fill_points[i][NR::Y] / zoom_scale)) * affine;
781 pw[NR::X] = (int)MIN(width - 1, MAX(0, pw[NR::X]));
782 pw[NR::Y] = (int)MIN(height - 1, MAX(0, pw[NR::Y]));
784 if (is_touch_fill) {
785 if (i == 0) {
786 color_queue.push(pw);
787 } else {
788 fill_queue.push_back(pw);
789 }
790 } else {
791 color_queue.push(pw);
792 }
793 }
795 bool aborted = false;
796 int y_limit = height - 1;
798 PaintBucketChannels method = (PaintBucketChannels)prefs_get_int_attribute("tools.paintbucket", "channels", 0);
799 int threshold = prefs_get_int_attribute_limited("tools.paintbucket", "threshold", 1, 0, 100);
801 switch(method) {
802 case FLOOD_CHANNELS_ALPHA:
803 case FLOOD_CHANNELS_RGB:
804 case FLOOD_CHANNELS_R:
805 case FLOOD_CHANNELS_G:
806 case FLOOD_CHANNELS_B:
807 threshold = (255 * threshold) / 100;
808 break;
809 case FLOOD_CHANNELS_H:
810 case FLOOD_CHANNELS_S:
811 case FLOOD_CHANNELS_L:
812 break;
813 }
815 bool reached_screen_boundary = false;
817 bitmap_coords_info bci;
819 bci.y_limit = y_limit;
820 bci.width = width;
821 bci.height = height;
822 bci.threshold = threshold;
823 bci.method = method;
824 bci.bbox = *bbox;
825 bci.screen = screen;
826 bci.dtc = dtc;
827 bci.radius = prefs_get_int_attribute_limited("tools.paintbucket", "autogap", 0, 0, 3);
828 bci.max_queue_size = width * height;
829 bci.max_vertical_check = prefs_get_int_attribute_limited("tools.paintbucket", "fillaccuracy", 0, 0, 5);
831 bool first_run = true;
833 // Time values to measure each buffer's paint time
834 // GTimeVal tstart, tfinish;
836 // g_get_current_time (&tstart);
838 while (!color_queue.empty() && !aborted) {
839 NR::Point color_point = color_queue.front();
840 color_queue.pop();
842 unsigned char *orig_px = get_pixel(px, (int)color_point[NR::X], (int)color_point[NR::Y], width);
843 unsigned char orig_color[4];
844 for (int i = 0; i < 4; i++) { orig_color[i] = orig_px[i]; }
846 unsigned char merged_orig[3];
848 merge_pixel_with_background(orig_color, dtc, merged_orig);
850 bci.merged_orig_pixel = merged_orig;
852 unsigned char *trace_t = get_pixel(trace_px, (int)color_point[NR::X], (int)color_point[NR::Y], width);
853 if (!is_pixel_checked(trace_t) && !is_pixel_colored(trace_t)) {
854 if (check_if_pixel_is_paintable(px, trace_px, (int)color_point[NR::X], (int)color_point[NR::Y], orig_color, bci)) {
855 fill_queue.push_front(color_point);
857 if (!first_run) {
858 for (int y = 0; y < height; y++) {
859 for (int x = 0; x < width; x++) {
860 trace_t = get_pixel(trace_px, x, y, width);
861 clear_pixel_paintability(trace_t);
862 }
863 }
864 }
865 first_run = false;
866 }
867 }
869 while (!fill_queue.empty() && !aborted) {
870 NR::Point cp = fill_queue.front();
871 fill_queue.pop_front();
873 unsigned char *trace_t = get_pixel(trace_px, (int)cp[NR::X], (int)cp[NR::Y], width);
874 if (!is_pixel_checked(trace_t)) {
875 mark_pixel_checked(trace_t);
877 int x = (int)cp[NR::X];
878 int y = (int)cp[NR::Y];
880 if (y == 0) {
881 if (bbox->min()[NR::Y] > screen.min()[NR::Y]) {
882 aborted = true; break;
883 } else {
884 reached_screen_boundary = true;
885 }
886 }
888 if (y == y_limit) {
889 if (bbox->max()[NR::Y] < screen.max()[NR::Y]) {
890 aborted = true; break;
891 } else {
892 reached_screen_boundary = true;
893 }
894 }
896 bci.is_left = true;
897 bci.x = x;
898 bci.y = y;
900 ScanlineCheckResult result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci);
902 switch (result) {
903 case SCANLINE_CHECK_ABORTED:
904 aborted = true;
905 break;
906 case SCANLINE_CHECK_BOUNDARY:
907 reached_screen_boundary = true;
908 break;
909 default:
910 break;
911 }
913 bci.is_left = false;
914 bci.x = x + 1;
916 result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci);
918 switch (result) {
919 case SCANLINE_CHECK_ABORTED:
920 aborted = true;
921 break;
922 case SCANLINE_CHECK_BOUNDARY:
923 reached_screen_boundary = true;
924 break;
925 default:
926 break;
927 }
928 }
929 }
930 }
932 // g_get_current_time (&tfinish);
934 // Remember the slowest_buffer of this paint.
935 // glong this_buffer = (tfinish.tv_sec - tstart.tv_sec) * 1000000 + (tfinish.tv_usec - tstart.tv_usec);
937 // g_message("time: %ld", this_buffer);
939 g_free(px);
941 if (aborted) {
942 g_free(trace_px);
943 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
944 return;
945 }
947 if (reached_screen_boundary) {
948 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."));
949 }
951 GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(trace_px,
952 GDK_COLORSPACE_RGB,
953 TRUE,
954 8, width, height, width * 4,
955 (GdkPixbufDestroyNotify)g_free,
956 NULL);
958 NR::Matrix inverted_affine = NR::Matrix(affine).inverse();
960 do_trace(pixbuf, desktop, inverted_affine, union_with_selection);
962 g_free(trace_px);
964 sp_document_done(document, SP_VERB_CONTEXT_PAINTBUCKET, _("Fill bounded area"));
965 }
967 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
968 {
969 gint ret = FALSE;
971 SPDesktop *desktop = event_context->desktop;
973 switch (event->type) {
974 case GDK_BUTTON_PRESS:
975 if (event->button.state & GDK_CONTROL_MASK) {
976 NR::Point const button_w(event->button.x,
977 event->button.y);
979 SPItem *item = sp_event_context_find_item (desktop, button_w, TRUE, TRUE);
981 Inkscape::XML::Node *pathRepr = SP_OBJECT_REPR(item);
982 /* Set style */
983 sp_desktop_apply_style_tool (desktop, pathRepr, "tools.paintbucket", false);
984 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET, _("Set style on object"));
985 ret = TRUE;
986 }
987 break;
988 default:
989 break;
990 }
992 if (((SPEventContextClass *) parent_class)->item_handler) {
993 ret = ((SPEventContextClass *) parent_class)->item_handler(event_context, item, event);
994 }
996 return ret;
997 }
999 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event)
1000 {
1001 static bool dragging;
1003 gint ret = FALSE;
1004 SPDesktop *desktop = event_context->desktop;
1006 switch (event->type) {
1007 case GDK_BUTTON_PRESS:
1008 if ( event->button.button == 1 ) {
1009 if (!(event->button.state & GDK_CONTROL_MASK)) {
1010 NR::Point const button_w(event->button.x,
1011 event->button.y);
1013 if (Inkscape::have_viable_layer(desktop, event_context->defaultMessageContext())) {
1014 // save drag origin
1015 event_context->xp = (gint) button_w[NR::X];
1016 event_context->yp = (gint) button_w[NR::Y];
1017 event_context->within_tolerance = true;
1019 dragging = true;
1021 NR::Point const p(desktop->w2d(button_w));
1022 Inkscape::Rubberband::get()->setMode(RUBBERBAND_MODE_TOUCHPATH);
1023 Inkscape::Rubberband::get()->start(desktop, p);
1024 }
1025 }
1026 }
1027 case GDK_MOTION_NOTIFY:
1028 if ( dragging
1029 && ( event->motion.state & GDK_BUTTON1_MASK ) )
1030 {
1031 if ( event_context->within_tolerance
1032 && ( abs( (gint) event->motion.x - event_context->xp ) < event_context->tolerance )
1033 && ( abs( (gint) event->motion.y - event_context->yp ) < event_context->tolerance ) ) {
1034 break; // do not drag if we're within tolerance from origin
1035 }
1037 event_context->within_tolerance = false;
1039 NR::Point const motion_pt(event->motion.x, event->motion.y);
1040 NR::Point const p(desktop->w2d(motion_pt));
1041 if (Inkscape::Rubberband::get()->is_started()) {
1042 Inkscape::Rubberband::get()->move(p);
1043 event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Draw over</b> areas to add to fill, hold <b>Alt</b> for touch fill"));
1044 gobble_motion_events(GDK_BUTTON1_MASK);
1045 }
1046 }
1047 break;
1049 case GDK_BUTTON_RELEASE:
1050 if ( event->button.button == 1 ) {
1051 Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
1052 if (r->is_started()) {
1053 // set "busy" cursor
1054 desktop->setWaitingCursor();
1056 if (SP_IS_EVENT_CONTEXT(event_context)) {
1057 // Since setWaitingCursor runs main loop iterations, we may have already left this tool!
1058 // So check if the tool is valid before doing anything
1059 dragging = false;
1061 bool is_point_fill = event_context->within_tolerance;
1062 bool is_touch_fill = event->button.state & GDK_MOD1_MASK;
1064 sp_flood_do_flood_fill(event_context, event, event->button.state & GDK_SHIFT_MASK, is_point_fill, is_touch_fill);
1066 desktop->clearWaitingCursor();
1067 // restore cursor when done; note that it may already be different if e.g. user
1068 // switched to another tool during interruptible tracing or drawing, in which case do nothing
1070 ret = TRUE;
1071 }
1073 r->stop();
1074 event_context->defaultMessageContext()->clear();
1075 }
1076 }
1077 break;
1078 case GDK_KEY_PRESS:
1079 switch (get_group0_keyval (&event->key)) {
1080 case GDK_Up:
1081 case GDK_Down:
1082 case GDK_KP_Up:
1083 case GDK_KP_Down:
1084 // prevent the zoom field from activation
1085 if (!MOD__CTRL_ONLY)
1086 ret = TRUE;
1087 break;
1088 default:
1089 break;
1090 }
1091 break;
1092 default:
1093 break;
1094 }
1096 if (!ret) {
1097 if (((SPEventContextClass *) parent_class)->root_handler) {
1098 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1099 }
1100 }
1102 return ret;
1103 }
1106 static void sp_flood_finish(SPFloodContext *rc)
1107 {
1108 rc->_message_context->clear();
1110 if ( rc->item != NULL ) {
1111 SPDesktop * desktop;
1113 desktop = SP_EVENT_CONTEXT_DESKTOP(rc);
1115 SP_OBJECT(rc->item)->updateRepr();
1117 sp_canvas_end_forced_full_redraws(desktop->canvas);
1119 sp_desktop_selection(desktop)->set(rc->item);
1120 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET,
1121 _("Fill bounded area"));
1123 rc->item = NULL;
1124 }
1125 }
1127 void flood_channels_set_channels( gint channels )
1128 {
1129 prefs_set_int_attribute("tools.paintbucket", "channels", channels);
1130 }
1132 /*
1133 Local Variables:
1134 mode:c++
1135 c-file-style:"stroustrup"
1136 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1137 indent-tabs-mode:nil
1138 fill-column:99
1139 End:
1140 */
1141 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :