Code

Optimize flood algorithm to only scan adjacent runs once
[inkscape.git] / src / flood-context.cpp
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>
23 #include "macros.h"
24 #include "display/sp-canvas.h"
25 #include "document.h"
26 #include "sp-namedview.h"
27 #include "sp-object.h"
28 #include "sp-rect.h"
29 #include "selection.h"
30 #include "selection-chemistry.h"
31 #include "desktop-handles.h"
32 #include "snap.h"
33 #include "desktop.h"
34 #include "desktop-style.h"
35 #include "message-stack.h"
36 #include "message-context.h"
37 #include "pixmaps/cursor-paintbucket.xpm"
38 #include "flood-context.h"
39 #include "sp-metrics.h"
40 #include <glibmm/i18n.h>
41 #include "object-edit.h"
42 #include "xml/repr.h"
43 #include "xml/node-event-vector.h"
44 #include "prefs-utils.h"
45 #include "context-fns.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 "helper/png-write.h"
52 #include "libnr/nr-pixops.h"
53 #include "libnr/nr-matrix-rotate-ops.h"
54 #include "libnr/nr-matrix-translate-ops.h"
55 #include "libnr/nr-rotate-fns.h"
56 #include "libnr/nr-scale-ops.h"
57 #include "libnr/nr-scale-translate-ops.h"
58 #include "libnr/nr-translate-matrix-ops.h"
59 #include "libnr/nr-translate-scale-ops.h"
60 #include "libnr/nr-matrix-ops.h"
61 #include "sp-item.h"
62 #include "sp-root.h"
63 #include "sp-defs.h"
64 #include "splivarot.h"
65 #include "livarot/Path.h"
66 #include "livarot/Shape.h"
67 #include "libnr/n-art-bpath.h"
68 #include "svg/svg.h"
70 #include "trace/trace.h"
71 #include "trace/potrace/inkscape-potrace.h"
73 static void sp_flood_context_class_init(SPFloodContextClass *klass);
74 static void sp_flood_context_init(SPFloodContext *flood_context);
75 static void sp_flood_context_dispose(GObject *object);
77 static void sp_flood_context_setup(SPEventContext *ec);
79 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event);
80 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event);
82 static void sp_flood_finish(SPFloodContext *rc);
84 static SPEventContextClass *parent_class;
87 struct SPEBP {
88     int width, height, sheight;
89     guchar r, g, b, a;
90     NRArenaItem *root; // the root arena item to show; it is assumed that all unneeded items are hidden
91     guchar *px;
92     unsigned (*status)(float, void *);
93     void *data;
94 };
96 GtkType sp_flood_context_get_type()
97 {
98     static GType type = 0;
99     if (!type) {
100         GTypeInfo info = {
101             sizeof(SPFloodContextClass),
102             NULL, NULL,
103             (GClassInitFunc) sp_flood_context_class_init,
104             NULL, NULL,
105             sizeof(SPFloodContext),
106             4,
107             (GInstanceInitFunc) sp_flood_context_init,
108             NULL,    /* value_table */
109         };
110         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPFloodContext", &info, (GTypeFlags) 0);
111     }
112     return type;
115 static void sp_flood_context_class_init(SPFloodContextClass *klass)
117     GObjectClass *object_class = (GObjectClass *) klass;
118     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
120     parent_class = (SPEventContextClass *) g_type_class_peek_parent(klass);
122     object_class->dispose = sp_flood_context_dispose;
124     event_context_class->setup = sp_flood_context_setup;
125     event_context_class->root_handler  = sp_flood_context_root_handler;
126     event_context_class->item_handler  = sp_flood_context_item_handler;
129 static void sp_flood_context_init(SPFloodContext *flood_context)
131     SPEventContext *event_context = SP_EVENT_CONTEXT(flood_context);
133     event_context->cursor_shape = cursor_paintbucket_xpm;
134     event_context->hot_x = 11;
135     event_context->hot_y = 30;
136     event_context->xp = 0;
137     event_context->yp = 0;
138     event_context->tolerance = 0;
139     event_context->within_tolerance = false;
140     event_context->item_to_select = NULL;
142     event_context->shape_repr = NULL;
143     event_context->shape_knot_holder = NULL;
145     flood_context->item = NULL;
147     new (&flood_context->sel_changed_connection) sigc::connection();
150 static void sp_flood_context_dispose(GObject *object)
152     SPFloodContext *rc = SP_FLOOD_CONTEXT(object);
153     SPEventContext *ec = SP_EVENT_CONTEXT(object);
155     rc->sel_changed_connection.disconnect();
156     rc->sel_changed_connection.~connection();
158     /* fixme: This is necessary because we do not grab */
159     if (rc->item) {
160         sp_flood_finish(rc);
161     }
163     if (ec->shape_repr) { // remove old listener
164         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
165         Inkscape::GC::release(ec->shape_repr);
166         ec->shape_repr = 0;
167     }
169     if (rc->_message_context) {
170         delete rc->_message_context;
171     }
173     G_OBJECT_CLASS(parent_class)->dispose(object);
176 static Inkscape::XML::NodeEventVector ec_shape_repr_events = {
177     NULL, /* child_added */
178     NULL, /* child_removed */
179     ec_shape_event_attr_changed,
180     NULL, /* content_changed */
181     NULL  /* order_changed */
182 };
184 /**
185 \brief  Callback that processes the "changed" signal on the selection;
186 destroys old and creates new knotholder
187 */
188 void sp_flood_context_selection_changed(Inkscape::Selection *selection, gpointer data)
190     SPFloodContext *rc = SP_FLOOD_CONTEXT(data);
191     SPEventContext *ec = SP_EVENT_CONTEXT(rc);
193     if (ec->shape_repr) { // remove old listener
194         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
195         Inkscape::GC::release(ec->shape_repr);
196         ec->shape_repr = 0;
197     }
199     SPItem *item = selection->singleItem();
200     if (item) {
201         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
202         if (shape_repr) {
203             ec->shape_repr = shape_repr;
204             Inkscape::GC::anchor(shape_repr);
205             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
206         }
207     }
210 static void sp_flood_context_setup(SPEventContext *ec)
212     SPFloodContext *rc = SP_FLOOD_CONTEXT(ec);
214     if (((SPEventContextClass *) parent_class)->setup) {
215         ((SPEventContextClass *) parent_class)->setup(ec);
216     }
218     SPItem *item = sp_desktop_selection(ec->desktop)->singleItem();
219     if (item) {
220         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
221         if (shape_repr) {
222             ec->shape_repr = shape_repr;
223             Inkscape::GC::anchor(shape_repr);
224             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
225         }
226     }
228     rc->sel_changed_connection.disconnect();
229     rc->sel_changed_connection = sp_desktop_selection(ec->desktop)->connectChanged(
230         sigc::bind(sigc::ptr_fun(&sp_flood_context_selection_changed), (gpointer)rc)
231     );
233     rc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
236 /**
237 Hide all items which are not listed in list, recursively, skipping groups and defs
238 */
239 static void
240 hide_other_items_recursively(SPObject *o, GSList *list, unsigned dkey)
242     if (SP_IS_ITEM(o)
243         && !SP_IS_DEFS(o)
244         && !SP_IS_ROOT(o)
245         && !SP_IS_GROUP(o)
246         && !g_slist_find(list, o))
247     {
248         sp_item_invoke_hide(SP_ITEM(o), dkey);
249     }
251      // recurse
252     if (!g_slist_find(list, o)) {
253         for (SPObject *child = sp_object_first_child(o) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
254             hide_other_items_recursively(child, list, dkey);
255         }
256     }
259 inline unsigned char * get_pixel(guchar *px, int x, int y, int width) {
260   return px + (x + y * width) * 4;
263 static bool compare_pixels(unsigned char *a, unsigned char *b, int tolerance) {
264   for (int i = 0; i < 4; i++) {
265     if (abs(a[i] - b[i]) > tolerance) { 
266       return false;
267     }
268   }
269   return true;
272 static bool try_add_to_queue(std::queue<NR::Point> *fill_queue, guchar *px, unsigned char *orig, int x, int y, int width, int tolerance, bool fill_switch) {
273   unsigned char *t = get_pixel(px, x, y, width);
274   if (compare_pixels(t, orig, tolerance)) {
275     if (fill_switch) {
276       fill_queue->push(NR::Point(x, y));
277       return false;
278     }
279   }
280   return true;
283 static void do_trace(GdkPixbuf *px, SPDesktop *desktop, NR::Matrix transform) {
284     SPDocument *document = sp_desktop_document(desktop);
285     
286     Inkscape::Trace::Potrace::PotraceTracingEngine pte;
287         
288     pte.setTraceType(Inkscape::Trace::Potrace::TRACE_BRIGHTNESS);
289     pte.setInvert(false);
291     Glib::RefPtr<Gdk::Pixbuf> pixbuf = Glib::wrap(px, true);
292     
293     std::vector<Inkscape::Trace::TracingEngineResult> results = pte.trace(pixbuf);
294     
295     Inkscape::XML::Node *layer_repr = SP_GROUP(desktop->currentLayer())->repr;
296     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
298     long totalNodeCount = 0L;
300     for (unsigned int i=0 ; i<results.size() ; i++) {
301         Inkscape::Trace::TracingEngineResult result = results[i];
302         totalNodeCount += result.getNodeCount();
304         Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path");
305         /* Set style */
306         sp_desktop_apply_style_tool (desktop, pathRepr, "tools.paintbucket", false);
308         NArtBpath *bpath = sp_svg_read_path(result.getPathData().c_str());
309         Path *path = bpath_to_Path(bpath);
310         g_free(bpath);
311         
312         Shape *path_shape = new Shape();
313         
314         path->ConvertWithBackData(0.03);
315         path->Fill(path_shape, 0);
316         delete path;
317         
318         Shape *expanded_path_shape = new Shape();
319         
320         expanded_path_shape->ConvertToShape(path_shape, fill_nonZero);
321         path_shape->MakeOffset(expanded_path_shape, 1.5, join_round, 4);
322         expanded_path_shape->ConvertToShape(path_shape, fill_positive);
324         Path *expanded_path = new Path();
325         
326         expanded_path->Reset();
327         expanded_path_shape->ConvertToForme(expanded_path);
328         expanded_path->ConvertEvenLines(1.0);
329         expanded_path->Simplify(1.0);
330         
331         delete path_shape;
332         delete expanded_path_shape;
333         
334         gchar *str = expanded_path->svg_dump_path();
335         delete expanded_path;
336         pathRepr->setAttribute("d", str);
337         g_free(str);
339         layer_repr->addChild(pathRepr, NULL);
341         SPObject *reprobj = document->getObjectByRepr(pathRepr);
342         if (reprobj) {
343             sp_item_write_transform(SP_ITEM(reprobj), pathRepr, transform, NULL);
344             
345             // premultiply the item transform by the accumulated parent transform in the paste layer
346             NR::Matrix local = sp_item_i2doc_affine(SP_GROUP(desktop->currentLayer()));
347             if (!local.test_identity()) {
348                 gchar const *t_str = pathRepr->attribute("transform");
349                 NR::Matrix item_t (NR::identity());
350                 if (t_str)
351                     sp_svg_transform_read(t_str, &item_t);
352                 item_t *= local.inverse();
353                 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
354                 gchar *affinestr=sp_svg_transform_write(item_t);
355                 pathRepr->setAttribute("transform", affinestr);
356                 g_free(affinestr);
357             }
359             Inkscape::Selection *selection = sp_desktop_selection(desktop);
360             selection->set(reprobj);
361             pathRepr->setPosition(-1);
362         }
363         
364         Inkscape::GC::release(pathRepr);
365     }
368 static void sp_flood_do_flood_fill(SPEventContext *event_context, GdkEvent *event) {
369     SPDesktop *desktop = event_context->desktop;
370     SPDocument *document = sp_desktop_document(desktop);
372     /* Create new arena */
373     NRArena *arena = NRArena::create();
374     unsigned dkey = sp_item_display_key_new(1);
376     sp_document_ensure_up_to_date (document);
377     
378     SPItem *document_root = SP_ITEM(SP_DOCUMENT_ROOT(document));
379     NR::Rect bbox = document_root->invokeBbox(NR::identity());
381     if (bbox.isEmpty()) { 
382       desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
383       return;
384     }
385     
386     double zoom_scale = desktop->current_zoom();
387     double padding = 1.6;
389     NR::Rect screen = desktop->get_display_area();
391     int width = (int)ceil(screen.extent(NR::X) * zoom_scale * padding);
392     int height = (int)ceil(screen.extent(NR::Y) * zoom_scale * padding);
394     NR::Point origin(screen.min()[NR::X],
395                      sp_document_height(document) - screen.extent(NR::Y) - screen.min()[NR::Y]);
396                      
397     origin[NR::X] = origin[NR::X] + (screen.extent(NR::X) * ((1 - padding) / 2));
398     origin[NR::Y] = origin[NR::Y] + (screen.extent(NR::Y) * ((1 - padding) / 2));
399     
400     NR::scale scale(zoom_scale, zoom_scale);
401     NR::Matrix affine = scale * NR::translate(-origin * scale);
402     
403     /* Create ArenaItems and set transform */
404     NRArenaItem *root = sp_item_invoke_show(SP_ITEM(sp_document_root(document)), arena, dkey, SP_ITEM_SHOW_DISPLAY);
405     nr_arena_item_set_transform(NR_ARENA_ITEM(root), affine);
407     NRGC gc(NULL);
408     nr_matrix_set_identity(&gc.transform);
409     
410     NRRectL final_bbox;
411     final_bbox.x0 = 0;
412     final_bbox.y0 = 0;//row;
413     final_bbox.x1 = width;
414     final_bbox.y1 = height;//row + num_rows;
415     
416     nr_arena_item_invoke_update(root, &final_bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
418     guchar *px = g_new(guchar, 4 * width * height);
419     memset(px, 0x00, 4 * width * height);
421     NRPixBlock B;
422     nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
423                               final_bbox.x0, final_bbox.y0, final_bbox.x1, final_bbox.y1,
424                               px, 4 * width, FALSE, FALSE );
425     
426     nr_arena_item_invoke_render( root, &final_bbox, &B, NR_ARENA_ITEM_RENDER_NO_CACHE );
427     nr_pixblock_release(&B);
428     
429     // Hide items
430     sp_item_invoke_hide(SP_ITEM(sp_document_root(document)), dkey);
431     
432     nr_arena_item_unref(root);
433     nr_object_unref((NRObject *) arena);
434     
435     NR::Point pw = NR::Point(event->button.x / zoom_scale, sp_document_height(document) + (event->button.y / zoom_scale)) * affine;
436     
437     pw[NR::X] = (int)MIN(width - 1, MAX(0, pw[NR::X]));
438     pw[NR::Y] = (int)MIN(height - 1, MAX(0, pw[NR::Y]));
440     guchar *trace_px = g_new(guchar, 4 * width * height);
441     memset(trace_px, 0x00, 4 * width * height);
442     
443     std::queue<NR::Point> fill_queue;
444     fill_queue.push(pw);
445     
446     bool aborted = false;
447     int y_limit = height - 1;
448     
449     unsigned char orig_color[4];
450     unsigned char *orig_px = get_pixel(px, (int)pw[NR::X], (int)pw[NR::Y], width);
451     for (int i = 0; i < 4; i++) { orig_color[i] = orig_px[i]; }
453     int tolerance = (255 * prefs_get_int_attribute_limited("tools.paintbucket", "tolerance", 1, 0, 100)) / 100;
455     while (!fill_queue.empty() && !aborted) {
456       NR::Point cp = fill_queue.front();
457       fill_queue.pop();
458       unsigned char *s = get_pixel(px, (int)cp[NR::X], (int)cp[NR::Y], width);
459       
460       // same color at this point
461       if (compare_pixels(s, orig_color, tolerance)) {
462         int left = (int)cp[NR::X];
463         int right = (int)cp[NR::X] + 1;
464         int x = (int)cp[NR::X];
465         int y = (int)cp[NR::Y];
466         
467         bool top_fill = true;
468         bool bottom_fill = true;
469         
470         if (y > 0) { 
471           top_fill = try_add_to_queue(&fill_queue, px, orig_color, x, y - 1, width, tolerance, top_fill);
472         } else {
473           aborted = true; break;
474         }
475         if (y < y_limit) { 
476           bottom_fill = try_add_to_queue(&fill_queue, px, orig_color, x, y + 1, width, tolerance, bottom_fill);
477         } else {
478           aborted = true; break;
479         }
480         
481         bool default_top_fill = top_fill;
482         bool default_bottom_fill = bottom_fill;
483         
484         unsigned char *t, *trace_t;
485         bool ok = false;
486         
487         trace_t = get_pixel(trace_px, left, y, width);
488         
489         do {
490           ok = false;
491           // go left
492           if (left >= 0) {
493             t = get_pixel(px, left, y, width);
494             if (compare_pixels(t, orig_color, tolerance)) {
495               for (int i = 0; i < 4; i++) { t[i] = 255 - t[i]; }
496               trace_t[3] = 255; trace_t -= 4;
497               if (y > 0) { top_fill = try_add_to_queue(&fill_queue, px, orig_color, left, y - 1, width, tolerance, top_fill); }
498               if (y < y_limit) { bottom_fill = try_add_to_queue(&fill_queue, px, orig_color, left, y + 1, width, tolerance, bottom_fill); }
499               left--; ok = true;
500             }
501           } else {
502             aborted = true; break;
503           }
504         } while (ok);
505       
506         top_fill = default_top_fill;
507         bottom_fill = default_bottom_fill;
508         trace_t = get_pixel(trace_px, right, y, width);
509         
510         do {
511           ok = false;
512           // go right
513           if (right < width) {
514             t = get_pixel(px, right, y, width);
515             if (compare_pixels(t, orig_color, tolerance)) {
516               for (int i = 0; i < 4; i++) { t[i] = 255 - t[i]; }
517               trace_t[3] = 255; trace_t += 4;
518               if (y > 0) { top_fill = try_add_to_queue(&fill_queue, px, orig_color, right, y - 1, width, tolerance, top_fill); }
519               if (y < y_limit) { bottom_fill = try_add_to_queue(&fill_queue, px, orig_color, right, y + 1, width, tolerance, bottom_fill); }
520               right++; ok = true;
521             }
522           } else {
523             aborted = true; break;
524           }
525         } while (ok);
526       }
527     }
528     
529     g_free(px);
530     
531     if (aborted) {
532       g_free(trace_px);
533       desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill."));
534       return;
535     }
536     
537     GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(trace_px,
538                                       GDK_COLORSPACE_RGB,
539                                       TRUE,
540                                       8, width, height, width * 4,
541                                       (GdkPixbufDestroyNotify)g_free,
542                                       NULL);
544     NR::Matrix inverted_affine = NR::Matrix(affine).inverse();
545     
546     do_trace(pixbuf, desktop, inverted_affine);
548     g_free(trace_px);
549     
550     sp_document_done(document, SP_VERB_CONTEXT_PAINTBUCKET, _("Fill bounded area"));
553 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
555     gint ret = FALSE;
557     switch (event->type) {
558     case GDK_BUTTON_PRESS:
559         break;
560         // motion and release are always on root (why?)
561     default:
562         break;
563     }
565     if (((SPEventContextClass *) parent_class)->item_handler) {
566         ret = ((SPEventContextClass *) parent_class)->item_handler(event_context, item, event);
567     }
569     return ret;
572 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event)
574     SPDesktop *desktop = event_context->desktop;
576     gint ret = FALSE;
577     switch (event->type) {
578     case GDK_BUTTON_PRESS:
579         if ( event->button.button == 1 ) {
580             sp_flood_do_flood_fill(event_context, event);
582             ret = TRUE;
583         }
584         break;
585     case GDK_KEY_PRESS:
586         switch (get_group0_keyval (&event->key)) {
587         case GDK_Up:
588         case GDK_Down:
589         case GDK_KP_Up:
590         case GDK_KP_Down:
591             // prevent the zoom field from activation
592             if (!MOD__CTRL_ONLY)
593                 ret = TRUE;
594             break;
595         case GDK_Escape:
596             sp_desktop_selection(desktop)->clear();
597         default:
598             break;
599         }
600         break;
601     default:
602         break;
603     }
605     if (!ret) {
606         if (((SPEventContextClass *) parent_class)->root_handler) {
607             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
608         }
609     }
611     return ret;
615 static void sp_flood_finish(SPFloodContext *rc)
617     rc->_message_context->clear();
619     if ( rc->item != NULL ) {
620         SPDesktop * desktop;
622         desktop = SP_EVENT_CONTEXT_DESKTOP(rc);
624         SP_OBJECT(rc->item)->updateRepr();
626         sp_canvas_end_forced_full_redraws(desktop->canvas);
628         sp_desktop_selection(desktop)->set(rc->item);
629         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET,
630                          _("Fill bounded area"));
632         rc->item = NULL;
633     }
636 /*
637   Local Variables:
638   mode:c++
639   c-file-style:"stroustrup"
640   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
641   indent-tabs-mode:nil
642   fill-column:99
643   End:
644 */
645 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :