Code

Add 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 void try_add_to_queue(std::queue<NR::Point> *fill_queue, guchar *px, int x, int y, int width) {
263   unsigned char *t = get_pixel(px, x, y, width);
264   if (t[3] == 0) {
265     fill_queue->push(NR::Point(x, y));
266   }
269 static void do_trace(GdkPixbuf *px, SPDesktop *desktop, NR::Matrix transform) {
270     SPDocument *document = sp_desktop_document(desktop);
271     
272     Inkscape::Trace::Potrace::PotraceTracingEngine pte;
273         
274     pte.setTraceType(Inkscape::Trace::Potrace::TRACE_BRIGHTNESS);
275     pte.setInvert(false);
277     Glib::RefPtr<Gdk::Pixbuf> pixbuf = Glib::wrap(px, true);
278     
279     std::vector<Inkscape::Trace::TracingEngineResult> results = pte.trace(pixbuf);
280     
281     Inkscape::XML::Node *layer_repr = SP_GROUP(desktop->currentLayer())->repr;
282     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
284     long totalNodeCount = 0L;
286     for (unsigned int i=0 ; i<results.size() ; i++) {
287         Inkscape::Trace::TracingEngineResult result = results[i];
288         totalNodeCount += result.getNodeCount();
290         Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path");
291         /* Set style */
292         sp_desktop_apply_style_tool (desktop, pathRepr, "tools.flood", false);
294         NArtBpath *bpath = sp_svg_read_path(result.getPathData().c_str());
295         Path *path = bpath_to_Path(bpath);
296         g_free(bpath);
297         
298         Shape *path_shape = new Shape();
299         
300         path->ConvertWithBackData(0.03);
301         path->Fill(path_shape, 0);
302         delete path;
303         
304         Shape *expanded_path_shape = new Shape();
305         
306         expanded_path_shape->ConvertToShape(path_shape, fill_nonZero);
307         path_shape->MakeOffset(expanded_path_shape, 1.5, join_round, 4);
308         expanded_path_shape->ConvertToShape(path_shape, fill_positive);
310         Path *expanded_path = new Path();
311         
312         expanded_path->Reset();
313         expanded_path_shape->ConvertToForme(expanded_path);
314         expanded_path->ConvertEvenLines(1.0);
315         expanded_path->Simplify(1.0);
316         
317         delete path_shape;
318         delete expanded_path_shape;
319         
320         gchar *str = expanded_path->svg_dump_path();
321         delete expanded_path;
322         pathRepr->setAttribute("d", str);
323         g_free(str);
324         
325         layer_repr->addChild(pathRepr, NULL);
327         SPObject *reprobj = document->getObjectByRepr(pathRepr);
328         if (reprobj) {
329             sp_item_write_transform(SP_ITEM(reprobj), pathRepr, transform, NULL);
330             Inkscape::Selection *selection = sp_desktop_selection(desktop);
331             selection->set(reprobj);
332         }
333         
334         Inkscape::GC::release(pathRepr);
335     }
338 static void sp_flood_do_flood_fill(SPEventContext *event_context, GdkEvent *event) {
339     SPDesktop *desktop = event_context->desktop;
340     SPDocument *document = sp_desktop_document(desktop);
342     /* Create new arena */
343     NRArena *arena = NRArena::create();
344     unsigned dkey = sp_item_display_key_new(1);
346     sp_document_ensure_up_to_date (document);
347     
348     SPItem *document_root = SP_ITEM(SP_DOCUMENT_ROOT(document));
349     NR::Rect bbox = document_root->invokeBbox(NR::identity());
351     if (bbox.isEmpty()) { return; }
353     int width = (int)ceil(bbox.extent(NR::X));
354     int height = (int)ceil(bbox.extent(NR::Y));
356     NR::Point origin(bbox.min()[NR::X], bbox.min()[NR::Y]);
357     
358     NR::scale scale(width / (bbox.extent(NR::X)), height / (bbox.extent(NR::Y)));
359     NR::Matrix affine = scale * NR::translate(-origin * scale);
360     
361     /* Create ArenaItems and set transform */
362     NRArenaItem *root = sp_item_invoke_show(SP_ITEM(sp_document_root(document)), arena, dkey, SP_ITEM_SHOW_DISPLAY);
363     nr_arena_item_set_transform(root, affine);
365     NRGC gc(NULL);
366     nr_matrix_set_identity(&gc.transform);
367     
368     NRRectL final_bbox;
369     final_bbox.x0 = 0;
370     final_bbox.y0 = 0;//row;
371     final_bbox.x1 = width;
372     final_bbox.y1 = height;//row + num_rows;
373     
374     nr_arena_item_invoke_update(root, &final_bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
376 //     /* Set up pixblocks */
377     guchar *px = g_new(guchar, 4 * width * height);
378     memset(px, 0x00, 4 * width * height);
380     guchar *trace_px = g_new(guchar, 4 * width * height);
381     memset(trace_px, 0x00, 4 * width * height);
382 // 
383 //     /* Render */
384     NRPixBlock B;
385     nr_pixblock_setup_extern( &B, NR_PIXBLOCK_MODE_R8G8B8A8N,
386                               final_bbox.x0, final_bbox.y0, final_bbox.x1, final_bbox.y1,
387                               px, 4 * width, FALSE, FALSE );
388     
389     nr_arena_item_invoke_render( root, &final_bbox, &B, NR_ARENA_ITEM_RENDER_NO_CACHE );
390     nr_pixblock_release(&B);
391 // 
392     double zoom_scale = desktop->current_zoom();
394     NR::Point pw = NR::Point(event->button.x / zoom_scale, sp_document_height(document) + (event->button.y / zoom_scale)) * affine;
395     
396     pw[NR::X] = (int)MIN(width - 1, MAX(0, pw[NR::X]));
397     pw[NR::Y] = (int)MIN(height - 1, MAX(0, pw[NR::Y]));
399     std::queue<NR::Point> fill_queue;
400     fill_queue.push(pw);
401     
402     while (!fill_queue.empty()) {
403       NR::Point cp = fill_queue.front();
404       fill_queue.pop();
405       unsigned char *s = get_pixel(px, (int)cp[NR::X], (int)cp[NR::Y], width);
406       
407       // nothing at this point
408       if (s[3] == 0) {
409         int left = (int)cp[NR::X];
410         int right = (int)cp[NR::X] + 1;
411         int x = (int)cp[NR::X];
412         int y = (int)cp[NR::Y];
413         
414         if (y > 0) { try_add_to_queue(&fill_queue, px, x, y - 1, width); }
415         if (y < (height - 1)) { try_add_to_queue(&fill_queue, px, x, y + 1, width); }
416         
417         unsigned char *t, *trace_t;
418         bool ok = false;
419         
420         do {
421           ok = false;
422           // go left
423           if (left >= 0) {
424             t = get_pixel(px, left, y, width);
425             if (t[3] == 0) {
426               t[0] = 255; t[3] = 255;
427               trace_t = get_pixel(trace_px, left, y, width);
428               trace_t[0] = 255; trace_t[3] = 255;
429               if (y > 0) { try_add_to_queue(&fill_queue, px, left, y - 1, width); }
430               if (y < (height - 1)) { try_add_to_queue(&fill_queue, px, left, y + 1, width); }
431               left--; ok = true;
432             }
433           }
434         } while (ok);
435       
436         do {
437           ok = false;
438           // go left
439           if (right < width) {
440             t = get_pixel(px, right, y, width);
441             if (t[3] == 0) {
442               t[0] = 255; t[3] = 255; 
443               trace_t = get_pixel(trace_px, right, y, width);
444               trace_t[0] = 255; trace_t[3] = 255; 
445               if (y > 0) { try_add_to_queue(&fill_queue, px, right, y - 1, width); }
446               if (y < (height - 1)) { try_add_to_queue(&fill_queue, px, right, y + 1, width); }
447               right++; ok = true;
448             }
449           }
450         } while (ok);
451       }
452     }
453     
454     g_free(px);
455     
456     GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(trace_px,
457                                       GDK_COLORSPACE_RGB,
458                                       TRUE,
459                                       8, width, height, width * 4,
460                                       (GdkPixbufDestroyNotify)g_free,
461                                       NULL);
463     NR::Matrix inverted_affine = NR::Matrix(affine).inverse();
464     
465     do_trace(pixbuf, desktop, inverted_affine);
467     /* Free Arena and ArenaItem */
468     nr_arena_item_unref(root);
469     nr_object_unref((NRObject *) arena);
470     
471     sp_document_done(document, SP_VERB_CONTEXT_FLOOD, _("Flood fill"));
474 static gint sp_flood_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
476     gint ret = FALSE;
478     switch (event->type) {
479     case GDK_BUTTON_PRESS:
480         if ( event->button.button == 1 ) {
481             sp_flood_do_flood_fill(event_context, event);
482             ret = TRUE;
483         }
484         break;
485         // motion and release are always on root (why?)
486     default:
487         break;
488     }
490     if (((SPEventContextClass *) parent_class)->item_handler) {
491         ret = ((SPEventContextClass *) parent_class)->item_handler(event_context, item, event);
492     }
494     return ret;
497 static gint sp_flood_context_root_handler(SPEventContext *event_context, GdkEvent *event)
499     gint ret = FALSE;
500     switch (event->type) {
501     case GDK_BUTTON_PRESS:
502         if ( event->button.button == 1 ) {
503             sp_flood_do_flood_fill(event_context, event);
505             ret = TRUE;
506         }
507         break;
508     default:
509         break;
510     }
512     if (!ret) {
513         if (((SPEventContextClass *) parent_class)->root_handler) {
514             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
515         }
516     }
518     return ret;
522 static void sp_flood_finish(SPFloodContext *rc)
524     rc->_message_context->clear();
526     if ( rc->item != NULL ) {
527         SPDesktop * desktop;
529         desktop = SP_EVENT_CONTEXT_DESKTOP(rc);
531         SP_OBJECT(rc->item)->updateRepr();
533         sp_canvas_end_forced_full_redraws(desktop->canvas);
535         sp_desktop_selection(desktop)->set(rc->item);
536         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_RECT,
537                          _("Create floodangle"));
539         rc->item = NULL;
540     }
543 /*
544   Local Variables:
545   mode:c++
546   c-file-style:"stroustrup"
547   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
548   indent-tabs-mode:nil
549   fill-column:99
550   End:
551 */
552 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :