Code

A simple layout document as to what, why and how is cppification.
[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     tempdoc->doUnref();
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     tempdoc->doUnref();
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 = item->getBboxDesktop();
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     tempdoc->doUnref();
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         tempdoc->doUnref();
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         tempdoc->doUnref();
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(i->data)->i2doc_affine());
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(item)->first_child()));
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(pattern)->first_child() ; 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(desktop->currentLayer())->i2doc_affine().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     target_document->ensure_up_to_date();
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         sp_lpe_item_fork_path_effects_if_necessary(lpeitem, 1);
1062         std::istringstream iss(effectstack);
1063         std::string href;
1064         while (std::getline(iss, href, ';'))
1065         {
1066             SPObject *obj = sp_uri_reference_resolve(_clipboardSPDoc, href.c_str());
1067             if (!obj) {
1068                 return;
1069             }
1070             LivePathEffectObject *lpeobj = LIVEPATHEFFECT(obj);
1071             sp_lpe_item_add_path_effect(lpeitem, lpeobj);
1072         }
1073     }
1077 /**
1078  * @brief Retrieve the clipboard contents as a document
1079  * @return Clipboard contents converted to SPDocument, or NULL if no suitable content was present
1080  */
1081 SPDocument *ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_target)
1083     Glib::ustring best_target;
1084     if ( required_target == "" ) {
1085         best_target = _getBestTarget();
1086     } else {
1087         best_target = required_target;
1088     }
1090     if ( best_target == "" ) {
1091         return NULL;
1092     }
1094     // FIXME: Temporary hack until we add memory input.
1095     // Save the clipboard contents to some file, then read it
1096     gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-import", NULL );
1098     bool file_saved = false;
1099     Glib::ustring target = best_target;
1101 #ifdef WIN32
1102     if (best_target == CLIPBOARD_WIN32_EMF_TARGET)
1103     {   // Try to save clipboard data as en emf file (using win32 api)
1104         if (OpenClipboard(NULL)) {
1105             HGLOBAL hglb = GetClipboardData(CF_ENHMETAFILE);
1106             if (hglb) {
1107                 HENHMETAFILE hemf = CopyEnhMetaFile((HENHMETAFILE) hglb, filename);
1108                 if (hemf) {
1109                     file_saved = true;
1110                     target = CLIPBOARD_WIN32_EMF_MIME;
1111                     DeleteEnhMetaFile(hemf);
1112                 }
1113             }
1114             CloseClipboard();
1115         }
1116     }
1117 #endif
1119     if (!file_saved) {
1120         if ( !_clipboard->wait_is_target_available(best_target) ) {
1121             return NULL;
1122         }
1124         // doing this synchronously makes better sense
1125         // TODO: use another method because this one is badly broken imo.
1126         // from documentation: "Returns: A SelectionData object, which will be invalid if retrieving the given target failed."
1127         // I don't know how to check whether an object is 'valid' or not, unusable if that's not possible...
1128         Gtk::SelectionData sel = _clipboard->wait_for_contents(best_target);
1129         target = sel.get_target();  // this can crash if the result was invalid of last function. No way to check for this :(
1131         // FIXME: Temporary hack until we add memory input.
1132         // Save the clipboard contents to some file, then read it
1133         g_file_set_contents(filename, (const gchar *) sel.get_data(), sel.get_length(), NULL);
1134     }
1136     // there is no specific plain SVG input extension, so if we can paste the Inkscape SVG format,
1137     // we use the image/svg+xml mimetype to look up the input extension
1138     if (target == "image/x-inkscape-svg") {
1139         target = "image/svg+xml";
1140     }
1142     Inkscape::Extension::DB::InputList inlist;
1143     Inkscape::Extension::db.get_input_list(inlist);
1144     Inkscape::Extension::DB::InputList::const_iterator in = inlist.begin();
1145     for (; in != inlist.end() && target != (*in)->get_mimetype() ; ++in) {
1146     };
1147     if ( in == inlist.end() ) {
1148         return NULL; // this shouldn't happen unless _getBestTarget returns something bogus
1149     }
1151     SPDocument *tempdoc = NULL;
1152     try {
1153         tempdoc = (*in)->open(filename);
1154     } catch (...) {
1155     }
1156     g_unlink(filename);
1157     g_free(filename);
1159     return tempdoc;
1163 /**
1164  * @brief Callback called when some other application requests data from Inkscape
1165  *
1166  * Finds a suitable output extension to save the internal clipboard document,
1167  * then saves it to memory and sets the clipboard contents.
1168  */
1169 void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint /*info*/)
1171     g_assert( _clipboardSPDoc != NULL );
1173     Glib::ustring target = sel.get_target();
1174     if (target == "") {
1175         return; // this shouldn't happen
1176     }
1178     if (target == CLIPBOARD_TEXT_TARGET) {
1179         target = "image/x-inkscape-svg";
1180     }
1182     Inkscape::Extension::DB::OutputList outlist;
1183     Inkscape::Extension::db.get_output_list(outlist);
1184     Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
1185     for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out) {
1186     };
1187     if ( out == outlist.end() && target != "image/png") {
1188         return; // this also shouldn't happen
1189     }
1191     // FIXME: Temporary hack until we add support for memory output.
1192     // Save to a temporary file, read it back and then set the clipboard contents
1193     gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export", NULL );
1194     gsize len; gchar *data;
1196     try {
1197         if (out == outlist.end() && target == "image/png")
1198         {
1199             gdouble dpi = PX_PER_IN;
1200             guint32 bgcolor = 0x00000000;
1202             Geom::Point origin (SP_ROOT(_clipboardSPDoc->root)->x.computed, SP_ROOT(_clipboardSPDoc->root)->y.computed);
1203             Geom::Rect area = Geom::Rect(origin, origin + _clipboardSPDoc->getDimensions());
1205             unsigned long int width = (unsigned long int) (area.width() * dpi / PX_PER_IN + 0.5);
1206             unsigned long int height = (unsigned long int) (area.height() * dpi / PX_PER_IN + 0.5);
1208             // read from namedview
1209             Inkscape::XML::Node *nv = sp_repr_lookup_name (_clipboardSPDoc->rroot, "sodipodi:namedview");
1210             if (nv && nv->attribute("pagecolor")) {
1211                 bgcolor = sp_svg_read_color(nv->attribute("pagecolor"), 0xffffff00);
1212             }
1213             if (nv && nv->attribute("inkscape:pageopacity")) {
1214                 bgcolor |= SP_COLOR_F_TO_U(sp_repr_get_double_attribute (nv, "inkscape:pageopacity", 1.0));
1215             }
1217             sp_export_png_file(_clipboardSPDoc, filename, area, width, height, dpi, dpi, bgcolor, NULL, NULL, true, NULL);
1218         }
1219         else
1220         {
1221             if (!(*out)->loaded()) {
1222                 // Need to load the extension.
1223                 (*out)->set_state(Inkscape::Extension::Extension::STATE_LOADED);
1224             }
1225             (*out)->save(_clipboardSPDoc, filename);
1226         }
1227         g_file_get_contents(filename, &data, &len, NULL);
1229         sel.set(8, (guint8 const *) data, len);
1230     } catch (...) {
1231     }
1233     g_unlink(filename); // delete the temporary file
1234     g_free(filename);
1238 /**
1239  * @brief Callback when someone else takes the clipboard
1240  *
1241  * When the clipboard owner changes, this callback clears the internal clipboard document
1242  * to reduce memory usage.
1243  */
1244 void ClipboardManagerImpl::_onClear()
1246     // why is this called before _onGet???
1247     //_discardInternalClipboard();
1251 /**
1252  * @brief Creates an internal clipboard document from scratch
1253  */
1254 void ClipboardManagerImpl::_createInternalClipboard()
1256     if ( _clipboardSPDoc == NULL ) {
1257         _clipboardSPDoc = SPDocument::createNewDoc(NULL, false, true);
1258         //g_assert( _clipboardSPDoc != NULL );
1259         _defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(_clipboardSPDoc));
1260         _doc = sp_document_repr_doc(_clipboardSPDoc);
1261         _root = sp_document_repr_root(_clipboardSPDoc);
1263         _clipnode = _doc->createElement("inkscape:clipboard");
1264         _root->appendChild(_clipnode);
1265         Inkscape::GC::release(_clipnode);
1267         // once we create a SVG document, style will be stored in it, so flush _text_style
1268         if (_text_style) {
1269             sp_repr_css_attr_unref(_text_style);
1270             _text_style = NULL;
1271         }
1272     }
1276 /**
1277  * @brief Deletes the internal clipboard document
1278  */
1279 void ClipboardManagerImpl::_discardInternalClipboard()
1281     if ( _clipboardSPDoc != NULL ) {
1282         _clipboardSPDoc->doUnref();
1283         _clipboardSPDoc = NULL;
1284         _defs = NULL;
1285         _doc = NULL;
1286         _root = NULL;
1287         _clipnode = NULL;
1288     }
1292 /**
1293  * @brief Get the scale to resize an item, based on the command and desktop state
1294  */
1295 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)
1297     double scale_x = 1.0;
1298     double scale_y = 1.0;
1300     if (apply_x) {
1301         scale_x = (max[Geom::X] - min[Geom::X]) / obj_rect[Geom::X].extent();
1302     }
1303     if (apply_y) {
1304         scale_y = (max[Geom::Y] - min[Geom::Y]) / obj_rect[Geom::Y].extent();
1305     }
1306     // If the "lock aspect ratio" button is pressed and we paste only a single coordinate,
1307     // resize the second one by the same ratio too
1308     if (desktop->isToolboxButtonActive("lock")) {
1309         if (apply_x && !apply_y) {
1310             scale_y = scale_x;
1311         }
1312         if (apply_y && !apply_x) {
1313             scale_x = scale_y;
1314         }
1315     }
1317     return Geom::Scale(scale_x, scale_y);
1321 /**
1322  * @brief Find the most suitable clipboard target
1323  */
1324 Glib::ustring ClipboardManagerImpl::_getBestTarget()
1326     // GTKmm's wait_for_targets() is broken, see the comment in _inkscape_wait_for_targets()
1327     std::list<Glib::ustring> targets; // = _clipboard->wait_for_targets();
1328     _inkscape_wait_for_targets(targets);
1330     // clipboard target debugging snippet
1331     /*
1332     g_debug("Begin clipboard targets");
1333     for ( std::list<Glib::ustring>::iterator x = targets.begin() ; x != targets.end(); ++x )
1334         g_debug("Clipboard target: %s", (*x).data());
1335     g_debug("End clipboard targets\n");
1336     //*/
1338     for (std::list<Glib::ustring>::iterator i = _preferred_targets.begin() ;
1339         i != _preferred_targets.end() ; ++i)
1340     {
1341         if ( std::find(targets.begin(), targets.end(), *i) != targets.end() ) {
1342             return *i;
1343         }
1344     }
1345 #ifdef WIN32
1346     if (OpenClipboard(NULL))
1347     {   // If both bitmap and metafile are present, pick the one that was exported first.
1348         UINT format = EnumClipboardFormats(0);
1349         while (format) {
1350             if (format == CF_ENHMETAFILE || format == CF_DIB || format == CF_BITMAP) {
1351                 break;
1352             }
1353             format = EnumClipboardFormats(format);
1354         }
1355         CloseClipboard();
1357         if (format == CF_ENHMETAFILE) {
1358             return CLIPBOARD_WIN32_EMF_TARGET;
1359         }
1360         if (format == CF_DIB || format == CF_BITMAP) {
1361             return CLIPBOARD_GDK_PIXBUF_TARGET;
1362         }
1363     }
1365     if (IsClipboardFormatAvailable(CF_ENHMETAFILE)) {
1366         return CLIPBOARD_WIN32_EMF_TARGET;
1367     }
1368 #endif
1369     if (_clipboard->wait_is_image_available()) {
1370         return CLIPBOARD_GDK_PIXBUF_TARGET;
1371     }
1372     if (_clipboard->wait_is_text_available()) {
1373         return CLIPBOARD_TEXT_TARGET;
1374     }
1376     return "";
1380 /**
1381  * @brief Set the clipboard targets to reflect the mimetypes Inkscape can output
1382  */
1383 void ClipboardManagerImpl::_setClipboardTargets()
1385     Inkscape::Extension::DB::OutputList outlist;
1386     Inkscape::Extension::db.get_output_list(outlist);
1387     std::list<Gtk::TargetEntry> target_list;
1388     bool plaintextSet = false;
1389     for (Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin() ; out != outlist.end() ; ++out) {
1390         if ( !(*out)->deactivated() ) {
1391             Glib::ustring mime = (*out)->get_mimetype();
1392             if (mime != CLIPBOARD_TEXT_TARGET) {
1393                 if ( !plaintextSet && (mime.find("svg") == Glib::ustring::npos) ) {
1394                     target_list.push_back(Gtk::TargetEntry(CLIPBOARD_TEXT_TARGET));
1395                     plaintextSet = true;
1396                 }
1397                 target_list.push_back(Gtk::TargetEntry(mime));
1398             }
1399         }
1400     }
1402     // Add PNG export explicitly since there is no extension for this...
1403     // On Windows, GTK will also present this as a CF_DIB/CF_BITMAP
1404     target_list.push_back(Gtk::TargetEntry( "image/png" ));
1406     _clipboard->set(target_list,
1407         sigc::mem_fun(*this, &ClipboardManagerImpl::_onGet),
1408         sigc::mem_fun(*this, &ClipboardManagerImpl::_onClear));
1410 #ifdef WIN32
1411     // If the "image/x-emf" target handled by the emf extension would be
1412     // presented as a CF_ENHMETAFILE automatically (just like an "image/bmp"
1413     // is presented as a CF_BITMAP) this code would not be needed.. ???
1414     // Or maybe there is some other way to achieve the same?
1416     // Note: Metafile is the only format that is rendered and stored in clipboard
1417     // on Copy, all other formats are rendered only when needed by a Paste command.
1419     // FIXME: This should at least be rewritten to use "delayed rendering".
1420     //        If possible make it delayed rendering by using GTK API only.
1422     if (OpenClipboard(NULL)) {
1423         if ( _clipboardSPDoc != NULL ) {
1424             const Glib::ustring target = CLIPBOARD_WIN32_EMF_MIME;
1426             Inkscape::Extension::DB::OutputList outlist;
1427             Inkscape::Extension::db.get_output_list(outlist);
1428             Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
1429             for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out) {
1430             }
1431             if ( out != outlist.end() ) {
1432                 // FIXME: Temporary hack until we add support for memory output.
1433                 // Save to a temporary file, read it back and then set the clipboard contents
1434                 gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export.emf", NULL );
1436                 try {
1437                     (*out)->save(_clipboardSPDoc, filename);
1438                     HENHMETAFILE hemf = GetEnhMetaFileA(filename);
1439                     if (hemf) {
1440                         SetClipboardData(CF_ENHMETAFILE, hemf);
1441                         DeleteEnhMetaFile(hemf);
1442                     }
1443                 } catch (...) {
1444                 }
1445                 g_unlink(filename); // delete the temporary file
1446                 g_free(filename);
1447             }
1448         }
1449         CloseClipboard();
1450     }
1451 #endif
1455 /**
1456  * @brief Set the string representation of a 32-bit RGBA color as the clipboard contents
1457  */
1458 void ClipboardManagerImpl::_setClipboardColor(guint32 color)
1460     gchar colorstr[16];
1461     g_snprintf(colorstr, 16, "%08x", color);
1462     _clipboard->set_text(colorstr);
1466 /**
1467  * @brief Put a notification on the mesage stack
1468  */
1469 void ClipboardManagerImpl::_userWarn(SPDesktop *desktop, char const *msg)
1471     desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, msg);
1475 // GTKMM's clipboard::wait_for_targets is buggy and might return bogus, see
1476 //
1477 // https://bugs.launchpad.net/inkscape/+bug/296778
1478 // http://mail.gnome.org/archives/gtk-devel-list/2009-June/msg00062.html
1479 //
1480 // for details. Until this has been fixed upstream we will use our own implementation
1481 // of this method, as copied from /gtkmm-2.16.0/gtk/gtkmm/clipboard.cc.
1482 void ClipboardManagerImpl::_inkscape_wait_for_targets(std::list<Glib::ustring> &listTargets)
1484     //Get a newly-allocated array of atoms:
1485     GdkAtom* targets = 0;
1486     gint n_targets = 0;
1487     gboolean test = gtk_clipboard_wait_for_targets( gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), &targets, &n_targets );
1488     if (!test) {
1489         n_targets = 0; //otherwise it will be -1.
1490     }
1492     //Add the targets to the C++ container:
1493     for (int i = 0; i < n_targets; i++)
1494     {
1495         //Convert the atom to a string:
1496         gchar* const atom_name = gdk_atom_name(targets[i]);
1498         Glib::ustring target;
1499         if (atom_name) {
1500             target = Glib::ScopedPtr<char>(atom_name).get(); //This frees the gchar*.
1501         }
1503         listTargets.push_back(target);
1504     }
1507 /* #######################################
1508           ClipboardManager class
1509    ####################################### */
1511 ClipboardManager *ClipboardManager::_instance = NULL;
1513 ClipboardManager::ClipboardManager() {}
1514 ClipboardManager::~ClipboardManager() {}
1515 ClipboardManager *ClipboardManager::get()
1517     if ( _instance == NULL ) {
1518         _instance = new ClipboardManagerImpl;
1519     }
1521     return _instance;
1524 } // namespace Inkscape
1525 } // namespace IO
1527 /*
1528   Local Variables:
1529   mode:c++
1530   c-file-style:"stroustrup"
1531   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1532   indent-tabs-mode:nil
1533   fill-column:99
1534   End:
1535 */
1536 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :