Code

replace use of invokeBbox in flood fill tool
[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-context.h"
36 #include "pixmaps/cursor-rect.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"
46 #include "display/nr-arena-item.h"
47 #include "display/nr-arena.h"
48 #include "display/nr-arena-image.h"
49 #include "display/canvas-arena.h"
50 #include "helper/png-write.h"
51 #include "libnr/nr-pixops.h"
52 #include "libnr/nr-matrix-rotate-ops.h"
53 #include "libnr/nr-matrix-translate-ops.h"
54 #include "libnr/nr-rotate-fns.h"
55 #include "libnr/nr-scale-ops.h"
56 #include "libnr/nr-scale-translate-ops.h"
57 #include "libnr/nr-translate-matrix-ops.h"
58 #include "libnr/nr-translate-scale-ops.h"
59 #include "libnr/nr-matrix-ops.h"
60 #include "sp-item.h"
61 #include "sp-root.h"
62 #include "sp-defs.h"
63 #include "splivarot.h"
64 #include "livarot/Path.h"
65 #include "livarot/Shape.h"
66 #include "libnr/n-art-bpath.h"
67 #include "svg/svg.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 struct SPEBP {
87     int width, height, sheight;
88     guchar r, g, b, a;
89     NRArenaItem *root; // the root arena item to show; it is assumed that all unneeded items are hidden
90     guchar *px;
91     unsigned (*status)(float, void *);
92     void *data;
93 };
95 GtkType sp_flood_context_get_type()
96 {
97     static GType type = 0;
98     if (!type) {
99         GTypeInfo info = {
100             sizeof(SPFloodContextClass),
101             NULL, NULL,
102             (GClassInitFunc) sp_flood_context_class_init,
103             NULL, NULL,
104             sizeof(SPFloodContext),
105             4,
106             (GInstanceInitFunc) sp_flood_context_init,
107             NULL,    /* value_table */
108         };
109         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPFloodContext", &info, (GTypeFlags) 0);
110     }
111     return type;
114 static void sp_flood_context_class_init(SPFloodContextClass *klass)
116     GObjectClass *object_class = (GObjectClass *) klass;
117     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
119     parent_class = (SPEventContextClass *) g_type_class_peek_parent(klass);
121     object_class->dispose = sp_flood_context_dispose;
123     event_context_class->setup = sp_flood_context_setup;
124     event_context_class->root_handler  = sp_flood_context_root_handler;
125     event_context_class->item_handler  = sp_flood_context_item_handler;
128 static void sp_flood_context_init(SPFloodContext *flood_context)
130     SPEventContext *event_context = SP_EVENT_CONTEXT(flood_context);
132     event_context->cursor_shape = cursor_rect_xpm;
133     event_context->hot_x = 4;
134     event_context->hot_y = 4;
135     event_context->xp = 0;
136     event_context->yp = 0;
137     event_context->tolerance = 0;
138     event_context->within_tolerance = false;
139     event_context->item_to_select = NULL;
141     event_context->shape_repr = NULL;
142     event_context->shape_knot_holder = NULL;
144     flood_context->item = NULL;
146     new (&flood_context->sel_changed_connection) sigc::connection();
149 static void sp_flood_context_dispose(GObject *object)
151     SPFloodContext *rc = SP_FLOOD_CONTEXT(object);
152     SPEventContext *ec = SP_EVENT_CONTEXT(object);
154     rc->sel_changed_connection.disconnect();
155     rc->sel_changed_connection.~connection();
157     /* fixme: This is necessary because we do not grab */
158     if (rc->item) {
159         sp_flood_finish(rc);
160     }
162     if (ec->shape_repr) { // remove old listener
163         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
164         Inkscape::GC::release(ec->shape_repr);
165         ec->shape_repr = 0;
166     }
168     if (rc->_message_context) {
169         delete rc->_message_context;
170     }
172     G_OBJECT_CLASS(parent_class)->dispose(object);
175 static Inkscape::XML::NodeEventVector ec_shape_repr_events = {
176     NULL, /* child_added */
177     NULL, /* child_removed */
178     ec_shape_event_attr_changed,
179     NULL, /* content_changed */
180     NULL  /* order_changed */
181 };
183 /**
184 \brief  Callback that processes the "changed" signal on the selection;
185 destroys old and creates new knotholder
186 */
187 void sp_flood_context_selection_changed(Inkscape::Selection *selection, gpointer data)
189     SPFloodContext *rc = SP_FLOOD_CONTEXT(data);
190     SPEventContext *ec = SP_EVENT_CONTEXT(rc);
192     if (ec->shape_repr) { // remove old listener
193         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
194         Inkscape::GC::release(ec->shape_repr);
195         ec->shape_repr = 0;
196     }
198     SPItem *item = selection->singleItem();
199     if (item) {
200         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
201         if (shape_repr) {
202             ec->shape_repr = shape_repr;
203             Inkscape::GC::anchor(shape_repr);
204             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
205         }
206     }
209 static void sp_flood_context_setup(SPEventContext *ec)
211     SPFloodContext *rc = SP_FLOOD_CONTEXT(ec);
213     if (((SPEventContextClass *) parent_class)->setup) {
214         ((SPEventContextClass *) parent_class)->setup(ec);
215     }
217     SPItem *item = sp_desktop_selection(ec->desktop)->singleItem();
218     if (item) {
219         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
220         if (shape_repr) {
221             ec->shape_repr = shape_repr;
222             Inkscape::GC::anchor(shape_repr);
223             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
224         }
225     }
227     rc->sel_changed_connection.disconnect();
228     rc->sel_changed_connection = sp_desktop_selection(ec->desktop)->connectChanged(
229         sigc::bind(sigc::ptr_fun(&sp_flood_context_selection_changed), (gpointer)rc)
230     );
232     rc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
235 /**
236 Hide all items which are not listed in list, recursively, skipping groups and defs
237 */
238 static void
239 hide_other_items_recursively(SPObject *o, GSList *list, unsigned dkey)
241     if (SP_IS_ITEM(o)
242         && !SP_IS_DEFS(o)
243         && !SP_IS_ROOT(o)
244         && !SP_IS_GROUP(o)
245         && !g_slist_find(list, o))
246     {
247         sp_item_invoke_hide(SP_ITEM(o), dkey);
248     }
250      // recurse
251     if (!g_slist_find(list, o)) {
252         for (SPObject *child = sp_object_first_child(o) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
253             hide_other_items_recursively(child, list, dkey);
254         }
255     }
258 inline unsigned char * get_pixel(guchar *px, int x, int y, int width) {
259   return px + (x + y * width) * 4;
262 static bool compare_pixels(unsigned char *a, unsigned char *b, int fuzziness) {
263   for (int i = 0; i < 4; i++) {
264     if (a[i] != b[i]) { 
265       return false;
266     }
267   }
268   return true;
271 static void try_add_to_queue(std::queue<NR::Point> *fill_queue, guchar *px, unsigned char *orig, int x, int y, int width) {
272   unsigned char *t = get_pixel(px, x, y, width);
273   if (compare_pixels(t, orig, 0)) {
274     fill_queue->push(NR::Point(x, y));
275   }
278 static void do_trace(GdkPixbuf *px, SPDesktop *desktop, NR::Matrix transform) {
279     SPDocument *document = sp_desktop_document(desktop);
280     
281     Inkscape::Trace::Potrace::PotraceTracingEngine pte;
282         
283     pte.setTraceType(Inkscape::Trace::Potrace::TRACE_BRIGHTNESS);
284     pte.setInvert(false);
286     Glib::RefPtr<Gdk::Pixbuf> pixbuf = Glib::wrap(px, true);
287     
288     std::vector<Inkscape::Trace::TracingEngineResult> results = pte.trace(pixbuf);
289     
290     Inkscape::XML::Node *layer_repr = SP_GROUP(desktop->currentLayer())->repr;
291     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
293     long totalNodeCount = 0L;
295     for (unsigned int i=0 ; i<results.size() ; i++) {
296         Inkscape::Trace::TracingEngineResult result = results[i];
297         totalNodeCount += result.getNodeCount();
299         Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path");
300         /* Set style */
301         sp_desktop_apply_style_tool (desktop, pathRepr, "tools.flood", false);
303         NArtBpath *bpath = sp_svg_read_path(result.getPathData().c_str());
304         Path *path = bpath_to_Path(bpath);
305         g_free(bpath);
306         
307         Shape *path_shape = new Shape();
308         
309         path->ConvertWithBackData(0.03);
310         path->Fill(path_shape, 0);
311         delete path;
312         
313         Shape *expanded_path_shape = new Shape();
314         
315         expanded_path_shape->ConvertToShape(path_shape, fill_nonZero);
316         path_shape->MakeOffset(expanded_path_shape, 1.5, join_round, 4);
317         expanded_path_shape->ConvertToShape(path_shape, fill_positive);
319         Path *expanded_path = new Path();
320         
321         expanded_path->Reset();
322         expanded_path_shape->ConvertToForme(expanded_path);
323         expanded_path->ConvertEvenLines(1.0);
324         expanded_path->Simplify(1.0);
325         
326         delete path_shape;
327         delete expanded_path_shape;
328         
329         gchar *str = expanded_path->svg_dump_path();
330         delete expanded_path;
331         pathRepr->setAttribute("d", str);
332         g_free(str);
333         
334         layer_repr->addChild(pathRepr, NULL);
336         SPObject *reprobj = document->getObjectByRepr(pathRepr);
337         if (reprobj) {
338             sp_item_write_transform(SP_ITEM(reprobj), pathRepr, transform, NULL);
339             Inkscape::Selection *selection = sp_desktop_selection(desktop);
340             selection->set(reprobj);
341             pathRepr->setPosition(-1);
342         }
343         
344         Inkscape::GC::release(pathRepr);
345     }
348 static void sp_flood_do_flood_fill(SPEventContext *event_context, GdkEvent *event) {
349     SPDesktop *desktop = event_context->desktop;
350     SPDocument *document = sp_desktop_document(desktop);
352     /* Create new arena */
353     NRArena *arena = NRArena::create();
354     unsigned dkey = sp_item_display_key_new(1);
356     sp_document_ensure_up_to_date (document);
357     
358     SPItem *document_root = SP_ITEM(SP_DOCUMENT_ROOT(document));
359     NR::Rect bbox = document_root->getBounds(NR::identity());
361     if (bbox.isEmpty()) { return; }
363     int width = (int)ceil(bbox.extent(NR::X));
364     int height = (int)ceil(bbox.extent(NR::Y));
366     NR::Point origin(bbox.min()[NR::X], bbox.min()[NR::Y]);
367     
368     NR::scale scale(width / (bbox.extent(NR::X)), height / (bbox.extent(NR::Y)));
369     NR::Matrix affine = scale * NR::translate(-origin * scale);
370     
371     /* Create ArenaItems and set transform */
372     NRArenaItem *root = sp_item_invoke_show(SP_ITEM(sp_document_root(document)), arena, dkey, SP_ITEM_SHOW_DISPLAY);
373     nr_arena_item_set_transform(root, affine);
375     NRGC gc(NULL);
376     nr_matrix_set_identity(&gc.transform);
377     
378     NRRectL final_bbox;
379     final_bbox.x0 = 0;
380     final_bbox.y0 = 0;//row;
381     final_bbox.x1 = width;
382     final_bbox.y1 = height;//row + num_rows;
383     
384     nr_arena_item_invoke_update(root, &final_bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
386 //     /* Set up pixblocks */
387     guchar *px = g_new(guchar, 4 * width * height);
388     memset(px, 0x00, 4 * width * height);
390     guchar *trace_px = g_new(guchar, 4 * width * height);
391     memset(trace_px, 0x00, 4 * width * height);
392     
393     NRPixBlock B;
394     nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
395                               final_bbox.x0, final_bbox.y0, final_bbox.x1, final_bbox.y1,
396                               px, 4 * width, FALSE, FALSE );
397     
398     nr_arena_item_invoke_render( root, &final_bbox, &B, NR_ARENA_ITEM_RENDER_NO_CACHE );
399     
400     nr_pixblock_release(&B);
401     nr_arena_item_unref(root);
402     nr_object_unref((NRObject *) arena);
403     
404     double zoom_scale = desktop->current_zoom();
406     NR::Point pw = NR::Point(event->button.x / zoom_scale, sp_document_height(document) + (event->button.y / zoom_scale)) * affine;
407     
408     pw[NR::X] = (int)MIN(width - 1, MAX(0, pw[NR::X]));
409     pw[NR::Y] = (int)MIN(height - 1, MAX(0, pw[NR::Y]));
411     std::queue<NR::Point> fill_queue;
412     fill_queue.push(pw);
413     
414     bool aborted = false;
415     int y_limit = height - 1;
416     
417     unsigned char orig_color[4];
418     unsigned char *orig_px = get_pixel(px, (int)pw[NR::X], (int)pw[NR::Y], width);
419     for (int i = 0; i < 4; i++) { orig_color[i] = orig_px[i]; }
421     while (!fill_queue.empty() && !aborted) {
422       NR::Point cp = fill_queue.front();
423       fill_queue.pop();
424       unsigned char *s = get_pixel(px, (int)cp[NR::X], (int)cp[NR::Y], width);
425       
426       // same color at this point
427       if (compare_pixels(s, orig_color, 0)) {
428         int left = (int)cp[NR::X];
429         int right = (int)cp[NR::X] + 1;
430         int x = (int)cp[NR::X];
431         int y = (int)cp[NR::Y];
432         
433         if (y > 0) { 
434           try_add_to_queue(&fill_queue, px, orig_color, x, y - 1, width);
435         } else {
436           aborted = true; break;
437         }
438         if (y < y_limit) { 
439           try_add_to_queue(&fill_queue, px, orig_color, x, y + 1, width);
440         } else {
441           aborted = true; break;
442         }
443         
444         unsigned char *t, *trace_t;
445         bool ok = false;
446         
447         do {
448           ok = false;
449           // go left
450           if (left >= 0) {
451             t = get_pixel(px, left, y, width);
452             if (compare_pixels(t, orig_color, 0)) {
453               for (int i = 0; i < 4; i++) { t[i] = 255 - t[i]; }
454               trace_t = get_pixel(trace_px, left, y, width);
455               trace_t[3] = 255;
456               if (y > 0) { try_add_to_queue(&fill_queue, px, orig_color, left, y - 1, width); }
457               if (y < y_limit) { try_add_to_queue(&fill_queue, px, orig_color, left, y + 1, width); }
458               left--; ok = true;
459             }
460           } else {
461             aborted = true; break;
462           }
463         } while (ok);
464       
465         do {
466           ok = false;
467           // go left
468           if (right < width) {
469             t = get_pixel(px, right, y, width);
470             if (compare_pixels(t, orig_color, 0)) {
471               for (int i = 0; i < 4; i++) { t[i] = 255 - t[i]; }
472               trace_t = get_pixel(trace_px, right, y, width);
473               trace_t[3] = 255; 
474               if (y > 0) { try_add_to_queue(&fill_queue, px, orig_color, right, y - 1, width); }
475               if (y < y_limit) { try_add_to_queue(&fill_queue, px, orig_color, right, y + 1, width); }
476               right++; ok = true;
477             }
478           } else {
479             aborted = true; break;
480           }
481         } while (ok);
482       }
483     }
484     
485     g_free(px);
486     
487     if (aborted) {
488       g_free(trace_px);
489       return;
490     }
491     
492     GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(trace_px,
493                                       GDK_COLORSPACE_RGB,
494                                       TRUE,
495                                       8, width, height, width * 4,
496                                       (GdkPixbufDestroyNotify)g_free,
497                                       NULL);
499     g_free(trace_px);
501     NR::Matrix inverted_affine = NR::Matrix(affine).inverse();
502     
503     do_trace(pixbuf, desktop, inverted_affine);
505     sp_document_done(document, SP_VERB_CONTEXT_FLOOD, _("Flood fill"));
508 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
510     gint ret = FALSE;
512     switch (event->type) {
513     case GDK_BUTTON_PRESS:
514         if ( event->button.button == 1 ) {
515             sp_flood_do_flood_fill(event_context, event);
516             ret = TRUE;
517         }
518         break;
519         // motion and release are always on root (why?)
520     default:
521         break;
522     }
524     if (((SPEventContextClass *) parent_class)->item_handler) {
525         ret = ((SPEventContextClass *) parent_class)->item_handler(event_context, item, event);
526     }
528     return ret;
531 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event)
533     gint ret = FALSE;
534     switch (event->type) {
535     case GDK_BUTTON_PRESS:
536         if ( event->button.button == 1 ) {
537             sp_flood_do_flood_fill(event_context, event);
539             ret = TRUE;
540         }
541         break;
542     default:
543         break;
544     }
546     if (!ret) {
547         if (((SPEventContextClass *) parent_class)->root_handler) {
548             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
549         }
550     }
552     return ret;
556 static void sp_flood_finish(SPFloodContext *rc)
558     rc->_message_context->clear();
560     if ( rc->item != NULL ) {
561         SPDesktop * desktop;
563         desktop = SP_EVENT_CONTEXT_DESKTOP(rc);
565         SP_OBJECT(rc->item)->updateRepr();
567         sp_canvas_end_forced_full_redraws(desktop->canvas);
569         sp_desktop_selection(desktop)->set(rc->item);
570         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_RECT,
571                          _("Create floodangle"));
573         rc->item = NULL;
574     }
577 /*
578   Local Variables:
579   mode:c++
580   c-file-style:"stroustrup"
581   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
582   indent-tabs-mode:nil
583   fill-column:99
584   End:
585 */
586 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :