Code

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