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 is_pixel_checked(unsigned char *t) { return t[0] == 1; }
311 static bool is_pixel_queued(unsigned char *t) { return t[1] == 1; }
312 static bool is_pixel_paintability_checked(unsigned char *t) { return t[2] != 0; }
313 static bool is_pixel_paintable(unsigned char *t) { return t[2] == 1; }
314 static bool is_pixel_colored(unsigned char *t) { return t[3] == 255; }
316 static void mark_pixel_checked(unsigned char *t) { t[0] = 1; }
317 static void mark_pixel_queued(unsigned char *t) { t[1] = 1; }
318 static void mark_pixel_paintable(unsigned char *t) { t[2] = 1; }
319 static void mark_pixel_not_paintable(unsigned char *t) { t[2] = 2; }
320 static void mark_pixel_colored(unsigned char *t) { t[3] = 255; }
322 static void clear_pixel_paintability(unsigned char *t) { t[2] = 0; }
324 struct bitmap_coords_info {
325 bool is_left;
326 int x;
327 int y;
328 int y_limit;
329 int width;
330 int height;
331 int threshold;
332 int radius;
333 PaintBucketChannels method;
334 unsigned char *dtc;
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, guchar *trace_px, int x, int y, unsigned char *orig_color, bitmap_coords_info bci) {
342 unsigned char *trace_t = get_pixel(trace_px, x, y, bci.width);
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.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 bool try_add_to_queue(std::deque<NR::Point> *fill_queue, guchar *px, guchar *trace_px, unsigned char *orig, int x, int y, int width, bitmap_coords_info bci, unsigned int max_queue_size) {
358 unsigned char *trace_t = get_pixel(trace_px, x, y, width);
359 if (!(is_pixel_checked(trace_t) || is_pixel_queued(trace_t))) {
360 if (check_if_pixel_is_paintable(px, trace_px, x, y, orig, bci)) {
361 if ((fill_queue->size() < max_queue_size)) {
362 fill_queue->push_back(NR::Point(x, y));
363 mark_pixel_queued(trace_t);
364 }
365 }
366 }
367 return true;
368 }
370 static void do_trace(GdkPixbuf *px, SPDesktop *desktop, NR::Matrix transform, bool union_with_selection) {
371 SPDocument *document = sp_desktop_document(desktop);
373 Inkscape::Trace::Potrace::PotraceTracingEngine pte;
375 pte.setTraceType(Inkscape::Trace::Potrace::TRACE_BRIGHTNESS);
376 pte.setInvert(false);
378 Glib::RefPtr<Gdk::Pixbuf> pixbuf = Glib::wrap(px, true);
380 std::vector<Inkscape::Trace::TracingEngineResult> results = pte.trace(pixbuf);
382 Inkscape::XML::Node *layer_repr = SP_GROUP(desktop->currentLayer())->repr;
383 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
385 long totalNodeCount = 0L;
387 double offset = prefs_get_double_attribute("tools.paintbucket", "offset", 0.0);
389 for (unsigned int i=0 ; i<results.size() ; i++) {
390 Inkscape::Trace::TracingEngineResult result = results[i];
391 totalNodeCount += result.getNodeCount();
393 Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path");
394 /* Set style */
395 sp_desktop_apply_style_tool (desktop, pathRepr, "tools.paintbucket", false);
397 NArtBpath *bpath = sp_svg_read_path(result.getPathData().c_str());
398 Path *path = bpath_to_Path(bpath);
399 g_free(bpath);
401 if (offset != 0) {
403 Shape *path_shape = new Shape();
405 path->ConvertWithBackData(0.03);
406 path->Fill(path_shape, 0);
407 delete path;
409 Shape *expanded_path_shape = new Shape();
411 expanded_path_shape->ConvertToShape(path_shape, fill_nonZero);
412 path_shape->MakeOffset(expanded_path_shape, offset * desktop->current_zoom(), join_round, 4);
413 expanded_path_shape->ConvertToShape(path_shape, fill_positive);
415 Path *expanded_path = new Path();
417 expanded_path->Reset();
418 expanded_path_shape->ConvertToForme(expanded_path);
419 expanded_path->ConvertEvenLines(1.0);
420 expanded_path->Simplify(1.0);
422 delete path_shape;
423 delete expanded_path_shape;
425 gchar *str = expanded_path->svg_dump_path();
426 if (str && *str) {
427 pathRepr->setAttribute("d", str);
428 g_free(str);
429 } else {
430 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Too much inset</b>, the result is empty."));
431 Inkscape::GC::release(pathRepr);
432 g_free(str);
433 return;
434 }
436 delete expanded_path;
438 } else {
439 gchar *str = path->svg_dump_path();
440 delete path;
441 pathRepr->setAttribute("d", str);
442 g_free(str);
443 }
445 layer_repr->addChild(pathRepr, NULL);
447 SPObject *reprobj = document->getObjectByRepr(pathRepr);
448 if (reprobj) {
449 sp_item_write_transform(SP_ITEM(reprobj), pathRepr, transform, NULL);
451 // premultiply the item transform by the accumulated parent transform in the paste layer
452 NR::Matrix local = sp_item_i2doc_affine(SP_GROUP(desktop->currentLayer()));
453 if (!local.test_identity()) {
454 gchar const *t_str = pathRepr->attribute("transform");
455 NR::Matrix item_t (NR::identity());
456 if (t_str)
457 sp_svg_transform_read(t_str, &item_t);
458 item_t *= local.inverse();
459 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
460 gchar *affinestr=sp_svg_transform_write(item_t);
461 pathRepr->setAttribute("transform", affinestr);
462 g_free(affinestr);
463 }
465 Inkscape::Selection *selection = sp_desktop_selection(desktop);
467 pathRepr->setPosition(-1);
469 if (union_with_selection) {
470 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)));
471 selection->add(reprobj);
472 sp_selected_path_union_skip_undo();
473 } else {
474 desktop->messageStack()->flashF(Inkscape::WARNING_MESSAGE, _("Area filled, path with <b>%d</b> nodes created."), sp_nodes_in_path(SP_PATH(reprobj)));
475 selection->set(reprobj);
476 }
478 }
480 Inkscape::GC::release(pathRepr);
482 }
483 }
485 enum ScanlineCheckResult {
486 SCANLINE_CHECK_OK,
487 SCANLINE_CHECK_ABORTED,
488 SCANLINE_CHECK_BOUNDARY
489 };
491 static bool coords_in_range(int x, int y, bitmap_coords_info bci) {
492 return (x >= 0)
493 && (x < bci.width)
494 && (y >= 0)
495 && (y < bci.height);
496 }
498 #define PAINT_DIRECTION_LEFT 1
499 #define PAINT_DIRECTION_RIGHT 2
500 #define PAINT_DIRECTION_UP 4
501 #define PAINT_DIRECTION_DOWN 8
502 #define PAINT_DIRECTION_ALL 15
504 static unsigned int paint_pixel(guchar *px, guchar *trace_px, unsigned char *orig_color, bitmap_coords_info bci) {
505 unsigned char *trace_t;
507 if (bci.radius == 0) {
508 trace_t = get_pixel(trace_px, bci.x, bci.y, bci.width);
509 mark_pixel_colored(trace_t);
510 return PAINT_DIRECTION_ALL;
511 } else {
512 bool can_paint_up = true;
513 bool can_paint_down = true;
514 bool can_paint_left = true;
515 bool can_paint_right = true;
517 for (int y = -bci.radius; y <= bci.radius; y++) {
518 int ty = bci.y + y;
519 for (int x = -bci.radius; x <= bci.radius; x++) {
520 int tx = bci.x + x;
522 if (coords_in_range(tx, ty, bci)) {
523 trace_t = get_pixel(trace_px, tx, ty, bci.width);
524 if (!is_pixel_colored(trace_t)) {
525 if (check_if_pixel_is_paintable(px, trace_px, tx, ty, orig_color, bci)) {
526 mark_pixel_colored(trace_t);
527 } else {
528 if (x < 0) { can_paint_left = false; }
529 if (x > 0) { can_paint_right = false; }
530 if (y < 0) { can_paint_up = false; }
531 if (y > 0) { can_paint_down = false; }
532 }
533 }
534 }
535 }
536 }
538 unsigned int paint_directions = 0;
539 if (can_paint_left) { paint_directions += PAINT_DIRECTION_LEFT; }
540 if (can_paint_right) { paint_directions += PAINT_DIRECTION_RIGHT; }
541 if (can_paint_up) { paint_directions += PAINT_DIRECTION_UP; }
542 if (can_paint_down) { paint_directions += PAINT_DIRECTION_DOWN; }
544 return paint_directions;
545 }
546 }
548 static unsigned int paint_leading_edge(guchar *px, guchar *trace_px, unsigned char *orig_color, bitmap_coords_info bci, unsigned int direction) {
549 unsigned char *trace_t;
551 if (bci.radius > 0) {
552 bool can_paint_up = true;
553 bool can_paint_down = true;
554 bool can_paint_left = true;
555 bool can_paint_right = true;
557 int tx = bci.x;
559 switch (direction) {
560 case PAINT_DIRECTION_LEFT:
561 tx = bci.x - bci.radius;
562 break;
563 case PAINT_DIRECTION_RIGHT:
564 tx = bci.x + bci.radius;
565 break;
566 }
568 for (int y = -bci.radius; y <= bci.radius; y++) {
569 int ty = bci.y + y;
570 if (coords_in_range(tx, ty, bci)) {
571 trace_t = get_pixel(trace_px, tx, ty, bci.width);
572 if (!is_pixel_colored(trace_t)) {
573 if (check_if_pixel_is_paintable(px, trace_px, tx, ty, orig_color, bci)) {
574 mark_pixel_colored(trace_t);
575 } else {
576 if (direction == PAINT_DIRECTION_LEFT) { can_paint_left = false; }
577 if (direction == PAINT_DIRECTION_RIGHT) { can_paint_right = false; }
578 if (y < 0) { can_paint_up = false; }
579 if (y > 0) { can_paint_down = false; }
580 }
581 }
582 }
583 }
585 unsigned int paint_directions = 0;
586 if (can_paint_left) { paint_directions += PAINT_DIRECTION_LEFT; }
587 if (can_paint_right) { paint_directions += PAINT_DIRECTION_RIGHT; }
588 if (can_paint_up) { paint_directions += PAINT_DIRECTION_UP; }
589 if (can_paint_down) { paint_directions += PAINT_DIRECTION_DOWN; }
591 return paint_directions;
592 } else {
593 return 0;
594 }
595 }
597 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) {
598 bool aborted = false;
599 bool reached_screen_boundary = false;
600 bool ok;
602 bool keep_tracing;
603 bool initial_paint = true;
605 int vertical_check_count = 0;
607 do {
608 ok = false;
609 if (bci.is_left) {
610 keep_tracing = (bci.x >= 0);
611 } else {
612 keep_tracing = (bci.x < bci.width);
613 }
615 if (keep_tracing) {
616 if (check_if_pixel_is_paintable(px, trace_px, bci.x, bci.y, orig_color, bci)) {
617 unsigned int paint_directions;
618 if ((bci.radius == 0) || ((bci.radius > 0) && initial_paint)) {
619 paint_directions = paint_pixel(px, trace_px, orig_color, bci);
620 } else {
621 if (bci.is_left) {
622 paint_directions = paint_leading_edge(px, trace_px, orig_color, bci, PAINT_DIRECTION_LEFT);
623 } else {
624 paint_directions = paint_leading_edge(px, trace_px, orig_color, bci, PAINT_DIRECTION_RIGHT);
625 }
626 }
627 initial_paint = false;
629 if (vertical_check_count == 0) {
630 if (paint_directions & PAINT_DIRECTION_UP) {
631 try_add_to_queue(fill_queue, px, trace_px, orig_color, bci.x, bci.y - 1, bci.width, bci, bci.max_queue_size);
632 }
633 if (paint_directions & PAINT_DIRECTION_DOWN) {
634 try_add_to_queue(fill_queue, px, trace_px, orig_color, bci.x, bci.y + 1, bci.width, bci, bci.max_queue_size);
635 }
636 }
638 if (bci.max_vertical_check > 0) {
639 vertical_check_count = (vertical_check_count + 1) % bci.max_vertical_check;
640 }
642 if (bci.is_left) {
643 if (paint_directions & PAINT_DIRECTION_LEFT) {
644 bci.x -= 1;
645 ok = true;
646 }
647 } else {
648 if (paint_directions & PAINT_DIRECTION_RIGHT) {
649 bci.x += 1;
650 ok = true;
651 }
652 }
653 }
654 } else {
655 if (bci.bbox.min()[NR::X] > bci.screen.min()[NR::X]) {
656 aborted = true; break;
657 } else {
658 reached_screen_boundary = true;
659 }
660 }
661 } while (ok);
663 if (aborted) { return SCANLINE_CHECK_ABORTED; }
664 if (reached_screen_boundary) { return SCANLINE_CHECK_BOUNDARY; }
665 return SCANLINE_CHECK_OK;
666 }
668 static void sp_flood_do_flood_fill(SPEventContext *event_context, GdkEvent *event, bool union_with_selection, bool is_point_fill, bool is_touch_fill) {
669 SPDesktop *desktop = event_context->desktop;
670 SPDocument *document = sp_desktop_document(desktop);
672 /* Create new arena */
673 NRArena *arena = NRArena::create();
674 unsigned dkey = sp_item_display_key_new(1);
676 sp_document_ensure_up_to_date (document);
678 SPItem *document_root = SP_ITEM(SP_DOCUMENT_ROOT(document));
679 NR::Maybe<NR::Rect> bbox = document_root->getBounds(NR::identity());
681 if (!bbox) {
682 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
683 return;
684 }
686 double zoom_scale = desktop->current_zoom();
687 double padding = 1.6;
689 NR::Rect screen = desktop->get_display_area();
691 int width = (int)ceil(screen.extent(NR::X) * zoom_scale * padding);
692 int height = (int)ceil(screen.extent(NR::Y) * zoom_scale * padding);
694 NR::Point origin(screen.min()[NR::X],
695 sp_document_height(document) - screen.extent(NR::Y) - screen.min()[NR::Y]);
697 origin[NR::X] = origin[NR::X] + (screen.extent(NR::X) * ((1 - padding) / 2));
698 origin[NR::Y] = origin[NR::Y] + (screen.extent(NR::Y) * ((1 - padding) / 2));
700 NR::scale scale(zoom_scale, zoom_scale);
701 NR::Matrix affine = scale * NR::translate(-origin * scale);
703 /* Create ArenaItems and set transform */
704 NRArenaItem *root = sp_item_invoke_show(SP_ITEM(sp_document_root(document)), arena, dkey, SP_ITEM_SHOW_DISPLAY);
705 nr_arena_item_set_transform(NR_ARENA_ITEM(root), affine);
707 NRGC gc(NULL);
708 nr_matrix_set_identity(&gc.transform);
710 NRRectL final_bbox;
711 final_bbox.x0 = 0;
712 final_bbox.y0 = 0;//row;
713 final_bbox.x1 = width;
714 final_bbox.y1 = height;//row + num_rows;
716 nr_arena_item_invoke_update(root, &final_bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
718 guchar *px = g_new(guchar, 4 * width * height);
720 NRPixBlock B;
721 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
722 final_bbox.x0, final_bbox.y0, final_bbox.x1, final_bbox.y1,
723 px, 4 * width, FALSE, FALSE );
725 SPNamedView *nv = sp_desktop_namedview(desktop);
726 unsigned long bgcolor = nv->pagecolor;
728 unsigned char dtc[4];
729 dtc[0] = NR_RGBA32_R(bgcolor);
730 dtc[1] = NR_RGBA32_G(bgcolor);
731 dtc[2] = NR_RGBA32_B(bgcolor);
732 dtc[3] = NR_RGBA32_A(bgcolor);
734 for (int fy = 0; fy < height; fy++) {
735 guchar *p = NR_PIXBLOCK_PX(&B) + fy * B.rs;
736 for (int fx = 0; fx < width; fx++) {
737 for (int i = 0; i < 4; i++) {
738 *p++ = dtc[i];
739 }
740 }
741 }
743 nr_arena_item_invoke_render(NULL, root, &final_bbox, &B, NR_ARENA_ITEM_RENDER_NO_CACHE );
744 nr_pixblock_release(&B);
746 // Hide items
747 sp_item_invoke_hide(SP_ITEM(sp_document_root(document)), dkey);
749 nr_arena_item_unref(root);
750 nr_object_unref((NRObject *) arena);
752 guchar *trace_px = g_new(guchar, 4 * width * height);
753 memset(trace_px, 0x00, 4 * width * height);
755 std::deque<NR::Point> fill_queue;
756 std::queue<NR::Point> color_queue;
758 std::vector<NR::Point> fill_points;
760 if (is_point_fill) {
761 fill_points.push_back(NR::Point(event->button.x, event->button.y));
762 } else {
763 Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
764 fill_points = r->getPoints();
765 }
767 for (unsigned int i = 0; i < fill_points.size(); i++) {
768 NR::Point pw = NR::Point(fill_points[i][NR::X] / zoom_scale, sp_document_height(document) + (fill_points[i][NR::Y] / zoom_scale)) * affine;
770 pw[NR::X] = (int)MIN(width - 1, MAX(0, pw[NR::X]));
771 pw[NR::Y] = (int)MIN(height - 1, MAX(0, pw[NR::Y]));
773 if (is_touch_fill) {
774 if (i == 0) {
775 color_queue.push(pw);
776 } else {
777 fill_queue.push_back(pw);
778 }
779 } else {
780 color_queue.push(pw);
781 }
782 }
784 bool aborted = false;
785 int y_limit = height - 1;
787 PaintBucketChannels method = (PaintBucketChannels)prefs_get_int_attribute("tools.paintbucket", "channels", 0);
788 int threshold = prefs_get_int_attribute_limited("tools.paintbucket", "threshold", 1, 0, 100);
790 switch(method) {
791 case FLOOD_CHANNELS_ALPHA:
792 case FLOOD_CHANNELS_RGB:
793 case FLOOD_CHANNELS_R:
794 case FLOOD_CHANNELS_G:
795 case FLOOD_CHANNELS_B:
796 threshold = (255 * threshold) / 100;
797 break;
798 case FLOOD_CHANNELS_H:
799 case FLOOD_CHANNELS_S:
800 case FLOOD_CHANNELS_L:
801 break;
802 }
804 bool reached_screen_boundary = false;
806 bitmap_coords_info bci;
808 bci.y_limit = y_limit;
809 bci.width = width;
810 bci.height = height;
811 bci.threshold = threshold;
812 bci.method = method;
813 bci.bbox = *bbox;
814 bci.screen = screen;
815 bci.dtc = dtc;
816 bci.radius = prefs_get_int_attribute_limited("tools.paintbucket", "autogap", 0, 0, 3);
817 bci.max_queue_size = width * height;
818 bci.max_vertical_check = prefs_get_int_attribute_limited("tools.paintbucket", "fillaccuracy", 0, 0, 5);
820 bool first_run = true;
822 // Time values to measure each buffer's paint time
823 // GTimeVal tstart, tfinish;
825 // g_get_current_time (&tstart);
827 while (!color_queue.empty() && !aborted) {
828 NR::Point color_point = color_queue.front();
829 color_queue.pop();
831 unsigned char *orig_px = get_pixel(px, (int)color_point[NR::X], (int)color_point[NR::Y], width);
832 unsigned char orig_color[4];
833 for (int i = 0; i < 4; i++) { orig_color[i] = orig_px[i]; }
835 unsigned char merged_orig[4];
837 merge_pixel_with_background(orig_color, dtc, merged_orig);
839 unsigned char *trace_t = get_pixel(trace_px, (int)color_point[NR::X], (int)color_point[NR::Y], width);
840 if (!is_pixel_checked(trace_t) && !is_pixel_colored(trace_t)) {
841 fill_queue.push_front(color_point);
843 if (!first_run) {
844 for (int y = 0; y < height; y++) {
845 for (int x = 0; x < width; x++) {
846 trace_t = get_pixel(trace_px, x, y, width);
847 clear_pixel_paintability(trace_t);
848 }
849 }
850 }
851 first_run = false;
852 }
854 while (!fill_queue.empty() && !aborted) {
855 NR::Point cp = fill_queue.front();
856 fill_queue.pop_front();
858 unsigned char *trace_t = get_pixel(trace_px, (int)cp[NR::X], (int)cp[NR::Y], width);
859 if (!is_pixel_checked(trace_t)) {
860 mark_pixel_checked(trace_t);
862 int x = (int)cp[NR::X];
863 int y = (int)cp[NR::Y];
865 // same color at this point
866 if (check_if_pixel_is_paintable(px, trace_px, x, y, orig_color, bci)) {
867 if (y == 0) {
868 if (bbox->min()[NR::Y] > screen.min()[NR::Y]) {
869 aborted = true; break;
870 } else {
871 reached_screen_boundary = true;
872 }
873 }
875 if (y == y_limit) {
876 if (bbox->max()[NR::Y] < screen.max()[NR::Y]) {
877 aborted = true; break;
878 } else {
879 reached_screen_boundary = true;
880 }
881 }
883 bci.is_left = true;
884 bci.x = x;
885 bci.y = y;
887 ScanlineCheckResult result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci);
889 switch (result) {
890 case SCANLINE_CHECK_ABORTED:
891 aborted = true;
892 break;
893 case SCANLINE_CHECK_BOUNDARY:
894 reached_screen_boundary = true;
895 break;
896 default:
897 break;
898 }
900 bci.is_left = false;
901 bci.x = x + 1;
902 bci.y = y;
904 result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci);
906 switch (result) {
907 case SCANLINE_CHECK_ABORTED:
908 aborted = true;
909 break;
910 case SCANLINE_CHECK_BOUNDARY:
911 reached_screen_boundary = true;
912 break;
913 default:
914 break;
915 }
916 }
917 }
918 }
919 }
921 // g_get_current_time (&tfinish);
923 // Remember the slowest_buffer of this paint.
924 // glong this_buffer = (tfinish.tv_sec - tstart.tv_sec) * 1000000 + (tfinish.tv_usec - tstart.tv_usec);
926 // g_message("time: %ld", this_buffer);
928 g_free(px);
930 if (aborted) {
931 g_free(trace_px);
932 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
933 return;
934 }
936 if (reached_screen_boundary) {
937 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."));
938 }
940 GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(trace_px,
941 GDK_COLORSPACE_RGB,
942 TRUE,
943 8, width, height, width * 4,
944 (GdkPixbufDestroyNotify)g_free,
945 NULL);
947 NR::Matrix inverted_affine = NR::Matrix(affine).inverse();
949 do_trace(pixbuf, desktop, inverted_affine, union_with_selection);
951 g_free(trace_px);
953 sp_document_done(document, SP_VERB_CONTEXT_PAINTBUCKET, _("Fill bounded area"));
954 }
956 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
957 {
958 gint ret = FALSE;
960 SPDesktop *desktop = event_context->desktop;
962 switch (event->type) {
963 case GDK_BUTTON_PRESS:
964 if (event->button.state & GDK_CONTROL_MASK) {
965 NR::Point const button_w(event->button.x,
966 event->button.y);
968 SPItem *item = sp_event_context_find_item (desktop, button_w, TRUE, TRUE);
970 Inkscape::XML::Node *pathRepr = SP_OBJECT_REPR(item);
971 /* Set style */
972 sp_desktop_apply_style_tool (desktop, pathRepr, "tools.paintbucket", false);
973 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET, _("Set style on object"));
974 ret = TRUE;
975 }
976 break;
977 default:
978 break;
979 }
981 if (((SPEventContextClass *) parent_class)->item_handler) {
982 ret = ((SPEventContextClass *) parent_class)->item_handler(event_context, item, event);
983 }
985 return ret;
986 }
988 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event)
989 {
990 static bool dragging;
992 gint ret = FALSE;
993 SPDesktop *desktop = event_context->desktop;
995 switch (event->type) {
996 case GDK_BUTTON_PRESS:
997 if ( event->button.button == 1 ) {
998 if (!(event->button.state & GDK_CONTROL_MASK)) {
999 NR::Point const button_w(event->button.x,
1000 event->button.y);
1002 if (Inkscape::have_viable_layer(desktop, event_context->defaultMessageContext())) {
1003 // save drag origin
1004 event_context->xp = (gint) button_w[NR::X];
1005 event_context->yp = (gint) button_w[NR::Y];
1006 event_context->within_tolerance = true;
1008 dragging = true;
1010 NR::Point const p(desktop->w2d(button_w));
1011 Inkscape::Rubberband::get()->setMode(RUBBERBAND_MODE_TOUCHPATH);
1012 Inkscape::Rubberband::get()->start(desktop, p);
1013 }
1014 }
1015 }
1016 case GDK_MOTION_NOTIFY:
1017 if ( dragging
1018 && ( event->motion.state & GDK_BUTTON1_MASK ) )
1019 {
1020 if ( event_context->within_tolerance
1021 && ( abs( (gint) event->motion.x - event_context->xp ) < event_context->tolerance )
1022 && ( abs( (gint) event->motion.y - event_context->yp ) < event_context->tolerance ) ) {
1023 break; // do not drag if we're within tolerance from origin
1024 }
1026 event_context->within_tolerance = false;
1028 NR::Point const motion_pt(event->motion.x, event->motion.y);
1029 NR::Point const p(desktop->w2d(motion_pt));
1030 if (Inkscape::Rubberband::get()->is_started()) {
1031 Inkscape::Rubberband::get()->move(p);
1032 event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Draw over</b> areas to add to fill, hold <b>Alt</b> for touch fill"));
1033 gobble_motion_events(GDK_BUTTON1_MASK);
1034 }
1035 }
1036 break;
1038 case GDK_BUTTON_RELEASE:
1039 if ( event->button.button == 1 ) {
1040 Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
1041 if (r->is_started()) {
1042 // set "busy" cursor
1043 desktop->setWaitingCursor();
1045 if (SP_IS_EVENT_CONTEXT(event_context)) {
1046 // Since setWaitingCursor runs main loop iterations, we may have already left this tool!
1047 // So check if the tool is valid before doing anything
1048 dragging = false;
1050 bool is_point_fill = event_context->within_tolerance;
1051 bool is_touch_fill = event->button.state & GDK_MOD1_MASK;
1053 sp_flood_do_flood_fill(event_context, event, event->button.state & GDK_SHIFT_MASK, is_point_fill, is_touch_fill);
1055 desktop->clearWaitingCursor();
1056 // restore cursor when done; note that it may already be different if e.g. user
1057 // switched to another tool during interruptible tracing or drawing, in which case do nothing
1059 ret = TRUE;
1060 }
1062 r->stop();
1063 event_context->defaultMessageContext()->clear();
1064 }
1065 }
1066 break;
1067 case GDK_KEY_PRESS:
1068 switch (get_group0_keyval (&event->key)) {
1069 case GDK_Up:
1070 case GDK_Down:
1071 case GDK_KP_Up:
1072 case GDK_KP_Down:
1073 // prevent the zoom field from activation
1074 if (!MOD__CTRL_ONLY)
1075 ret = TRUE;
1076 break;
1077 default:
1078 break;
1079 }
1080 break;
1081 default:
1082 break;
1083 }
1085 if (!ret) {
1086 if (((SPEventContextClass *) parent_class)->root_handler) {
1087 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1088 }
1089 }
1091 return ret;
1092 }
1095 static void sp_flood_finish(SPFloodContext *rc)
1096 {
1097 rc->_message_context->clear();
1099 if ( rc->item != NULL ) {
1100 SPDesktop * desktop;
1102 desktop = SP_EVENT_CONTEXT_DESKTOP(rc);
1104 SP_OBJECT(rc->item)->updateRepr();
1106 sp_canvas_end_forced_full_redraws(desktop->canvas);
1108 sp_desktop_selection(desktop)->set(rc->item);
1109 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET,
1110 _("Fill bounded area"));
1112 rc->item = NULL;
1113 }
1114 }
1116 void flood_channels_set_channels( gint channels )
1117 {
1118 prefs_set_int_attribute("tools.paintbucket", "channels", channels);
1119 }
1121 /*
1122 Local Variables:
1123 mode:c++
1124 c-file-style:"stroustrup"
1125 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1126 indent-tabs-mode:nil
1127 fill-column:99
1128 End:
1129 */
1130 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :