Code

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