~valavanisalex/ubuntu/precise/inkscape/fix-943984

« back to all changes in this revision

Viewing changes to inkscape-0.47pre1/src/ui/clipboard.cpp

  • Committer: Bazaar Package Importer
  • Author(s): Bryce Harrington
  • Date: 2009-07-02 17:09:45 UTC
  • mfrom: (1.1.9 upstream)
  • Revision ID: james.westby@ubuntu.com-20090702170945-nn6d6zswovbwju1t
Tags: 0.47~pre1-0ubuntu1
* New upstream release.
  - Don't constrain maximization on small resolution devices (pre0)
    (LP: #348842)
  - Fixes segfault on startup (pre0)
    (LP: #391149)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/** @file
 
2
 * @brief System-wide clipboard management - implementation
 
3
 */
 
4
/* Authors:
 
5
 *   Krzysztof Kosiński <tweenk@o2.pl>
 
6
 *   Incorporates some code from selection-chemistry.cpp, see that file for more credits.
 
7
 *
 
8
 * Copyright (C) 2008 authors
 
9
 *
 
10
 * This program is free software; you can redistribute it and/or
 
11
 * modify it under the terms of the GNU General Public License
 
12
 * as published by the Free Software Foundation; either version 2
 
13
 * of the License, or (at your option) any later version.
 
14
 *
 
15
 * See the file COPYING for details.
 
16
 */
 
17
 
 
18
#include "ui/clipboard.h"
 
19
 
 
20
// TODO: reduce header bloat if possible
 
21
 
 
22
#include <list>
 
23
#include <algorithm>
 
24
#include <gtkmm/clipboard.h>
 
25
#include <glibmm/ustring.h>
 
26
#include <glibmm/i18n.h>
 
27
#include <glib/gstdio.h> // for g_file_set_contents etc., used in _onGet and paste
 
28
#include "gc-core.h"
 
29
#include "xml/repr.h"
 
30
#include "inkscape.h"
 
31
#include "io/stringstream.h"
 
32
#include "desktop.h"
 
33
#include "desktop-handles.h"
 
34
#include "desktop-style.h" // for sp_desktop_set_style, used in _pasteStyle
 
35
#include "document.h"
 
36
#include "document-private.h"
 
37
#include "selection.h"
 
38
#include "message-stack.h"
 
39
#include "context-fns.h"
 
40
#include "dropper-context.h" // used in copy()
 
41
#include "style.h"
 
42
#include "extension/db.h" // extension database
 
43
#include "extension/input.h"
 
44
#include "extension/output.h"
 
45
#include "selection-chemistry.h"
 
46
#include "libnr/nr-rect.h"
 
47
#include "libnr/nr-convert2geom.h"
 
48
#include <2geom/rect.h>
 
49
#include <2geom/transforms.h>
 
50
#include "box3d.h"
 
51
#include "gradient-drag.h"
 
52
#include "sp-item.h"
 
53
#include "sp-item-transform.h" // for sp_item_scale_rel, used in _pasteSize
 
54
#include "sp-path.h"
 
55
#include "sp-pattern.h"
 
56
#include "sp-shape.h"
 
57
#include "sp-gradient.h"
 
58
#include "sp-gradient-reference.h"
 
59
#include "sp-gradient-fns.h"
 
60
#include "sp-linear-gradient-fns.h"
 
61
#include "sp-radial-gradient-fns.h"
 
62
#include "sp-clippath.h"
 
63
#include "sp-mask.h"
 
64
#include "sp-textpath.h"
 
65
#include "sp-rect.h"
 
66
#include "live_effects/lpeobject.h"
 
67
#include "live_effects/lpeobject-reference.h"
 
68
#include "live_effects/parameter/path.h"
 
69
#include "svg/svg.h" // for sp_svg_transform_write, used in _copySelection
 
70
#include "svg/css-ostringstream.h" // used in _parseColor
 
71
#include "file.h" // for file_import, used in _pasteImage
 
72
#include "preferences.h" // for used in _pasteImage
 
73
#include "text-context.h"
 
74
#include "text-editing.h"
 
75
#include "tools-switch.h"
 
76
#include "path-chemistry.h"
 
77
#include "id-clash.h"
 
78
#include "unit-constants.h"
 
79
#include "helper/png-write.h"
 
80
#include "svg/svg-color.h"
 
81
#include "sp-namedview.h"
 
82
#include "snap.h"
 
83
 
 
84
/// @brief Made up mimetype to represent Gdk::Pixbuf clipboard contents
 
85
#define CLIPBOARD_GDK_PIXBUF_TARGET "image/x-gdk-pixbuf"
 
86
 
 
87
#define CLIPBOARD_TEXT_TARGET "text/plain"
 
88
 
 
89
#ifdef WIN32
 
90
#include <windows.h>
 
91
// Clipboard Formats: http://msdn.microsoft.com/en-us/library/ms649013(VS.85).aspx
 
92
// On Windows, most graphical applications can handle CF_DIB/CF_BITMAP and/or CF_ENHMETAFILE
 
93
// GTK automatically presents an "image/bmp" target as CF_DIB/CF_BITMAP
 
94
// Presenting "image/x-emf" as CF_ENHMETAFILE must be done by Inkscape ?
 
95
#define CLIPBOARD_WIN32_EMF_TARGET "CF_ENHMETAFILE"
 
96
#define CLIPBOARD_WIN32_EMF_MIME   "image/x-emf"
 
97
#endif
 
98
 
 
99
namespace Inkscape {
 
100
namespace UI {
 
101
 
 
102
 
 
103
/**
 
104
 * @brief Default implementation of the clipboard manager
 
105
 */
 
106
class ClipboardManagerImpl : public ClipboardManager {
 
107
public:
 
108
    virtual void copy();
 
109
    virtual void copyPathParameter(Inkscape::LivePathEffect::PathParam *);
 
110
    virtual bool paste(bool in_place);
 
111
    virtual bool pasteStyle();
 
112
    virtual bool pasteSize(bool, bool, bool);
 
113
    virtual bool pastePathEffect();
 
114
    virtual Glib::ustring getPathParameter();
 
115
    virtual Glib::ustring getShapeOrTextObjectId();
 
116
    virtual const gchar *getFirstObjectID();
 
117
 
 
118
    ClipboardManagerImpl();
 
119
    ~ClipboardManagerImpl();
 
120
 
 
121
private:
 
122
    void _copySelection(Inkscape::Selection *);
 
123
    void _copyUsedDefs(SPItem *);
 
124
    void _copyGradient(SPGradient *);
 
125
    void _copyPattern(SPPattern *);
 
126
    void _copyTextPath(SPTextPath *);
 
127
    Inkscape::XML::Node *_copyNode(Inkscape::XML::Node *, Inkscape::XML::Document *, Inkscape::XML::Node *);
 
128
 
 
129
    void _pasteDocument(SPDocument *, bool in_place);
 
130
    void _pasteDefs(SPDocument *);
 
131
    bool _pasteImage();
 
132
    bool _pasteText();
 
133
    SPCSSAttr *_parseColor(const Glib::ustring &);
 
134
    void _applyPathEffect(SPItem *, gchar const *);
 
135
    SPDocument *_retrieveClipboard(Glib::ustring = "");
 
136
 
 
137
    // clipboard callbacks
 
138
    void _onGet(Gtk::SelectionData &, guint);
 
139
    void _onClear();
 
140
 
 
141
    // various helpers
 
142
    void _createInternalClipboard();
 
143
    void _discardInternalClipboard();
 
144
    Inkscape::XML::Node *_createClipNode();
 
145
    Geom::Scale _getScale(Geom::Point const &, Geom::Point const &, Geom::Rect const &, bool, bool);
 
146
    Glib::ustring _getBestTarget();
 
147
    void _setClipboardTargets();
 
148
    void _setClipboardColor(guint32);
 
149
    void _userWarn(SPDesktop *, char const *);
 
150
 
 
151
    // private properites
 
152
    SPDocument *_clipboardSPDoc; ///< Document that stores the clipboard until someone requests it
 
153
    Inkscape::XML::Node *_defs; ///< Reference to the clipboard document's defs node
 
154
    Inkscape::XML::Node *_root; ///< Reference to the clipboard's root node
 
155
    Inkscape::XML::Node *_clipnode; ///< The node that holds extra information
 
156
    Inkscape::XML::Document *_doc; ///< Reference to the clipboard's Inkscape::XML::Document
 
157
 
 
158
    // we need a way to copy plain text AND remember its style;
 
159
    // the standard _clipnode is only available in an SVG tree, hence this special storage
 
160
    SPCSSAttr *_text_style; ///< Style copied along with plain text fragment
 
161
 
 
162
    Glib::RefPtr<Gtk::Clipboard> _clipboard; ///< Handle to the system wide clipboard - for convenience
 
163
    std::list<Glib::ustring> _preferred_targets; ///< List of supported clipboard targets
 
164
};
 
165
 
 
166
 
 
167
ClipboardManagerImpl::ClipboardManagerImpl()
 
168
    : _clipboardSPDoc(NULL),
 
169
      _defs(NULL),
 
170
      _root(NULL),
 
171
      _clipnode(NULL),
 
172
      _doc(NULL),
 
173
      _text_style(NULL),
 
174
      _clipboard( Gtk::Clipboard::get() )
 
175
{
 
176
    // push supported clipboard targets, in order of preference
 
177
    _preferred_targets.push_back("image/x-inkscape-svg");
 
178
    _preferred_targets.push_back("image/svg+xml");
 
179
    _preferred_targets.push_back("image/svg+xml-compressed");
 
180
#ifdef WIN32
 
181
    _preferred_targets.push_back(CLIPBOARD_WIN32_EMF_MIME);
 
182
#endif
 
183
    _preferred_targets.push_back("application/pdf");
 
184
    _preferred_targets.push_back("image/x-adobe-illustrator");
 
185
}
 
186
 
 
187
 
 
188
ClipboardManagerImpl::~ClipboardManagerImpl() {}
 
189
 
 
190
 
 
191
/**
 
192
 * @brief Copy selection contents to the clipboard
 
193
 */
 
194
void ClipboardManagerImpl::copy()
 
195
{
 
196
    SPDesktop *desktop = SP_ACTIVE_DESKTOP;
 
197
    if ( desktop == NULL ) return;
 
198
    Inkscape::Selection *selection = sp_desktop_selection(desktop);
 
199
 
 
200
    // Special case for when the gradient dragger is active - copies gradient color
 
201
    if (desktop->event_context->get_drag()) {
 
202
        GrDrag *drag = desktop->event_context->get_drag();
 
203
        if (drag->hasSelection()) {
 
204
            guint32 col = drag->getColor();
 
205
 
 
206
            // set the color as clipboard content (text in RRGGBBAA format)
 
207
            _setClipboardColor(col);
 
208
 
 
209
            // create a style with this color on fill and opacity in master opacity, so it can be
 
210
            // pasted on other stops or objects
 
211
            if (_text_style) {
 
212
                sp_repr_css_attr_unref(_text_style);
 
213
                _text_style = NULL;
 
214
            }
 
215
            _text_style = sp_repr_css_attr_new();
 
216
            // print and set properties
 
217
            gchar color_str[16];
 
218
            g_snprintf(color_str, 16, "#%06x", col >> 8);
 
219
            sp_repr_css_set_property(_text_style, "fill", color_str);
 
220
            float opacity = SP_RGBA32_A_F(col);
 
221
            if (opacity > 1.0) opacity = 1.0; // safeguard
 
222
            Inkscape::CSSOStringStream opcss;
 
223
            opcss << opacity;
 
224
            sp_repr_css_set_property(_text_style, "opacity", opcss.str().data());
 
225
 
 
226
            _discardInternalClipboard();
 
227
            return;
 
228
        }
 
229
    }
 
230
 
 
231
    // Special case for when the color picker ("dropper") is active - copies color under cursor
 
232
    if (tools_isactive(desktop, TOOLS_DROPPER)) {
 
233
        _setClipboardColor(sp_dropper_context_get_color(desktop->event_context));
 
234
        _discardInternalClipboard();
 
235
        return;
 
236
    }
 
237
 
 
238
    // Special case for when the text tool is active - if some text is selected, copy plain text,
 
239
    // not the object that holds it; also copy the style at cursor into
 
240
    if (tools_isactive(desktop, TOOLS_TEXT)) {
 
241
        _discardInternalClipboard();
 
242
        Glib::ustring selected_text = sp_text_get_selected_text(desktop->event_context);
 
243
        if (!selected_text.empty()) {
 
244
            _clipboard->set_text(selected_text);
 
245
        }
 
246
        if (_text_style) {
 
247
            sp_repr_css_attr_unref(_text_style);
 
248
            _text_style = NULL;
 
249
        }
 
250
        _text_style = sp_text_get_style_at_cursor(desktop->event_context);
 
251
        return;
 
252
    }
 
253
 
 
254
    if (selection->isEmpty()) {  // check whether something is selected
 
255
        _userWarn(desktop, _("Nothing was copied."));
 
256
        return;
 
257
    }
 
258
    _discardInternalClipboard();
 
259
 
 
260
    _createInternalClipboard();   // construct a new clipboard document
 
261
    _copySelection(selection);   // copy all items in the selection to the internal clipboard
 
262
    fit_canvas_to_drawing(_clipboardSPDoc);
 
263
 
 
264
    _setClipboardTargets();
 
265
}
 
266
 
 
267
 
 
268
/**
 
269
 * @brief Copy a Live Path Effect path parameter to the clipboard
 
270
 * @param pp The path parameter to store in the clipboard
 
271
 */
 
272
void ClipboardManagerImpl::copyPathParameter(Inkscape::LivePathEffect::PathParam *pp)
 
273
{
 
274
    if ( pp == NULL ) return;
 
275
    gchar *svgd = sp_svg_write_path( pp->get_pathvector() );
 
276
    if ( svgd == NULL || *svgd == '\0' ) return;
 
277
 
 
278
    _discardInternalClipboard();
 
279
    _createInternalClipboard();
 
280
 
 
281
    Inkscape::XML::Node *pathnode = _doc->createElement("svg:path");
 
282
    pathnode->setAttribute("d", svgd);
 
283
    g_free(svgd);
 
284
    _root->appendChild(pathnode);
 
285
    Inkscape::GC::release(pathnode);
 
286
 
 
287
    fit_canvas_to_drawing(_clipboardSPDoc);
 
288
    _setClipboardTargets();
 
289
}
 
290
 
 
291
/**
 
292
 * @brief Paste from the system clipboard into the active desktop
 
293
 * @param in_place Whether to put the contents where they were when copied
 
294
 */
 
295
bool ClipboardManagerImpl::paste(bool in_place)
 
296
{
 
297
    // do any checking whether we really are able to paste before requesting the contents
 
298
    SPDesktop *desktop = SP_ACTIVE_DESKTOP;
 
299
    if ( desktop == NULL ) return false;
 
300
    if ( Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false ) return false;
 
301
 
 
302
    Glib::ustring target = _getBestTarget();
 
303
 
 
304
    // Special cases of clipboard content handling go here
 
305
    // Note that target priority is determined in _getBestTarget.
 
306
    // TODO: Handle x-special/gnome-copied-files and text/uri-list to support pasting files
 
307
 
 
308
    // if there is an image on the clipboard, paste it
 
309
    if ( target == CLIPBOARD_GDK_PIXBUF_TARGET ) return _pasteImage();
 
310
    // if there's only text, paste it into a selected text object or create a new one
 
311
    if ( target == CLIPBOARD_TEXT_TARGET ) return _pasteText();
 
312
 
 
313
    // otherwise, use the import extensions
 
314
    SPDocument *tempdoc = _retrieveClipboard(target);
 
315
    if ( tempdoc == NULL ) {
 
316
        _userWarn(desktop, _("Nothing on the clipboard."));
 
317
        return false;
 
318
    }
 
319
 
 
320
    _pasteDocument(tempdoc, in_place);
 
321
    sp_document_unref(tempdoc);
 
322
 
 
323
    return true;
 
324
}
 
325
 
 
326
/**
 
327
 * @brief Returns the id of the first visible copied object
 
328
 */
 
329
const gchar *ClipboardManagerImpl::getFirstObjectID()
 
330
{
 
331
    SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
 
332
    if ( tempdoc == NULL ) {
 
333
        return NULL;
 
334
    }
 
335
 
 
336
    Inkscape::XML::Node
 
337
        *root = sp_document_repr_root(tempdoc);
 
338
 
 
339
    if (!root)
 
340
        return NULL;
 
341
 
 
342
    Inkscape::XML::Node *ch = sp_repr_children(root);
 
343
    while (ch != NULL &&
 
344
           strcmp(ch->name(), "svg:g") &&
 
345
           strcmp(ch->name(), "svg:path") &&
 
346
           strcmp(ch->name(), "svg:use") &&
 
347
           strcmp(ch->name(), "svg:text") &&
 
348
           strcmp(ch->name(), "svg:image") &&
 
349
           strcmp(ch->name(), "svg:rect")
 
350
        )
 
351
        ch = ch->next();
 
352
 
 
353
    if (ch) {
 
354
        return ch->attribute("id");
 
355
    }
 
356
 
 
357
    return NULL;
 
358
}
 
359
 
 
360
 
 
361
/**
 
362
 * @brief Implements the Paste Style action
 
363
 */
 
364
bool ClipboardManagerImpl::pasteStyle()
 
365
{
 
366
    SPDesktop *desktop = SP_ACTIVE_DESKTOP;
 
367
    if (desktop == NULL) return false;
 
368
 
 
369
    // check whether something is selected
 
370
    Inkscape::Selection *selection = sp_desktop_selection(desktop);
 
371
    if (selection->isEmpty()) {
 
372
        _userWarn(desktop, _("Select <b>object(s)</b> to paste style to."));
 
373
        return false;
 
374
    }
 
375
 
 
376
    SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
 
377
    if ( tempdoc == NULL ) {
 
378
        // no document, but we can try _text_style
 
379
        if (_text_style) {
 
380
            sp_desktop_set_style(desktop, _text_style);
 
381
            return true;
 
382
        } else {
 
383
            _userWarn(desktop, _("No style on the clipboard."));
 
384
            return false;
 
385
        }
 
386
    }
 
387
 
 
388
    Inkscape::XML::Node
 
389
        *root = sp_document_repr_root(tempdoc),
 
390
        *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
 
391
 
 
392
    bool pasted = false;
 
393
 
 
394
    if (clipnode) {
 
395
        _pasteDefs(tempdoc);
 
396
        SPCSSAttr *style = sp_repr_css_attr(clipnode, "style");
 
397
        sp_desktop_set_style(desktop, style);
 
398
        pasted = true;
 
399
    }
 
400
    else {
 
401
        _userWarn(desktop, _("No style on the clipboard."));
 
402
    }
 
403
 
 
404
    sp_document_unref(tempdoc);
 
405
    return pasted;
 
406
}
 
407
 
 
408
 
 
409
/**
 
410
 * @brief Resize the selection or each object in the selection to match the clipboard's size
 
411
 * @param separately Whether to scale each object in the selection separately
 
412
 * @param apply_x Whether to scale the width of objects / selection
 
413
 * @param apply_y Whether to scale the height of objects / selection
 
414
 */
 
415
bool ClipboardManagerImpl::pasteSize(bool separately, bool apply_x, bool apply_y)
 
416
{
 
417
    if(!apply_x && !apply_y) return false; // pointless parameters
 
418
 
 
419
    SPDesktop *desktop = SP_ACTIVE_DESKTOP;
 
420
    if ( desktop == NULL ) return false;
 
421
    Inkscape::Selection *selection = sp_desktop_selection(desktop);
 
422
    if (selection->isEmpty()) {
 
423
        _userWarn(desktop, _("Select <b>object(s)</b> to paste size to."));
 
424
        return false;
 
425
    }
 
426
 
 
427
    // FIXME: actually, this should accept arbitrary documents
 
428
    SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
 
429
    if ( tempdoc == NULL ) {
 
430
        _userWarn(desktop, _("No size on the clipboard."));
 
431
        return false;
 
432
    }
 
433
 
 
434
    // retrieve size ifomration from the clipboard
 
435
    Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
 
436
    Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
 
437
    bool pasted = false;
 
438
    if (clipnode) {
 
439
        Geom::Point min, max;
 
440
        sp_repr_get_point(clipnode, "min", &min);
 
441
        sp_repr_get_point(clipnode, "max", &max);
 
442
 
 
443
        // resize each object in the selection
 
444
        if (separately) {
 
445
            for (GSList *i = const_cast<GSList*>(selection->itemList()) ; i ; i = i->next) {
 
446
                SPItem *item = SP_ITEM(i->data);
 
447
                Geom::OptRect obj_size = sp_item_bbox_desktop(item);
 
448
                if ( !obj_size ) continue;
 
449
                sp_item_scale_rel(item, _getScale(min, max, *obj_size, apply_x, apply_y));
 
450
            }
 
451
        }
 
452
        // resize the selection as a whole
 
453
        else {
 
454
            Geom::OptRect sel_size = selection->bounds();
 
455
            if ( sel_size ) {
 
456
                sp_selection_scale_relative(selection, sel_size->midpoint(),
 
457
                    _getScale(min, max, *sel_size, apply_x, apply_y));
 
458
            }
 
459
        }
 
460
        pasted = true;
 
461
    }
 
462
    sp_document_unref(tempdoc);
 
463
    return pasted;
 
464
}
 
465
 
 
466
 
 
467
/**
 
468
 * @brief Applies a path effect from the clipboard to the selected path
 
469
 */
 
470
bool ClipboardManagerImpl::pastePathEffect()
 
471
{
 
472
    /** @todo FIXME: pastePathEffect crashes when moving the path with the applied effect,
 
473
        segfaulting in fork_private_if_necessary(). */
 
474
 
 
475
    SPDesktop *desktop = SP_ACTIVE_DESKTOP;
 
476
    if ( desktop == NULL )
 
477
        return false;
 
478
 
 
479
    Inkscape::Selection *selection = sp_desktop_selection(desktop);
 
480
    if (selection && selection->isEmpty()) {
 
481
        _userWarn(desktop, _("Select <b>object(s)</b> to paste live path effect to."));
 
482
        return false;
 
483
    }
 
484
 
 
485
    SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
 
486
    if ( tempdoc ) {
 
487
        Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
 
488
        Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
 
489
        if ( clipnode ) {
 
490
            gchar const *effect = clipnode->attribute("inkscape:path-effect");
 
491
            if ( effect ) {
 
492
                _pasteDefs(tempdoc);
 
493
                // make sure all selected items are converted to paths first (i.e. rectangles)
 
494
                sp_selected_path_to_curves(desktop, false);
 
495
                for (GSList *item = const_cast<GSList *>(selection->itemList()) ; item ; item = item->next) {
 
496
                    _applyPathEffect(reinterpret_cast<SPItem*>(item->data), effect);
 
497
                }
 
498
 
 
499
                return true;
 
500
            }
 
501
        }
 
502
    }
 
503
 
 
504
    // no_effect:
 
505
    _userWarn(desktop, _("No effect on the clipboard."));
 
506
    return false;
 
507
}
 
508
 
 
509
 
 
510
/**
 
511
 * @brief Get LPE path data from the clipboard
 
512
 * @return The retrieved path data (contents of the d attribute), or "" if no path was found
 
513
 */
 
514
Glib::ustring ClipboardManagerImpl::getPathParameter()
 
515
{
 
516
    SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
 
517
    if ( tempdoc == NULL ) {
 
518
        _userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
 
519
        return "";
 
520
    }
 
521
    Inkscape::XML::Node
 
522
        *root = sp_document_repr_root(tempdoc),
 
523
        *path = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
 
524
    if ( path == NULL ) {
 
525
        _userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
 
526
        sp_document_unref(tempdoc);
 
527
        return "";
 
528
    }
 
529
    gchar const *svgd = path->attribute("d");
 
530
    return svgd;
 
531
}
 
532
 
 
533
 
 
534
/**
 
535
 * @brief Get object id of a shape or text item from the clipboard
 
536
 * @return The retrieved id string (contents of the id attribute), or "" if no shape or text item was found
 
537
 */
 
538
Glib::ustring ClipboardManagerImpl::getShapeOrTextObjectId()
 
539
{
 
540
    SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
 
541
    if ( tempdoc == NULL ) {
 
542
        _userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
 
543
        return "";
 
544
    }
 
545
    Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
 
546
 
 
547
    Inkscape::XML::Node *repr = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
 
548
    if ( repr == NULL )
 
549
        repr = sp_repr_lookup_name(root, "svg:text", -1);
 
550
 
 
551
    if ( repr == NULL ) {
 
552
        _userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
 
553
        sp_document_unref(tempdoc);
 
554
        return "";
 
555
    }
 
556
    gchar const *svgd = repr->attribute("id");
 
557
    return svgd;
 
558
}
 
559
 
 
560
 
 
561
/**
 
562
 * @brief Iterate over a list of items and copy them to the clipboard.
 
563
 */
 
564
void ClipboardManagerImpl::_copySelection(Inkscape::Selection *selection)
 
565
{
 
566
    GSList const *items = selection->itemList();
 
567
    // copy the defs used by all items
 
568
    for (GSList *i = const_cast<GSList *>(items) ; i != NULL ; i = i->next) {
 
569
        _copyUsedDefs(SP_ITEM (i->data));
 
570
    }
 
571
 
 
572
    // copy the representation of the items
 
573
    GSList *sorted_items = g_slist_copy(const_cast<GSList *>(items));
 
574
    sorted_items = g_slist_sort(sorted_items, (GCompareFunc) sp_object_compare_position);
 
575
 
 
576
    for (GSList *i = sorted_items ; i ; i = i->next) {
 
577
        if (!SP_IS_ITEM(i->data)) continue;
 
578
        Inkscape::XML::Node *obj = SP_OBJECT_REPR(i->data);
 
579
        Inkscape::XML::Node *obj_copy = _copyNode(obj, _doc, _root);
 
580
 
 
581
        // copy complete inherited style
 
582
        SPCSSAttr *css = sp_repr_css_attr_inherited(obj, "style");
 
583
        sp_repr_css_set(obj_copy, css, "style");
 
584
        sp_repr_css_attr_unref(css);
 
585
 
 
586
        // write the complete accumulated transform passed to us
 
587
        // (we're dealing with unattached representations, so we write to their attributes
 
588
        // instead of using sp_item_set_transform)
 
589
        gchar *transform_str = sp_svg_transform_write(sp_item_i2doc_affine(SP_ITEM(i->data)));
 
590
        obj_copy->setAttribute("transform", transform_str);
 
591
        g_free(transform_str);
 
592
    }
 
593
 
 
594
    // copy style for Paste Style action
 
595
    if (sorted_items) {
 
596
        if(SP_IS_ITEM(sorted_items->data)) {
 
597
            SPCSSAttr *style = take_style_from_item((SPItem *) sorted_items->data);
 
598
            sp_repr_css_set(_clipnode, style, "style");
 
599
            sp_repr_css_attr_unref(style);
 
600
        }
 
601
 
 
602
        // copy path effect from the first path
 
603
        if (SP_IS_OBJECT(sorted_items->data)) {
 
604
            gchar const *effect = SP_OBJECT_REPR(sorted_items->data)->attribute("inkscape:path-effect");
 
605
            if (effect) {
 
606
                _clipnode->setAttribute("inkscape:path-effect", effect);
 
607
            }
 
608
        }
 
609
    }
 
610
 
 
611
    Geom::OptRect size = selection->bounds();
 
612
    if (size) {
 
613
        sp_repr_set_point(_clipnode, "min", size->min());
 
614
        sp_repr_set_point(_clipnode, "max", size->max());
 
615
    }
 
616
 
 
617
    g_slist_free(sorted_items);
 
618
}
 
619
 
 
620
 
 
621
/**
 
622
 * @brief Recursively copy all the definitions used by a given item to the clipboard defs
 
623
 */
 
624
void ClipboardManagerImpl::_copyUsedDefs(SPItem *item)
 
625
{
 
626
    // copy fill and stroke styles (patterns and gradients)
 
627
    SPStyle *style = SP_OBJECT_STYLE(item);
 
628
 
 
629
    if (style && (style->fill.isPaintserver())) {
 
630
        SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
 
631
        if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
 
632
            _copyGradient(SP_GRADIENT(server));
 
633
        if (SP_IS_PATTERN(server))
 
634
            _copyPattern(SP_PATTERN(server));
 
635
    }
 
636
    if (style && (style->stroke.isPaintserver())) {
 
637
        SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
 
638
        if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
 
639
            _copyGradient(SP_GRADIENT(server));
 
640
        if (SP_IS_PATTERN(server))
 
641
            _copyPattern(SP_PATTERN(server));
 
642
    }
 
643
 
 
644
    // For shapes, copy all of the shape's markers
 
645
    if (SP_IS_SHAPE(item)) {
 
646
        SPShape *shape = SP_SHAPE (item);
 
647
        for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
 
648
            if (shape->marker[i]) {
 
649
                _copyNode(SP_OBJECT_REPR(SP_OBJECT(shape->marker[i])), _doc, _defs);
 
650
            }
 
651
        }
 
652
    }
 
653
    // For lpe items, copy lpe stack if applicable
 
654
    if (SP_IS_LPE_ITEM(item)) {
 
655
        SPLPEItem *lpeitem = SP_LPE_ITEM (item);
 
656
        if (sp_lpe_item_has_path_effect(lpeitem)) {
 
657
            for (PathEffectList::iterator it = lpeitem->path_effect_list->begin(); it != lpeitem->path_effect_list->end(); ++it)
 
658
            {
 
659
                LivePathEffectObject *lpeobj = (*it)->lpeobject;
 
660
                if (lpeobj)
 
661
                    _copyNode(SP_OBJECT_REPR(SP_OBJECT(lpeobj)), _doc, _defs);
 
662
            }
 
663
        }
 
664
    }
 
665
    // For 3D boxes, copy perspectives
 
666
    if (SP_IS_BOX3D(item)) {
 
667
        _copyNode(SP_OBJECT_REPR(SP_OBJECT(box3d_get_perspective(SP_BOX3D(item)))), _doc, _defs);
 
668
    }
 
669
    // Copy text paths
 
670
    if (SP_IS_TEXT_TEXTPATH(item)) {
 
671
        _copyTextPath(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
 
672
    }
 
673
    // Copy clipping objects
 
674
    if (item->clip_ref->getObject()) {
 
675
        _copyNode(SP_OBJECT_REPR(item->clip_ref->getObject()), _doc, _defs);
 
676
    }
 
677
    // Copy mask objects
 
678
    if (item->mask_ref->getObject()) {
 
679
        SPObject *mask = item->mask_ref->getObject();
 
680
        _copyNode(SP_OBJECT_REPR(mask), _doc, _defs);
 
681
        // recurse into the mask for its gradients etc.
 
682
        for (SPObject *o = SP_OBJECT(mask)->children ; o != NULL ; o = o->next) {
 
683
            if (SP_IS_ITEM(o))
 
684
                _copyUsedDefs(SP_ITEM(o));
 
685
        }
 
686
    }
 
687
    // Copy filters
 
688
    if (style->getFilter()) {
 
689
        SPObject *filter = style->getFilter();
 
690
        if (SP_IS_FILTER(filter)) {
 
691
            _copyNode(SP_OBJECT_REPR(filter), _doc, _defs);
 
692
        }
 
693
    }
 
694
 
 
695
    // recurse
 
696
    for (SPObject *o = SP_OBJECT(item)->children ; o != NULL ; o = o->next) {
 
697
        if (SP_IS_ITEM(o))
 
698
            _copyUsedDefs(SP_ITEM(o));
 
699
    }
 
700
}
 
701
 
 
702
 
 
703
/**
 
704
 * @brief Copy a single gradient to the clipboard's defs element
 
705
 */
 
706
void ClipboardManagerImpl::_copyGradient(SPGradient *gradient)
 
707
{
 
708
    while (gradient) {
 
709
        // climb up the refs, copying each one in the chain
 
710
        _copyNode(SP_OBJECT_REPR(gradient), _doc, _defs);
 
711
        gradient = gradient->ref->getObject();
 
712
    }
 
713
}
 
714
 
 
715
 
 
716
/**
 
717
 * @brief Copy a single pattern to the clipboard document's defs element
 
718
 */
 
719
void ClipboardManagerImpl::_copyPattern(SPPattern *pattern)
 
720
{
 
721
    // climb up the references, copying each one in the chain
 
722
    while (pattern) {
 
723
        _copyNode(SP_OBJECT_REPR(pattern), _doc, _defs);
 
724
 
 
725
        // items in the pattern may also use gradients and other patterns, so recurse
 
726
        for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL ; child = SP_OBJECT_NEXT(child) ) {
 
727
            if (!SP_IS_ITEM (child)) continue;
 
728
            _copyUsedDefs(SP_ITEM(child));
 
729
        }
 
730
        pattern = pattern->ref->getObject();
 
731
    }
 
732
}
 
733
 
 
734
 
 
735
/**
 
736
 * @brief Copy a text path to the clipboard's defs element
 
737
 */
 
738
void ClipboardManagerImpl::_copyTextPath(SPTextPath *tp)
 
739
{
 
740
    SPItem *path = sp_textpath_get_path_item(tp);
 
741
    if(!path) return;
 
742
    Inkscape::XML::Node *path_node = SP_OBJECT_REPR(path);
 
743
 
 
744
    // Do not copy the text path to defs if it's already copied
 
745
    if(sp_repr_lookup_child(_root, "id", path_node->attribute("id"))) return;
 
746
    _copyNode(path_node, _doc, _defs);
 
747
}
 
748
 
 
749
 
 
750
/**
 
751
 * @brief Copy a single XML node from one document to another
 
752
 * @param node The node to be copied
 
753
 * @param target_doc The document to which the node is to be copied
 
754
 * @param parent The node in the target document which will become the parent of the copied node
 
755
 * @return Pointer to the copied node
 
756
 */
 
757
Inkscape::XML::Node *ClipboardManagerImpl::_copyNode(Inkscape::XML::Node *node, Inkscape::XML::Document *target_doc, Inkscape::XML::Node *parent)
 
758
{
 
759
    Inkscape::XML::Node *dup = node->duplicate(target_doc);
 
760
    parent->appendChild(dup);
 
761
    Inkscape::GC::release(dup);
 
762
    return dup;
 
763
}
 
764
 
 
765
 
 
766
/**
 
767
 * @brief Paste the contents of a document into the active desktop
 
768
 * @param clipdoc The document to paste
 
769
 * @param in_place Whether to paste the selection where it was when copied
 
770
 * @pre @c clipdoc is not empty and items can be added to the current layer
 
771
 */
 
772
void ClipboardManagerImpl::_pasteDocument(SPDocument *clipdoc, bool in_place)
 
773
{
 
774
    SPDesktop *desktop = SP_ACTIVE_DESKTOP;
 
775
    SPDocument *target_document = sp_desktop_document(desktop);
 
776
    Inkscape::XML::Node
 
777
        *root = sp_document_repr_root(clipdoc),
 
778
        *target_parent = SP_OBJECT_REPR(desktop->currentLayer());
 
779
    Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
 
780
 
 
781
    // copy definitions
 
782
    _pasteDefs(clipdoc);
 
783
 
 
784
    // copy objects
 
785
    GSList *pasted_objects = NULL;
 
786
    for (Inkscape::XML::Node *obj = root->firstChild() ; obj ; obj = obj->next()) {
 
787
        // Don't copy metadata, defs, named views and internal clipboard contents to the document
 
788
        if (!strcmp(obj->name(), "svg:defs")) continue;
 
789
        if (!strcmp(obj->name(), "svg:metadata")) continue;
 
790
        if (!strcmp(obj->name(), "sodipodi:namedview")) continue;
 
791
        if (!strcmp(obj->name(), "inkscape:clipboard")) continue;
 
792
        Inkscape::XML::Node *obj_copy = _copyNode(obj, target_xmldoc, target_parent);
 
793
        pasted_objects = g_slist_prepend(pasted_objects, (gpointer) obj_copy);
 
794
    }
 
795
 
 
796
    // Change the selection to the freshly pasted objects
 
797
    Inkscape::Selection *selection = sp_desktop_selection(desktop);
 
798
    selection->setReprList(pasted_objects);
 
799
 
 
800
    // invers apply parent transform
 
801
    Geom::Matrix doc2parent = sp_item_i2doc_affine(SP_ITEM(desktop->currentLayer())).inverse();
 
802
    sp_selection_apply_affine(selection, desktop->dt2doc() * doc2parent * desktop->doc2dt(), true, false);
 
803
 
 
804
    // Update (among other things) all curves in paths, for bounds() to work
 
805
    sp_document_ensure_up_to_date(target_document);
 
806
 
 
807
    // move selection either to original position (in_place) or to mouse pointer
 
808
    Geom::OptRect sel_bbox = selection->bounds();
 
809
    if (sel_bbox) {
 
810
        // get offset of selection to original position of copied elements
 
811
        Geom::Point pos_original;
 
812
        Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
 
813
        if (clipnode) {
 
814
            Geom::Point min, max;
 
815
            sp_repr_get_point(clipnode, "min", &min);
 
816
            sp_repr_get_point(clipnode, "max", &max);
 
817
            pos_original = Geom::Point(min[Geom::X], max[Geom::Y]);
 
818
        }
 
819
        Geom::Point offset = pos_original - sel_bbox->corner(3);
 
820
 
 
821
        if (!in_place) {
 
822
            SnapManager &m = desktop->namedview->snap_manager;
 
823
            m.setup(desktop, false); // Don't display the snapindicator
 
824
 
 
825
            // get offset from mouse pointer to bbox center, snap to grid if enabled
 
826
            Geom::Point mouse_offset = desktop->point() - sel_bbox->midpoint();
 
827
            offset = m.multipleOfGridPitch(mouse_offset - offset) + offset;
 
828
        }
 
829
 
 
830
        sp_selection_move_relative(selection, offset);
 
831
    }
 
832
 
 
833
    g_slist_free(pasted_objects);
 
834
}
 
835
 
 
836
 
 
837
/**
 
838
 * @brief Paste SVG defs from the document retrieved from the clipboard into the active document
 
839
 * @param clipdoc The document to paste
 
840
 * @pre @c clipdoc != NULL and pasting into the active document is possible
 
841
 */
 
842
void ClipboardManagerImpl::_pasteDefs(SPDocument *clipdoc)
 
843
{
 
844
    // boilerplate vars copied from _pasteDocument
 
845
    SPDesktop *desktop = SP_ACTIVE_DESKTOP;
 
846
    SPDocument *target_document = sp_desktop_document(desktop);
 
847
    Inkscape::XML::Node
 
848
        *root = sp_document_repr_root(clipdoc),
 
849
        *defs = sp_repr_lookup_name(root, "svg:defs", 1),
 
850
        *target_defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(target_document));
 
851
    Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
 
852
 
 
853
    prevent_id_clashes(clipdoc, target_document);
 
854
 
 
855
    for (Inkscape::XML::Node *def = defs->firstChild() ; def ; def = def->next()) {
 
856
        _copyNode(def, target_xmldoc, target_defs);
 
857
    }
 
858
}
 
859
 
 
860
 
 
861
/**
 
862
 * @brief Retrieve a bitmap image from the clipboard and paste it into the active document
 
863
 */
 
864
bool ClipboardManagerImpl::_pasteImage()
 
865
{
 
866
    SPDocument *doc = SP_ACTIVE_DOCUMENT;
 
867
    if ( doc == NULL ) return false;
 
868
 
 
869
    // retrieve image data
 
870
    Glib::RefPtr<Gdk::Pixbuf> img = _clipboard->wait_for_image();
 
871
    if (!img) return false;
 
872
 
 
873
    // Very stupid hack: Write into a file, then import the file into the document.
 
874
    // To avoid using tmpfile and POSIX file handles, make the filename based on current time.
 
875
    // This wasn't my idea, I just copied this from selection-chemistry.cpp
 
876
    // and just can't think of something saner at the moment. Pasting more than
 
877
    // one image per second will overwrite the image.
 
878
    // However, I don't think anyone is able to copy a _different_ image into inkscape
 
879
    // in 1 second.
 
880
    time_t rawtime;
 
881
    char image_filename[128];
 
882
 
 
883
    time(&rawtime);
 
884
    strftime(image_filename, 128, "inkscape_pasted_image_%Y%m%d_%H%M%S.png", localtime( &rawtime ));
 
885
    /// @todo Check whether the encoding is correct here
 
886
    Inkscape::Preferences *prefs = Inkscape::Preferences::get();
 
887
    std::string save_folder = Glib::filename_from_utf8(prefs->getString("/dialogs/save_as/path"));
 
888
 
 
889
    gchar *image_path = g_build_filename(save_folder.data(), image_filename, NULL);
 
890
    img->save(image_path, "png");
 
891
    file_import(doc, image_path, NULL);
 
892
    g_free(image_path);
 
893
 
 
894
    return true;
 
895
}
 
896
 
 
897
/**
 
898
 * @brief Paste text into the selected text object or create a new one to hold it
 
899
 */
 
900
bool ClipboardManagerImpl::_pasteText()
 
901
{
 
902
    SPDesktop *desktop = SP_ACTIVE_DESKTOP;
 
903
    if ( desktop == NULL ) return false;
 
904
 
 
905
    // if the text editing tool is active, paste the text into the active text object
 
906
    if (tools_isactive(desktop, TOOLS_TEXT))
 
907
        return sp_text_paste_inline(desktop->event_context);
 
908
 
 
909
    // try to parse the text as a color and, if successful, apply it as the current style
 
910
    SPCSSAttr *css = _parseColor(_clipboard->wait_for_text());
 
911
    if (css) {
 
912
        sp_desktop_set_style(desktop, css);
 
913
        return true;
 
914
    }
 
915
 
 
916
    return false;
 
917
}
 
918
 
 
919
 
 
920
/**
 
921
 * @brief Attempt to parse the passed string as a hexadecimal RGB or RGBA color
 
922
 * @param text The Glib::ustring to parse
 
923
 * @return New CSS style representation if the parsing was successful, NULL otherwise
 
924
 */
 
925
SPCSSAttr *ClipboardManagerImpl::_parseColor(const Glib::ustring &text)
 
926
{
 
927
// TODO reuse existing code instead of replicating here.
 
928
    Glib::ustring::size_type len = text.bytes();
 
929
    char *str = const_cast<char *>(text.data());
 
930
    bool attempt_alpha = false;
 
931
    if ( !str || ( *str == '\0' ) ) return NULL; // this is OK due to boolean short-circuit
 
932
 
 
933
    // those conditionals guard against parsing e.g. the string "fab" as "fab000"
 
934
    // (incomplete color) and "45fab71" as "45fab710" (incomplete alpha)
 
935
    if ( *str == '#' ) {
 
936
        if ( len < 7 ) return NULL;
 
937
        if ( len >= 9 ) attempt_alpha = true;
 
938
    } else {
 
939
        if ( len < 6 ) return NULL;
 
940
        if ( len >= 8 ) attempt_alpha = true;
 
941
    }
 
942
 
 
943
    unsigned int color = 0, alpha = 0xff;
 
944
 
 
945
    // skip a leading #, if present
 
946
    if ( *str == '#' ) ++str;
 
947
 
 
948
    // try to parse first 6 digits
 
949
    int res = sscanf(str, "%6x", &color);
 
950
    if ( res && ( res != EOF ) ) {
 
951
        if (attempt_alpha) {// try to parse alpha if there's enough characters
 
952
            sscanf(str + 6, "%2x", &alpha);
 
953
            if ( !res || res == EOF ) alpha = 0xff;
 
954
        }
 
955
 
 
956
        SPCSSAttr *color_css = sp_repr_css_attr_new();
 
957
 
 
958
        // print and set properties
 
959
        gchar color_str[16];
 
960
        g_snprintf(color_str, 16, "#%06x", color);
 
961
        sp_repr_css_set_property(color_css, "fill", color_str);
 
962
 
 
963
        float opacity = static_cast<float>(alpha)/static_cast<float>(0xff);
 
964
        if (opacity > 1.0) opacity = 1.0; // safeguard
 
965
        Inkscape::CSSOStringStream opcss;
 
966
        opcss << opacity;
 
967
        sp_repr_css_set_property(color_css, "fill-opacity", opcss.str().data());
 
968
        return color_css;
 
969
    }
 
970
    return NULL;
 
971
}
 
972
 
 
973
 
 
974
/**
 
975
 * @brief Applies a pasted path effect to a given item
 
976
 */
 
977
void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effect)
 
978
{
 
979
    if ( item == NULL ) return;
 
980
    if ( SP_IS_RECT(item) ) return;
 
981
 
 
982
    if (SP_IS_LPE_ITEM(item))
 
983
    {
 
984
        SPLPEItem *lpeitem = SP_LPE_ITEM(item);
 
985
        SPObject *obj = sp_uri_reference_resolve(_clipboardSPDoc, effect);
 
986
        if (!obj) return;
 
987
        // if the effect is not used by anyone, we might as well take it
 
988
        LivePathEffectObject *lpeobj = LIVEPATHEFFECT(obj)->fork_private_if_necessary(1);
 
989
        sp_lpe_item_add_path_effect(lpeitem, lpeobj);
 
990
    }
 
991
}
 
992
 
 
993
 
 
994
/**
 
995
 * @brief Retrieve the clipboard contents as a document
 
996
 * @return Clipboard contents converted to SPDocument, or NULL if no suitable content was present
 
997
 */
 
998
SPDocument *ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_target)
 
999
{
 
1000
    Glib::ustring best_target;
 
1001
    if ( required_target == "" )
 
1002
        best_target = _getBestTarget();
 
1003
    else
 
1004
        best_target = required_target;
 
1005
 
 
1006
    if ( best_target == "" ) {
 
1007
        return NULL;
 
1008
    }
 
1009
 
 
1010
    // FIXME: Temporary hack until we add memory input.
 
1011
    // Save the clipboard contents to some file, then read it
 
1012
    gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-import", NULL );
 
1013
 
 
1014
    bool file_saved = false;
 
1015
    Glib::ustring target = best_target;
 
1016
 
 
1017
#ifdef WIN32
 
1018
    if (best_target == CLIPBOARD_WIN32_EMF_TARGET)
 
1019
    {   // Try to save clipboard data as en emf file (using win32 api)
 
1020
        if (OpenClipboard(NULL)) {
 
1021
            HGLOBAL hglb = GetClipboardData(CF_ENHMETAFILE);
 
1022
            if (hglb) {
 
1023
                HENHMETAFILE hemf = CopyEnhMetaFile((HENHMETAFILE) hglb, filename);
 
1024
                if (hemf) {
 
1025
                    file_saved = true;
 
1026
                    target = CLIPBOARD_WIN32_EMF_MIME;
 
1027
                    DeleteEnhMetaFile(hemf);
 
1028
                }
 
1029
            }
 
1030
            CloseClipboard();
 
1031
        }
 
1032
    }
 
1033
#endif
 
1034
 
 
1035
    if (!file_saved) {
 
1036
        if ( !_clipboard->wait_is_target_available(best_target) ) {
 
1037
            return NULL;
 
1038
        }
 
1039
 
 
1040
        // doing this synchronously makes better sense
 
1041
        // TODO: use another method because this one is badly broken imo.
 
1042
        // from documentation: "Returns: A SelectionData object, which will be invalid if retrieving the given target failed."
 
1043
        // I don't know how to check whether an object is 'valid' or not, unusable if that's not possible...
 
1044
        Gtk::SelectionData sel = _clipboard->wait_for_contents(best_target);
 
1045
        target = sel.get_target();  // this can crash if the result was invalid of last function. No way to check for this :(
 
1046
 
 
1047
        // FIXME: Temporary hack until we add memory input.
 
1048
        // Save the clipboard contents to some file, then read it
 
1049
        g_file_set_contents(filename, (const gchar *) sel.get_data(), sel.get_length(), NULL);
 
1050
    }
 
1051
 
 
1052
    // there is no specific plain SVG input extension, so if we can paste the Inkscape SVG format,
 
1053
    // we use the image/svg+xml mimetype to look up the input extension
 
1054
    if(target == "image/x-inkscape-svg")
 
1055
        target = "image/svg+xml";
 
1056
 
 
1057
    Inkscape::Extension::DB::InputList inlist;
 
1058
    Inkscape::Extension::db.get_input_list(inlist);
 
1059
    Inkscape::Extension::DB::InputList::const_iterator in = inlist.begin();
 
1060
    for (; in != inlist.end() && target != (*in)->get_mimetype() ; ++in){};
 
1061
    if ( in == inlist.end() )
 
1062
        return NULL; // this shouldn't happen unless _getBestTarget returns something bogus
 
1063
 
 
1064
    SPDocument *tempdoc = NULL;
 
1065
    try {
 
1066
        tempdoc = (*in)->open(filename);
 
1067
    } catch (...) {
 
1068
    }
 
1069
    g_unlink(filename);
 
1070
    g_free(filename);
 
1071
 
 
1072
    return tempdoc;
 
1073
}
 
