1fc20768463a433697bed663889fdcc3cbc544c7
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 };
339 static bool check_if_pixel_is_paintable(guchar *px, guchar *trace_px, int x, int y, unsigned char *orig_color, bitmap_coords_info bci) {
340 unsigned char *trace_t = get_pixel(trace_px, x, y, bci.width);
341 if (is_pixel_paintability_checked(trace_t)) {
342 return is_pixel_paintable(trace_t);
343 } else {
344 unsigned char *t = get_pixel(px, x, y, bci.width);
345 if (compare_pixels(t, orig_color, bci.dtc, bci.threshold, bci.method)) {
346 mark_pixel_paintable(trace_t);
347 return true;
348 } else {
349 mark_pixel_not_paintable(trace_t);
350 return false;
351 }
352 }
353 }
355 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) {
356 unsigned char *trace_t = get_pixel(trace_px, x, y, width);
357 if (!(is_pixel_checked(trace_t) || is_pixel_queued(trace_t))) {
358 if (check_if_pixel_is_paintable(px, trace_px, x, y, orig, bci)) {
359 if ((fill_queue->size() < max_queue_size)) {
360 fill_queue->push_back(NR::Point(x, y));
361 mark_pixel_queued(trace_t);
362 }
363 }
364 }
365 return true;
366 }
368 static void do_trace(GdkPixbuf *px, SPDesktop *desktop, NR::Matrix transform, bool union_with_selection) {
369 SPDocument *document = sp_desktop_document(desktop);
371 Inkscape::Trace::Potrace::PotraceTracingEngine pte;
373 pte.setTraceType(Inkscape::Trace::Potrace::TRACE_BRIGHTNESS);
374 pte.setInvert(false);
376 Glib::RefPtr<Gdk::Pixbuf> pixbuf = Glib::wrap(px, true);
378 std::vector<Inkscape::Trace::TracingEngineResult> results = pte.trace(pixbuf);
380 Inkscape::XML::Node *layer_repr = SP_GROUP(desktop->currentLayer())->repr;
381 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
383 long totalNodeCount = 0L;
385 double offset = prefs_get_double_attribute("tools.paintbucket", "offset", 0.0);
387 for (unsigned int i=0 ; i<results.size() ; i++) {
388 Inkscape::Trace::TracingEngineResult result = results[i];
389 totalNodeCount += result.getNodeCount();
391 Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path");
392 /* Set style */
393 sp_desktop_apply_style_tool (desktop, pathRepr, "tools.paintbucket", false);
395 NArtBpath *bpath = sp_svg_read_path(result.getPathData().c_str());
396 Path *path = bpath_to_Path(bpath);
397 g_free(bpath);
399 if (offset != 0) {
401 Shape *path_shape = new Shape();
403 path->ConvertWithBackData(0.03);
404 path->Fill(path_shape, 0);
405 delete path;
407 Shape *expanded_path_shape = new Shape();
409 expanded_path_shape->ConvertToShape(path_shape, fill_nonZero);
410 path_shape->MakeOffset(expanded_path_shape, offset * desktop->current_zoom(), join_round, 4);
411 expanded_path_shape->ConvertToShape(path_shape, fill_positive);
413 Path *expanded_path = new Path();
415 expanded_path->Reset();
416 expanded_path_shape->ConvertToForme(expanded_path);
417 expanded_path->ConvertEvenLines(1.0);
418 expanded_path->Simplify(1.0);
420 delete path_shape;
421 delete expanded_path_shape;
423 gchar *str = expanded_path->svg_dump_path();
424 if (str && *str) {
425 pathRepr->setAttribute("d", str);
426 g_free(str);
427 } else {
428 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Too much inset</b>, the result is empty."));
429 Inkscape::GC::release(pathRepr);
430 g_free(str);
431 return;
432 }
434 delete expanded_path;
436 } else {
437 gchar *str = path->svg_dump_path();
438 delete path;
439 pathRepr->setAttribute("d", str);
440 g_free(str);
441 }
443 layer_repr->addChild(pathRepr, NULL);
445 SPObject *reprobj = document->getObjectByRepr(pathRepr);
446 if (reprobj) {
447 sp_item_write_transform(SP_ITEM(reprobj), pathRepr, transform, NULL);
449 // premultiply the item transform by the accumulated parent transform in the paste layer
450 NR::Matrix local = sp_item_i2doc_affine(SP_GROUP(desktop->currentLayer()));
451 if (!local.test_identity()) {
452 gchar const *t_str = pathRepr->attribute("transform");
453 NR::Matrix item_t (NR::identity());
454 if (t_str)
455 sp_svg_transform_read(t_str, &item_t);
456 item_t *= local.inverse();
457 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
458 gchar *affinestr=sp_svg_transform_write(item_t);
459 pathRepr->setAttribute("transform", affinestr);
460 g_free(affinestr);
461 }
463 Inkscape::Selection *selection = sp_desktop_selection(desktop);
465 pathRepr->setPosition(-1);
467 if (union_with_selection) {
468 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)));
469 selection->add(reprobj);
470 sp_selected_path_union_skip_undo();
471 } else {
472 desktop->messageStack()->flashF(Inkscape::WARNING_MESSAGE, _("Area filled, path with <b>%d</b> nodes created."), sp_nodes_in_path(SP_PATH(reprobj)));
473 selection->set(reprobj);
474 }
476 }
478 Inkscape::GC::release(pathRepr);
480 }
481 }
483 enum ScanlineCheckResult {
484 SCANLINE_CHECK_OK,
485 SCANLINE_CHECK_ABORTED,
486 SCANLINE_CHECK_BOUNDARY
487 };
489 static bool coords_in_range(int x, int y, bitmap_coords_info bci) {
490 return (x >= 0)
491 && (x < bci.width)
492 && (y >= 0)
493 && (y < bci.height);
494 }
496 #define PAINT_DIRECTION_LEFT 1
497 #define PAINT_DIRECTION_RIGHT 2
498 #define PAINT_DIRECTION_UP 4
499 #define PAINT_DIRECTION_DOWN 8
501 static unsigned int paint_pixel(guchar *px, guchar *trace_px, unsigned char *orig_color, bitmap_coords_info bci) {
502 unsigned char *trace_t;
504 bool can_paint_up = true;
505 bool can_paint_down = true;
506 bool can_paint_left = true;
507 bool can_paint_right = true;
509 if (bci.radius == 0) {
510 if (check_if_pixel_is_paintable(px, trace_px, bci.x, bci.y, orig_color, bci)) {
511 trace_t = get_pixel(trace_px, bci.x, bci.y, bci.width);
512 mark_pixel_colored(trace_t);
513 return PAINT_DIRECTION_LEFT + PAINT_DIRECTION_RIGHT + PAINT_DIRECTION_UP + PAINT_DIRECTION_DOWN;
514 } else {
515 return 0;
516 }
517 } else {
518 for (int y = -bci.radius; y <= bci.radius; y++) {
519 int ty = bci.y + y;
520 for (int x = -bci.radius; x <= bci.radius; x++) {
521 int tx = bci.x + x;
523 if (coords_in_range(tx, ty, bci)) {
524 trace_t = get_pixel(trace_px, tx, ty, bci.width);
525 if (!is_pixel_colored(trace_t)) {
526 if (check_if_pixel_is_paintable(px, trace_px, tx, ty, orig_color, bci)) {
527 mark_pixel_colored(trace_t);
528 } else {
529 if (x < 0) { can_paint_left = false; }
530 if (x > 0) { can_paint_right = false; }
531 if (y < 0) { can_paint_up = false; }
532 if (y > 0) { can_paint_down = false; }
533 }
534 }
535 }
536 }
537 }
539 unsigned int paint_directions = 0;
540 if (can_paint_left) { paint_directions += PAINT_DIRECTION_LEFT; }
541 if (can_paint_right) { paint_directions += PAINT_DIRECTION_RIGHT; }
542 if (can_paint_up) { paint_directions += PAINT_DIRECTION_UP; }
543 if (can_paint_down) { paint_directions += PAINT_DIRECTION_DOWN; }
545 return paint_directions;
546 }
547 }
549 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) {
550 bool aborted = false;
551 bool reached_screen_boundary = false;
552 bool ok;
554 bool keep_tracing;
555 unsigned int max_queue_size = bci.width * bci.height;
557 do {
558 ok = false;
559 if (bci.is_left) {
560 keep_tracing = (bci.x >= 0);
561 } else {
562 keep_tracing = (bci.x < bci.width);
563 }
565 if (keep_tracing) {
566 if (check_if_pixel_is_paintable(px, trace_px, bci.x, bci.y, orig_color, bci)) {
567 unsigned int paint_directions = paint_pixel(px, trace_px, orig_color, bci);
568 if (paint_directions & PAINT_DIRECTION_UP) {
569 try_add_to_queue(fill_queue, px, trace_px, orig_color, bci.x, bci.y - 1, bci.width, bci, max_queue_size);
570 }
571 if (paint_directions & PAINT_DIRECTION_DOWN) {
572 try_add_to_queue(fill_queue, px, trace_px, orig_color, bci.x, bci.y + 1, bci.width, bci, max_queue_size);
573 }
574 if (bci.is_left) {
575 if (paint_directions & PAINT_DIRECTION_LEFT) {
576 bci.x -= 1;
577 ok = true;
578 }
579 } else {
580 if (paint_directions & PAINT_DIRECTION_RIGHT) {
581 bci.x += 1;
582 ok = true;
583 }
584 }
585 }
586 } else {
587 if (bci.bbox.min()[NR::X] > bci.screen.min()[NR::X]) {
588 aborted = true; break;
589 } else {
590 reached_screen_boundary = true;
591 }
592 }
593 } while (ok);
595 if (aborted) { return SCANLINE_CHECK_ABORTED; }
596 if (reached_screen_boundary) { return SCANLINE_CHECK_BOUNDARY; }
597 return SCANLINE_CHECK_OK;
598 }
600 static void sp_flood_do_flood_fill(SPEventContext *event_context, GdkEvent *event, bool union_with_selection, bool is_point_fill, bool is_touch_fill) {
601 SPDesktop *desktop = event_context->desktop;
602 SPDocument *document = sp_desktop_document(desktop);
604 /* Create new arena */
605 NRArena *arena = NRArena::create();
606 unsigned dkey = sp_item_display_key_new(1);
608 sp_document_ensure_up_to_date (document);
610 SPItem *document_root = SP_ITEM(SP_DOCUMENT_ROOT(document));
611 NR::Maybe<NR::Rect> bbox = document_root->getBounds(NR::identity());
613 if (!bbox) {
614 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
615 return;
616 }
618 double zoom_scale = desktop->current_zoom();
619 double padding = 1.6;
621 NR::Rect screen = desktop->get_display_area();
623 int width = (int)ceil(screen.extent(NR::X) * zoom_scale * padding);
624 int height = (int)ceil(screen.extent(NR::Y) * zoom_scale * padding);
626 NR::Point origin(screen.min()[NR::X],
627 sp_document_height(document) - screen.extent(NR::Y) - screen.min()[NR::Y]);
629 origin[NR::X] = origin[NR::X] + (screen.extent(NR::X) * ((1 - padding) / 2));
630 origin[NR::Y] = origin[NR::Y] + (screen.extent(NR::Y) * ((1 - padding) / 2));
632 NR::scale scale(zoom_scale, zoom_scale);
633 NR::Matrix affine = scale * NR::translate(-origin * scale);
635 /* Create ArenaItems and set transform */
636 NRArenaItem *root = sp_item_invoke_show(SP_ITEM(sp_document_root(document)), arena, dkey, SP_ITEM_SHOW_DISPLAY);
637 nr_arena_item_set_transform(NR_ARENA_ITEM(root), affine);
639 NRGC gc(NULL);
640 nr_matrix_set_identity(&gc.transform);
642 NRRectL final_bbox;
643 final_bbox.x0 = 0;
644 final_bbox.y0 = 0;//row;
645 final_bbox.x1 = width;
646 final_bbox.y1 = height;//row + num_rows;
648 nr_arena_item_invoke_update(root, &final_bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
650 guchar *px = g_new(guchar, 4 * width * height);
652 NRPixBlock B;
653 nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
654 final_bbox.x0, final_bbox.y0, final_bbox.x1, final_bbox.y1,
655 px, 4 * width, FALSE, FALSE );
657 SPNamedView *nv = sp_desktop_namedview(desktop);
658 unsigned long bgcolor = nv->pagecolor;
660 unsigned char dtc[4];
661 dtc[0] = NR_RGBA32_R(bgcolor);
662 dtc[1] = NR_RGBA32_G(bgcolor);
663 dtc[2] = NR_RGBA32_B(bgcolor);
664 dtc[3] = NR_RGBA32_A(bgcolor);
666 for (int fy = 0; fy < height; fy++) {
667 guchar *p = NR_PIXBLOCK_PX(&B) + fy * B.rs;
668 for (int fx = 0; fx < width; fx++) {
669 for (int i = 0; i < 4; i++) {
670 *p++ = dtc[i];
671 }
672 }
673 }
675 nr_arena_item_invoke_render(NULL, root, &final_bbox, &B, NR_ARENA_ITEM_RENDER_NO_CACHE );
676 nr_pixblock_release(&B);
678 // Hide items
679 sp_item_invoke_hide(SP_ITEM(sp_document_root(document)), dkey);
681 nr_arena_item_unref(root);
682 nr_object_unref((NRObject *) arena);
684 guchar *trace_px = g_new(guchar, 4 * width * height);
685 memset(trace_px, 0x00, 4 * width * height);
687 std::deque<NR::Point> fill_queue;
688 std::queue<NR::Point> color_queue;
690 std::vector<NR::Point> fill_points;
692 if (is_point_fill) {
693 fill_points.push_back(NR::Point(event->button.x, event->button.y));
694 } else {
695 Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
696 fill_points = r->getPoints();
697 }
699 for (unsigned int i = 0; i < fill_points.size(); i++) {
700 NR::Point pw = NR::Point(fill_points[i][NR::X] / zoom_scale, sp_document_height(document) + (fill_points[i][NR::Y] / zoom_scale)) * affine;
702 pw[NR::X] = (int)MIN(width - 1, MAX(0, pw[NR::X]));
703 pw[NR::Y] = (int)MIN(height - 1, MAX(0, pw[NR::Y]));
705 if (is_touch_fill) {
706 if (i == 0) {
707 color_queue.push(pw);
708 } else {
709 fill_queue.push_back(pw);
710 }
711 } else {
712 color_queue.push(pw);
713 }
714 }
716 bool aborted = false;
717 int y_limit = height - 1;
719 PaintBucketChannels method = (PaintBucketChannels)prefs_get_int_attribute("tools.paintbucket", "channels", 0);
720 int threshold = prefs_get_int_attribute_limited("tools.paintbucket", "threshold", 1, 0, 100);
722 switch(method) {
723 case FLOOD_CHANNELS_ALPHA:
724 case FLOOD_CHANNELS_RGB:
725 case FLOOD_CHANNELS_R:
726 case FLOOD_CHANNELS_G:
727 case FLOOD_CHANNELS_B:
728 threshold = (255 * threshold) / 100;
729 break;
730 case FLOOD_CHANNELS_H:
731 case FLOOD_CHANNELS_S:
732 case FLOOD_CHANNELS_L:
733 break;
734 }
736 bool reached_screen_boundary = false;
738 bitmap_coords_info bci;
740 bci.y_limit = y_limit;
741 bci.width = width;
742 bci.height = height;
743 bci.threshold = threshold;
744 bci.method = method;
745 bci.bbox = *bbox;
746 bci.screen = screen;
747 bci.dtc = dtc;
748 bci.radius = prefs_get_int_attribute_limited("tools.paintbucket", "autogap", 0, 0, 3);
750 bool first_run = true;
752 while (!color_queue.empty() && !aborted) {
753 NR::Point color_point = color_queue.front();
754 color_queue.pop();
756 unsigned char *orig_px = get_pixel(px, (int)color_point[NR::X], (int)color_point[NR::Y], width);
757 unsigned char orig_color[4];
758 for (int i = 0; i < 4; i++) { orig_color[i] = orig_px[i]; }
760 unsigned char merged_orig[4];
762 merge_pixel_with_background(orig_color, dtc, merged_orig);
764 unsigned char *trace_t = get_pixel(trace_px, (int)color_point[NR::X], (int)color_point[NR::Y], width);
765 if (!is_pixel_checked(trace_t) && !is_pixel_colored(trace_t)) {
766 fill_queue.push_front(color_point);
768 if (!first_run) {
769 for (int y = 0; y < height; y++) {
770 for (int x = 0; x < width; x++) {
771 trace_t = get_pixel(trace_px, x, y, width);
772 clear_pixel_paintability(trace_t);
773 }
774 }
775 }
776 first_run = false;
777 }
779 while (!fill_queue.empty() && !aborted) {
780 NR::Point cp = fill_queue.front();
781 fill_queue.pop_front();
783 unsigned char *trace_t = get_pixel(trace_px, (int)cp[NR::X], (int)cp[NR::Y], width);
784 if (!is_pixel_checked(trace_t)) {
785 mark_pixel_checked(trace_t);
787 int x = (int)cp[NR::X];
788 int y = (int)cp[NR::Y];
790 // same color at this point
791 if (check_if_pixel_is_paintable(px, trace_px, x, y, orig_color, bci)) {
792 if (y == 0) {
793 if (bbox->min()[NR::Y] > screen.min()[NR::Y]) {
794 aborted = true; break;
795 } else {
796 reached_screen_boundary = true;
797 }
798 }
800 if (y == y_limit) {
801 if (bbox->max()[NR::Y] < screen.max()[NR::Y]) {
802 aborted = true; break;
803 } else {
804 reached_screen_boundary = true;
805 }
806 }
808 bci.is_left = true;
809 bci.x = x;
810 bci.y = y;
812 ScanlineCheckResult result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci);
814 switch (result) {
815 case SCANLINE_CHECK_ABORTED:
816 aborted = true;
817 break;
818 case SCANLINE_CHECK_BOUNDARY:
819 reached_screen_boundary = true;
820 break;
821 default:
822 break;
823 }
825 bci.is_left = false;
826 bci.x = x + 1;
827 bci.y = y;
829 result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci);
831 switch (result) {
832 case SCANLINE_CHECK_ABORTED:
833 aborted = true;
834 break;
835 case SCANLINE_CHECK_BOUNDARY:
836 reached_screen_boundary = true;
837 break;
838 default:
839 break;
840 }
841 }
842 }
843 }
844 }
846 g_free(px);
848 if (aborted) {
849 g_free(trace_px);
850 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
851 return;
852 }
854 if (reached_screen_boundary) {
855 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."));
856 }
858 GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(trace_px,
859 GDK_COLORSPACE_RGB,
860 TRUE,
861 8, width, height, width * 4,
862 (GdkPixbufDestroyNotify)g_free,
863 NULL);
865 NR::Matrix inverted_affine = NR::Matrix(affine).inverse();
867 do_trace(pixbuf, desktop, inverted_affine, union_with_selection);
869 g_free(trace_px);
871 sp_document_done(document, SP_VERB_CONTEXT_PAINTBUCKET, _("Fill bounded area"));
872 }
874 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
875 {
876 gint ret = FALSE;
878 SPDesktop *desktop = event_context->desktop;
880 switch (event->type) {
881 case GDK_BUTTON_PRESS:
882 if (event->button.state & GDK_CONTROL_MASK) {
883 NR::Point const button_w(event->button.x,
884 event->button.y);
886 SPItem *item = sp_event_context_find_item (desktop, button_w, TRUE, TRUE);
888 Inkscape::XML::Node *pathRepr = SP_OBJECT_REPR(item);
889 /* Set style */
890 sp_desktop_apply_style_tool (desktop, pathRepr, "tools.paintbucket", false);
891 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET, _("Set style on object"));
892 ret = TRUE;
893 }
894 break;
895 default:
896 break;
897 }
899 if (((SPEventContextClass *) parent_class)->item_handler) {
900 ret = ((SPEventContextClass *) parent_class)->item_handler(event_context, item, event);
901 }
903 return ret;
904 }
906 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event)
907 {
908 static bool dragging;
910 gint ret = FALSE;
911 SPDesktop *desktop = event_context->desktop;
913 switch (event->type) {
914 case GDK_BUTTON_PRESS:
915 if ( event->button.button == 1 ) {
916 if (!(event->button.state & GDK_CONTROL_MASK)) {
917 NR::Point const button_w(event->button.x,
918 event->button.y);
920 if (Inkscape::have_viable_layer(desktop, event_context->defaultMessageContext())) {
921 // save drag origin
922 event_context->xp = (gint) button_w[NR::X];
923 event_context->yp = (gint) button_w[NR::Y];
924 event_context->within_tolerance = true;
926 dragging = true;
928 NR::Point const p(desktop->w2d(button_w));
929 Inkscape::Rubberband::get()->setMode(RUBBERBAND_MODE_TOUCHPATH);
930 Inkscape::Rubberband::get()->start(desktop, p);
931 }
932 }
933 }
934 case GDK_MOTION_NOTIFY:
935 if ( dragging
936 && ( event->motion.state & GDK_BUTTON1_MASK ) )
937 {
938 if ( event_context->within_tolerance
939 && ( abs( (gint) event->motion.x - event_context->xp ) < event_context->tolerance )
940 && ( abs( (gint) event->motion.y - event_context->yp ) < event_context->tolerance ) ) {
941 break; // do not drag if we're within tolerance from origin
942 }
944 event_context->within_tolerance = false;
946 NR::Point const motion_pt(event->motion.x, event->motion.y);
947 NR::Point const p(desktop->w2d(motion_pt));
948 if (Inkscape::Rubberband::get()->is_started()) {
949 Inkscape::Rubberband::get()->move(p);
950 event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Draw over</b> areas to add to fill, hold <b>Alt</b> for touch fill"));
951 gobble_motion_events(GDK_BUTTON1_MASK);
952 }
953 }
954 break;
956 case GDK_BUTTON_RELEASE:
957 if ( event->button.button == 1 ) {
958 Inkscape::Rubberband::Rubberband *r = Inkscape::Rubberband::get();
959 if (r->is_started()) {
960 // set "busy" cursor
961 desktop->setWaitingCursor();
963 if (SP_IS_EVENT_CONTEXT(event_context)) {
964 // Since setWaitingCursor runs main loop iterations, we may have already left this tool!
965 // So check if the tool is valid before doing anything
966 dragging = false;
968 bool is_point_fill = event_context->within_tolerance;
969 bool is_touch_fill = event->button.state & GDK_MOD1_MASK;
971 sp_flood_do_flood_fill(event_context, event, event->button.state & GDK_SHIFT_MASK, is_point_fill, is_touch_fill);
973 desktop->clearWaitingCursor();
974 // restore cursor when done; note that it may already be different if e.g. user
975 // switched to another tool during interruptible tracing or drawing, in which case do nothing
977 ret = TRUE;
978 }
980 r->stop();
981 event_context->defaultMessageContext()->clear();
982 }
983 }
984 break;
985 case GDK_KEY_PRESS:
986 switch (get_group0_keyval (&event->key)) {
987 case GDK_Up:
988 case GDK_Down:
989 case GDK_KP_Up:
990 case GDK_KP_Down:
991 // prevent the zoom field from activation
992 if (!MOD__CTRL_ONLY)
993 ret = TRUE;
994 break;
995 default:
996 break;
997 }
998 break;
999 default:
1000 break;
1001 }
1003 if (!ret) {
1004 if (((SPEventContextClass *) parent_class)->root_handler) {
1005 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1006 }
1007 }
1009 return ret;
1010 }
1013 static void sp_flood_finish(SPFloodContext *rc)
1014 {
1015 rc->_message_context->clear();
1017 if ( rc->item != NULL ) {
1018 SPDesktop * desktop;
1020 desktop = SP_EVENT_CONTEXT_DESKTOP(rc);
1022 SP_OBJECT(rc->item)->updateRepr();
1024 sp_canvas_end_forced_full_redraws(desktop->canvas);
1026 sp_desktop_selection(desktop)->set(rc->item);
1027 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET,
1028 _("Fill bounded area"));
1030 rc->item = NULL;
1031 }
1032 }
1034 void flood_channels_set_channels( gint channels )
1035 {
1036 prefs_set_int_attribute("tools.paintbucket", "channels", channels);
1037 }
1039 /*
1040 Local Variables:
1041 mode:c++
1042 c-file-style:"stroustrup"
1043 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1044 indent-tabs-mode:nil
1045 fill-column:99
1046 End:
1047 */
1048 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :