summaryrefslogtreecommitdiffstats
path: root/src/trace/trace.cpp
blob: 802f497208296e726a886e4cc3f578375ec57b7e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * A generic interface for plugging different
 *  autotracers into Inkscape.
 *
 * Authors:
 *   Bob Jamison <rjamison@earthlink.net>
 *   Jon A. Cruz <jon@joncruz.org>
 *   Abhishek Sharma
 *
 * Copyright (C) 2004-2006 Bob Jamison
 *
 * Released under GNU GPL v2+, read the file 'COPYING' for more information.
 */

#include "trace/potrace/inkscape-potrace.h"

#include <limits>

#include <glibmm/i18n.h>
#include <gtkmm/main.h>

#include <2geom/transforms.h>

#include "desktop.h"
#include "document.h"
#include "document-undo.h"
#include "inkscape.h"
#include "message-stack.h"
#include "selection.h"

#include "display/cairo-utils.h"
#include "display/drawing.h"
#include "display/drawing-shape.h"

#include "object/sp-item.h"
#include "object/sp-shape.h"
#include "object/sp-image.h"

#include "ui/icon-names.h"

#include "xml/repr.h"
#include "xml/attribute-record.h"

#include "siox.h"

namespace Inkscape {
namespace Trace {

SPImage *Tracer::getSelectedSPImage()
{

    SPDesktop *desktop = SP_ACTIVE_DESKTOP;
    if (!desktop)
        {
        g_warning("Trace: No active desktop");
        return nullptr;
        }

    Inkscape::MessageStack *msgStack = desktop->getMessageStack();

    Inkscape::Selection *sel = desktop->getSelection();
    if (!sel)
        {
        char *msg = _("Select an <b>image</b> to trace");
        msgStack->flash(Inkscape::ERROR_MESSAGE, msg);
        //g_warning(msg);
        return nullptr;
        }

    if (sioxEnabled)
        {
        SPImage *img = nullptr;
        auto list = sel->items();
        std::vector<SPItem *> items;
        sioxShapes.clear();

        /*
           First, things are selected top-to-bottom, so we need to invert
           them as bottom-to-top so that we can discover the image and any
           SPItems above it
        */
        for (auto i=list.begin() ; list.end()!=i ; ++i)
            {
            if (!SP_IS_ITEM(*i))
                {
                continue;
                }
            SPItem *item = *i;
            items.insert(items.begin(), item);
            }
        std::vector<SPItem *>::iterator iter;
        for (iter = items.begin() ; iter!= items.end() ; ++iter)
            {
            SPItem *item = *iter;
            if (SP_IS_IMAGE(item))
                {
                if (img) //we want only one
                    {
                    char *msg = _("Select only one <b>image</b> to trace");
                    msgStack->flash(Inkscape::ERROR_MESSAGE, msg);
                    return nullptr;
                    }
                img = SP_IMAGE(item);
                }
            else // if (img) //# items -after- the image in tree (above it in Z)
                {
                if (SP_IS_SHAPE(item))
                    {
                    SPShape *shape = SP_SHAPE(item);
                    sioxShapes.push_back(shape);
                    }
                }
            }

        if (!img || sioxShapes.size() < 1)
            {
            char *msg = _("Select one image and one or more shapes above it");
            msgStack->flash(Inkscape::ERROR_MESSAGE, msg);
            return nullptr;
            }
        return img;
        }
    else
        //### SIOX not enabled.  We want exactly one image selected
        {
        SPItem *item = sel->singleItem();
        if (!item)
            {
            char *msg = _("Select an <b>image</b> to trace");  //same as above
            msgStack->flash(Inkscape::ERROR_MESSAGE, msg);
            //g_warning(msg);
            return nullptr;
            }

        if (!SP_IS_IMAGE(item))
            {
            char *msg = _("Select an <b>image</b> to trace");
            msgStack->flash(Inkscape::ERROR_MESSAGE, msg);
            //g_warning(msg);
            return nullptr;
            }

        SPImage *img = SP_IMAGE(item);

        return img;
        }

}



typedef org::siox::SioxImage SioxImage;
typedef org::siox::SioxObserver SioxObserver;
typedef org::siox::Siox Siox;


class TraceSioxObserver : public SioxObserver
{
public:

    /**
     *
     */
    TraceSioxObserver (void *contextArg) :
                     SioxObserver(contextArg)
        {}

    /**
     *
     */
    ~TraceSioxObserver () override
        = default;

    /**
     *  Informs the observer how much has been completed.
     *  Return false if the processing should be aborted.
     */
    bool progress(float /*percentCompleted*/) override
        {
        //Tracer *tracer = (Tracer *)context;
        //## Allow the GUI to update
        Gtk::Main::iteration(false); //at least once, non-blocking
        while( Gtk::Main::events_pending() )
            Gtk::Main::iteration();
        return true;
        }

    /**
     *  Send an error string to the Observer.  Processing will
     *  be halted.
     */
    void error(const std::string &/*msg*/) override
        {
        //Tracer *tracer = (Tracer *)context;
        }


};





Glib::RefPtr<Gdk::Pixbuf> Tracer::sioxProcessImage(SPImage *img, Glib::RefPtr<Gdk::Pixbuf>origPixbuf)
{
    if (!sioxEnabled)
        return origPixbuf;

    if (origPixbuf == lastOrigPixbuf)
        return lastSioxPixbuf;

    //g_message("siox: start");

    SioxImage simage(origPixbuf->gobj());

    SPDesktop *desktop = SP_ACTIVE_DESKTOP;
    if (!desktop)
        {
        g_warning("%s", _("Trace: No active desktop"));
        return Glib::RefPtr<Gdk::Pixbuf>(nullptr);
        }

    Inkscape::MessageStack *msgStack = desktop->getMessageStack();

    Inkscape::Selection *sel = desktop->getSelection();
    if (!sel)
        {
        char *msg = _("Select an <b>image</b> to trace");
        msgStack->flash(Inkscape::ERROR_MESSAGE, msg);
        //g_warning(msg);
        return Glib::RefPtr<Gdk::Pixbuf>(nullptr);
        }

    Inkscape::DrawingItem *aImg = img->get_arenaitem(desktop->dkey);
    //g_message("img: %d %d %d %d\n", aImg->bbox.x0, aImg->bbox.y0,
    //                                aImg->bbox.x1, aImg->bbox.y1);

    double width  = aImg->geometricBounds()->width();
    double height = aImg->geometricBounds()->height();

    double iwidth  = simage.getWidth();
    double iheight = simage.getHeight();

    double iwscale = width  / iwidth;
    double ihscale = height / iheight;

    std::vector<Inkscape::DrawingItem *> arenaItems;
    std::vector<SPShape *>::iterator iter;
    for (iter = sioxShapes.begin() ; iter!=sioxShapes.end() ; ++iter)
        {
        SPItem *item = *iter;
        Inkscape::DrawingItem *aItem = item->get_arenaitem(desktop->dkey);
        arenaItems.push_back(aItem);
        }

    //g_message("%d arena items\n", arenaItems.size());

    //g_message("siox: start selection");

    for (int row=0 ; row<iheight ; row++)
        {
        double ypos = aImg->geometricBounds()->top() + ihscale * (double) row;
        for (int col=0 ; col<simage.getWidth() ; col++)
            {
            //Get absolute X,Y position
            double xpos = aImg->geometricBounds()->left() + iwscale * (double)col;
            Geom::Point point(xpos, ypos);
            point *= aImg->transform();
            //point *= imgMat;
            //point = desktop->doc2dt(point);
            //g_message("x:%f    y:%f\n", point[0], point[1]);
            bool weHaveAHit = false;
            std::vector<Inkscape::DrawingItem *>::iterator aIter;
            for (aIter = arenaItems.begin() ; aIter!=arenaItems.end() ; ++aIter)
                {
                Inkscape::DrawingItem *arenaItem = *aIter;
                arenaItem->drawing().update();
                if (arenaItem->pick(point, 1.0f, 1))
                    {
                    weHaveAHit = true;
                    break;
                    }
                }

            if (weHaveAHit)
                {
                //g_message("hit!\n");
                simage.setConfidence(col, row,
                        Siox::UNKNOWN_REGION_CONFIDENCE);
                }
            else
                {
                //g_message("miss!\n");
                simage.setConfidence(col, row,
                        Siox::CERTAIN_BACKGROUND_CONFIDENCE);
                }
            }
        }

    //g_message("siox: selection done");

    //## ok we have our pixel buf
    TraceSioxObserver observer(this);
    Siox sengine(&observer);
    SioxImage result = sengine.extractForeground(simage, 0xffffff);
    if (!result.isValid())
        {
        g_warning("%s", _("Invalid SIOX result"));
        return Glib::RefPtr<Gdk::Pixbuf>(nullptr);
        }

    //result.writePPM("siox2.ppm");

    Glib::RefPtr<Gdk::Pixbuf> newPixbuf = Glib::wrap(result.getGdkPixbuf());

    //g_message("siox: done");

    lastSioxPixbuf = newPixbuf;

    return newPixbuf;
}


Glib::RefPtr<Gdk::Pixbuf> Tracer::getSelectedImage()
{


    SPImage *img = getSelectedSPImage();
    if (!img)
        return Glib::RefPtr<Gdk::Pixbuf>(nullptr);

    if (!img->pixbuf)
        return Glib::RefPtr<Gdk::Pixbuf>(nullptr);

    GdkPixbuf *raw_pb = img->pixbuf->getPixbufRaw(false);
    GdkPixbuf *trace_pb = gdk_pixbuf_copy(raw_pb);
    if (img->pixbuf->pixelFormat() == Inkscape::Pixbuf::PF_CAIRO) {
        convert_pixels_argb32_to_pixbuf(
            gdk_pixbuf_get_pixels(trace_pb),
            gdk_pixbuf_get_width(trace_pb),
            gdk_pixbuf_get_height(trace_pb),
            gdk_pixbuf_get_rowstride(trace_pb));
    }

    Glib::RefPtr<Gdk::Pixbuf> pixbuf = Glib::wrap(trace_pb, false);

    if (sioxEnabled)
        {
        Glib::RefPtr<Gdk::Pixbuf> sioxPixbuf =
             sioxProcessImage(img, pixbuf);
        if (!sioxPixbuf)
            {
            return pixbuf;
            }
        else
            {
            return sioxPixbuf;
            }
        }
    else
        {
        return pixbuf;
        }

}



//#########################################################################
//#  T R A C E
//#########################################################################

void Tracer::enableSiox(bool enable)
{
    sioxEnabled = enable;
}


void Tracer::traceThread()
{
    //## Remember. NEVER leave this method without setting
    //## engine back to NULL

    //## Prepare our kill flag.  We will watch this later to
    //## see if the main thread wants us to stop
    keepGoing = true;

    SPDesktop *desktop = SP_ACTIVE_DESKTOP;
    if (!desktop)
        {
        g_warning("Trace: No active desktop\n");
        return;
        }

    Inkscape::MessageStack *msgStack = desktop->getMessageStack();

    Inkscape::Selection *selection = desktop->getSelection();

    if (!SP_ACTIVE_DOCUMENT)
        {
        char *msg = _("Trace: No active document");
        msgStack->flash(Inkscape::ERROR_MESSAGE, msg);
        //g_warning(msg);
        engine = nullptr;
        return;
        }
    SPDocument *doc = SP_ACTIVE_DOCUMENT;
    doc->ensureUpToDate();


    SPImage *img = getSelectedSPImage();
    if (!img)
        {
        engine = nullptr;
        return;
        }

    GdkPixbuf *trace_pb = gdk_pixbuf_copy(img->pixbuf->getPixbufRaw(false));
    if (img->pixbuf->pixelFormat() == Inkscape::Pixbuf::PF_CAIRO) {
        convert_pixels_argb32_to_pixbuf(
            gdk_pixbuf_get_pixels(trace_pb),
            gdk_pixbuf_get_width(trace_pb),
            gdk_pixbuf_get_height(trace_pb),
            gdk_pixbuf_get_rowstride(trace_pb));
    }

    Glib::RefPtr<Gdk::Pixbuf> pixbuf = Glib::wrap(trace_pb, false);

    pixbuf = sioxProcessImage(img, pixbuf);

    if (!pixbuf)
        {
        char *msg = _("Trace: Image has no bitmap data");
        msgStack->flash(Inkscape::ERROR_MESSAGE, msg);
        //g_warning(msg);
        engine = nullptr;
        return;
        }

    msgStack->flash(Inkscape::NORMAL_MESSAGE, _("Trace: Starting trace..."));
    desktop->updateCanvasNow();

    std::vector<TracingEngineResult> results =
                engine->trace(pixbuf);
    //printf("nrPaths:%d\n", results.size());
    int nrPaths = results.size();

    //### Check if we should stop
    if (!keepGoing || nrPaths<1)
        {
        engine = nullptr;
        return;
        }

    //### Get pointers to the <image> and its parent
    //XML Tree being used directly here while it shouldn't be.
    Inkscape::XML::Node *imgRepr   = img->getRepr();
    Inkscape::XML::Node *par       = imgRepr->parent();

    //### Get some information for the new transform()
    double x = imgRepr->getAttributeDouble("x", 0.0);
    double y = imgRepr->getAttributeDouble("y", 0.0);
    double width = imgRepr->getAttributeDouble("width", 0.0);
    double height = imgRepr->getAttributeDouble("height", 0.0);

    double iwidth  = (double)pixbuf->get_width();
    double iheight = (double)pixbuf->get_height();

    double iwscale = width  / iwidth;
    double ihscale = height / iheight;

    Geom::Translate trans(x, y);
    Geom::Scale scal(iwscale, ihscale);

    //# Convolve scale, translation, and the original transform
    Geom::Affine tf(scal * trans);
    tf *= img->transform;


    //#OK.  Now let's start making new nodes

    Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc();
    Inkscape::XML::Node *groupRepr = nullptr;

    //# if more than 1, make a <g>roup of <path>s
    if (nrPaths > 1)
        {
        groupRepr = xml_doc->createElement("svg:g");
        par->addChild(groupRepr, imgRepr);
        }

    long totalNodeCount = 0L;

    for (auto result : results)
        {
        totalNodeCount += result.getNodeCount();

        Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path");
        pathRepr->setAttributeOrRemoveIfEmpty("style", result.getStyle());
        pathRepr->setAttributeOrRemoveIfEmpty("d",     result.getPathData());

        if (nrPaths > 1)
            groupRepr->addChild(pathRepr, nullptr);
        else
            par->addChild(pathRepr, imgRepr);

        //### Apply the transform from the image to the new shape
        SPObject *reprobj = doc->getObjectByRepr(pathRepr);
        if (reprobj)
            {
            SPItem *newItem = SP_ITEM(reprobj);
            newItem->doWriteTransform(tf);
            }
        if (nrPaths == 1)
            {
            selection->clear();
            selection->add(pathRepr);
            }
        Inkscape::GC::release(pathRepr);
        }

    // If we have a group, then focus on, then forget it
    if (nrPaths > 1)
        {
        selection->clear();
        selection->add(groupRepr);
        Inkscape::GC::release(groupRepr);
        }

    //## inform the document, so we can undo
    DocumentUndo::done(doc, _("Trace bitmap"), INKSCAPE_ICON("bitmap-trace"));

    engine = nullptr;

    char *msg = g_strdup_printf(_("Trace: Done. %ld nodes created"), totalNodeCount);
    msgStack->flash(Inkscape::NORMAL_MESSAGE, msg);
    g_free(msg);

}





void Tracer::trace(TracingEngine *theEngine)
{
    //Check if we are already running
    if (engine)
        return;

    engine = theEngine;

    traceThread();
}





void Tracer::abort()
{

    //## Inform Trace's working thread
    keepGoing = false;

    if (engine)
        {
        engine->abort();
        }

}



} // namespace Trace

} // namespace Inkscape


//#########################################################################
//# E N D   O F   F I L E
//#########################################################################