1074
 
 
1075
 
 
1076
/**
 
1077
 * @brief Callback called when some other application requests data from Inkscape
 
1078
 *
 
1079
 * Finds a suitable output extension to save the internal clipboard document,
 
1080
 * then saves it to memory and sets the clipboard contents.
 
1081
 */
 
1082
void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint /*info*/)
 
1083
{
 
1084
    g_assert( _clipboardSPDoc != NULL );
 
1085
 
 
1086
    Glib::ustring target = sel.get_target();
 
1087
    if(target == "") return; // this shouldn't happen
 
1088
 
 
1089
    if (target == CLIPBOARD_TEXT_TARGET) {
 
1090
        target = "image/x-inkscape-svg";
 
1091
    }
 
1092
 
 
1093
    Inkscape::Extension::DB::OutputList outlist;
 
1094
    Inkscape::Extension::db.get_output_list(outlist);
 
1095
    Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
 
1096
    for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out){};
 
1097
    if ( out == outlist.end() && target != "image/png") return; // this also shouldn't happen
 
1098
 
 
1099
    // FIXME: Temporary hack until we add support for memory output.
 
1100
    // Save to a temporary file, read it back and then set the clipboard contents
 
1101
    gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export", NULL );
 
1102
    gsize len; gchar *data;
 
1103
 
 
1104
    try {
 
1105
        if (out == outlist.end() && target == "image/png")
 
1106
        {
 
1107
            gdouble dpi = PX_PER_IN;
 
1108
            guint32 bgcolor = 0x00000000;
 
1109
 
 
1110
            Geom::Point origin (SP_ROOT(_clipboardSPDoc->root)->x.computed, SP_ROOT(_clipboardSPDoc->root)->y.computed);
 
1111
            Geom::Rect area = Geom::Rect(origin, origin + sp_document_dimensions(_clipboardSPDoc));
 
1112
 
 
1113
            unsigned long int width = (unsigned long int) (area.width() * dpi / PX_PER_IN + 0.5);
 
1114
            unsigned long int height = (unsigned long int) (area.height() * dpi / PX_PER_IN + 0.5);
 
1115
 
 
1116
            // read from namedview
 
1117
            Inkscape::XML::Node *nv = sp_repr_lookup_name (_clipboardSPDoc->rroot, "sodipodi:namedview");
 
1118
            if (nv && nv->attribute("pagecolor"))
 
1119
                bgcolor = sp_svg_read_color(nv->attribute("pagecolor"), 0xffffff00);
 
1120
            if (nv && nv->attribute("inkscape:pageopacity"))
 
1121
                bgcolor |= SP_COLOR_F_TO_U(sp_repr_get_double_attribute (nv, "inkscape:pageopacity", 1.0));
 
1122
 
 
1123
            sp_export_png_file(_clipboardSPDoc, filename, area, width, height, dpi, dpi, bgcolor, NULL, NULL, true, NULL);
 
1124
        }
 
1125
        else
 
1126
        {
 
1127
            if (!(*out)->loaded()) {
 
1128
                // Need to load the extension.
 
1129
                (*out)->set_state(Inkscape::Extension::Extension::STATE_LOADED);
 
1130
            }
 
1131
            (*out)->save(_clipboardSPDoc, filename);
 
1132
        }
 
1133
        g_file_get_contents(filename, &data, &len, NULL);
 
1134
 
 
1135
        sel.set(8, (guint8 const *) data, len);
 
1136
    } catch (...) {
 
1137
    }
 
1138
 
 
1139
    g_unlink(filename); // delete the temporary file
 
1140
    g_free(filename);
 
1141
}
 
1142
 
 
1143
 
 
1144
/**
 
1145
 * @brief Callback when someone else takes the clipboard
 
1146
 *
 
1147
 * When the clipboard owner changes, this callback clears the internal clipboard document
 
1148
 * to reduce memory usage.
 
1149
 */
 
1150
void ClipboardManagerImpl::_onClear()
 
1151
{
 
1152
    // why is this called before _onGet???
 
1153
    //_discardInternalClipboard();
 
1154
}
 
1155
 
 
1156
 
 
1157
/**
 
1158
 * @brief Creates an internal clipboard document from scratch
 
1159
 */
 
1160
void ClipboardManagerImpl::_createInternalClipboard()
 
1161
{
 
1162
    if ( _clipboardSPDoc == NULL ) {
 
1163
        _clipboardSPDoc = sp_document_new(NULL, false, true);
 
1164
        //g_assert( _clipboardSPDoc != NULL );
 
1165
        _defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(_clipboardSPDoc));
 
1166
        _doc = sp_document_repr_doc(_clipboardSPDoc);
 
1167
        _root = sp_document_repr_root(_clipboardSPDoc);
 
1168
 
 
1169
        _clipnode = _doc->createElement("inkscape:clipboard");
 
1170
        _root->appendChild(_clipnode);
 
1171
        Inkscape::GC::release(_clipnode);
 
1172
 
 
1173
        // once we create a SVG document, style will be stored in it, so flush _text_style
 
1174
        if (_text_style) {
 
1175
            sp_repr_css_attr_unref(_text_style);
 
1176
            _text_style = NULL;
 
1177
        }
 
1178
    }
 
1179
}
 
1180
 
 
1181
 
 
1182
/**
 
1183
 * @brief Deletes the internal clipboard document
 
1184
 */
 
1185
void ClipboardManagerImpl::_discardInternalClipboard()
 
1186
{
 
1187
    if ( _clipboardSPDoc != NULL ) {
 
1188
        sp_document_unref(_clipboardSPDoc);
 
1189
        _clipboardSPDoc = NULL;
 
1190
        _defs = NULL;
 
1191
        _doc = NULL;
 
1192
        _root = NULL;
 
1193
        _clipnode = NULL;
 
1194
    }
 
1195
}
 
1196
 
 
1197
 
 
1198
/**
 
1199
 * @brief Get the scale to resize an item, based on the command and desktop state
 
1200
 */
 
1201
Geom::Scale ClipboardManagerImpl::_getScale(Geom::Point const &min, Geom::Point const &max, Geom::Rect const &obj_rect, bool apply_x, bool apply_y)
 
1202
{
 
1203
    SPDesktop *desktop = SP_ACTIVE_DESKTOP;
 
1204
    double scale_x = 1.0;
 
1205
    double scale_y = 1.0;
 
1206
 
 
1207
    if (apply_x) {
 
1208
        scale_x = (max[Geom::X] - min[Geom::X]) / obj_rect[Geom::X].extent();
 
1209
    }
 
1210
    if (apply_y) {
 
1211
        scale_y = (max[Geom::Y] - min[Geom::Y]) / obj_rect[Geom::Y].extent();
 
1212
    }
 
1213
    // If the "lock aspect ratio" button is pressed and we paste only a single coordinate,
 
1214
    // resize the second one by the same ratio too
 
1215
    if (desktop->isToolboxButtonActive("lock")) {
 
1216
        if (apply_x && !apply_y) scale_y = scale_x;
 
1217
        if (apply_y && !apply_x) scale_x = scale_y;
 
1218
    }
 
1219
 
 
1220
    return Geom::Scale(scale_x, scale_y);
 
1221
}
 
1222
 
 
1223
 
 
1224
/**
 
1225
 * @brief Find the most suitable clipboard target
 
1226
 */
 
1227
Glib::ustring ClipboardManagerImpl::_getBestTarget()
 
1228
{
 
1229
    std::list<Glib::ustring> targets = _clipboard->wait_for_targets();
 
1230
 
 
1231
    // clipboard target debugging snippet
 
1232
    /*
 
1233
    g_debug("Begin clipboard targets");
 
1234
    for ( std::list<Glib::ustring>::iterator x = targets.begin() ; x != targets.end(); ++x )
 
1235
        g_debug("Clipboard target: %s", (*x).data());
 
1236
    g_debug("End clipboard targets\n");
 
1237
    //*/
 
1238
 
 
1239
    for(std::list<Glib::ustring>::iterator i = _preferred_targets.begin() ;
 
1240
        i != _preferred_targets.end() ; ++i)
 
1241
    {
 
1242
        if ( std::find(targets.begin(), targets.end(), *i) != targets.end() )
 
1243
            return *i;
 
1244
    }
 
1245
#ifdef WIN32
 
1246
    if (OpenClipboard(NULL))
 
1247
    {   // If both bitmap and metafile are present, pick the one that was exported first.
 
1248
        UINT format = EnumClipboardFormats(0);
 
1249
        while (format) {
 
1250
            if (format == CF_ENHMETAFILE || format == CF_DIB || format == CF_BITMAP)
 
1251
                break;
 
1252
            format = EnumClipboardFormats(format);
 
1253
        }
 
1254
        CloseClipboard();
 
1255
 
 
1256
        if (format == CF_ENHMETAFILE)
 
1257
            return CLIPBOARD_WIN32_EMF_TARGET;
 
1258
        if (format == CF_DIB || format == CF_BITMAP)
 
1259
            return CLIPBOARD_GDK_PIXBUF_TARGET;
 
1260
    }
 
1261
 
 
1262
    if (IsClipboardFormatAvailable(CF_ENHMETAFILE))
 
1263
        return CLIPBOARD_WIN32_EMF_TARGET;
 
1264
#endif
 
1265
    if (_clipboard->wait_is_image_available())
 
1266
        return CLIPBOARD_GDK_PIXBUF_TARGET;
 
1267
    if (_clipboard->wait_is_text_available())
 
1268
        return CLIPBOARD_TEXT_TARGET;
 
1269
 
 
1270
    return "";
 
1271
}
 
1272
 
 
1273
 
 
1274
/**
 
1275
 * @brief Set the clipboard targets to reflect the mimetypes Inkscape can output
 
1276
 */
 
1277
void ClipboardManagerImpl::_setClipboardTargets()
 
1278
{
 
1279
    Inkscape::Extension::DB::OutputList outlist;
 
1280
    Inkscape::Extension::db.get_output_list(outlist);
 
1281
    std::list<Gtk::TargetEntry> target_list;
 
1282
    bool plaintextSet = false;
 
1283
    for (Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin() ; out != outlist.end() ; ++out) {
 
1284
        if ( !(*out)->deactivated() ) {
 
1285
            Glib::ustring mime = (*out)->get_mimetype();
 
1286
            if (mime != CLIPBOARD_TEXT_TARGET) {
 
1287
                if ( !plaintextSet && (mime.find("svg") == Glib::ustring::npos) ) {
 
1288
                    target_list.push_back(Gtk::TargetEntry(CLIPBOARD_TEXT_TARGET));
 
1289
                    plaintextSet = true;
 
1290
                }
 
1291
                target_list.push_back(Gtk::TargetEntry(mime));
 
1292
            }
 
1293
        }
 
1294
    }
 
1295
 
 
1296
    // Add PNG export explicitly since there is no extension for this...
 
1297
    // On Windows, GTK will also present this as a CF_DIB/CF_BITMAP
 
1298
    target_list.push_back(Gtk::TargetEntry( "image/png" ));
 
1299
 
 
1300
    _clipboard->set(target_list,
 
1301
        sigc::mem_fun(*this, &ClipboardManagerImpl::_onGet),
 
1302
        sigc::mem_fun(*this, &ClipboardManagerImpl::_onClear));
 
1303
 
 
1304
#ifdef WIN32
 
1305
    // If the "image/x-emf" target handled by the emf extension would be
 
1306
    // presented as a CF_ENHMETAFILE automatically (just like an "image/bmp"
 
1307
    // is presented as a CF_BITMAP) this code would not be needed.. ???
 
1308
    // Or maybe there is some other way to achieve the same?
 
1309
 
 
1310
    // Note: Metafile is the only format that is rendered and stored in clipboard
 
1311
    // on Copy, all other formats are rendered only when needed by a Paste command.
 
1312
 
 
1313
    // FIXME: This should at least be rewritten to use "delayed rendering".
 
1314
    //        If possible make it delayed rendering by using GTK API only.
 
1315
 
 
1316
    if (OpenClipboard(NULL)) {
 
1317
        if ( _clipboardSPDoc != NULL ) {
 
1318
            const Glib::ustring target = CLIPBOARD_WIN32_EMF_MIME;
 
1319
 
 
1320
            Inkscape::Extension::DB::OutputList outlist;
 
1321
            Inkscape::Extension::db.get_output_list(outlist);
 
1322
            Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
 
1323
            for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out);
 
1324
            if ( out != outlist.end() ) {
 
1325
                // FIXME: Temporary hack until we add support for memory output.
 
1326
                // Save to a temporary file, read it back and then set the clipboard contents
 
1327
                gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export.emf", NULL );
 
1328
 
 
1329
                try {
 
1330
                    (*out)->save(_clipboardSPDoc, filename);
 
1331
                    HENHMETAFILE hemf = GetEnhMetaFileA(filename);
 
1332
                    if (hemf) {
 
1333
                        SetClipboardData(CF_ENHMETAFILE, hemf);
 
1334
                        DeleteEnhMetaFile(hemf);
 
1335
                    }
 
1336
                } catch (...) {
 
1337
                }
 
1338
                g_unlink(filename); // delete the temporary file
 
1339
                g_free(filename);
 
1340
            }
 
1341
        }
 
1342
        CloseClipboard();
 
1343
    }
 
1344
#endif
 
1345
}
 
1346
 
 
1347
 
 
1348
/**
 
1349
 * @brief Set the string representation of a 32-bit RGBA color as the clipboard contents
 
1350
 */
 
1351
void ClipboardManagerImpl::_setClipboardColor(guint32 color)
 
1352
{
 
1353
    gchar colorstr[16];
 
1354
    g_snprintf(colorstr, 16, "%08x", color);
 
1355
    _clipboard->set_text(colorstr);
 
1356
}
 
1357
 
 
1358
 
 
1359
/**
 
1360
 * @brief Put a notification on the mesage stack
 
1361
 */
 
1362
void ClipboardManagerImpl::_userWarn(SPDesktop *desktop, char const *msg)
 
1363
{
 
1364
    desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, msg);
 
1365
}
 
1366
 
 
1367
 
 
1368
 
 
1369
/* #######################################
 
1370
          ClipboardManager class
 
1371
   ####################################### */
 
1372
 
 
1373
ClipboardManager *ClipboardManager::_instance = NULL;
 
1374
 
 
1375
ClipboardManager::ClipboardManager() {}
 
1376
ClipboardManager::~ClipboardManager() {}
 
1377
ClipboardManager *ClipboardManager::get()
 
1378
{
 
1379
    if ( _instance == NULL )
 
1380
        _instance = new ClipboardManagerImpl;
 
1381
    return _instance;
 
1382
}
 
1383
 
 
1384
} // namespace Inkscape
 
1385
} // namespace IO
 
1386
 
 
1387
/*
 
1388
  Local Variables:
 
1389
  mode:c++
 
1390
  c-file-style:"stroustrup"
 
1391
  c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
 
1392
  indent-tabs-mode:nil
 
1393
  fill-column:99
 
1394
  End:
 
1395
*/
 
1396
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :