Code

17dabed82f2b256dbae1675acb5ba78074e608a0
[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 "box3d.h"
48 #include "gradient-drag.h"
49 #include "sp-item.h"
50 #include "sp-item-transform.h" // for sp_item_scale_rel, used in _pasteSize
51 #include "sp-path.h"
52 #include "sp-pattern.h"
53 #include "sp-shape.h"
54 #include "sp-gradient.h"
55 #include "sp-gradient-reference.h"
56 #include "sp-gradient-fns.h"
57 #include "sp-linear-gradient-fns.h"
58 #include "sp-radial-gradient-fns.h"
59 #include "sp-clippath.h"
60 #include "sp-mask.h"
61 #include "sp-textpath.h"
62 #include "sp-rect.h"
63 #include "live_effects/lpeobject.h"
64 #include "live_effects/lpeobject-reference.h"
65 #include "live_effects/parameter/path.h"
66 #include "svg/svg.h" // for sp_svg_transform_write, used in _copySelection
67 #include "svg/css-ostringstream.h" // used in _parseColor
68 #include "file.h" // for file_import, used in _pasteImage
69 #include "prefs-utils.h" // for prefs_get_string_attribute, used in _pasteImage
70 #include "text-context.h"
71 #include "text-editing.h"
72 #include "tools-switch.h"
73 #include "libnr/n-art-bpath-2geom.h"
74 #include "path-chemistry.h"
75 #include "id-clash.h"
76 #include "unit-constants.h"
77 #include "helper/png-write.h"
78 #include "svg/svg-color.h"
80 /// @brief Made up mimetype to represent Gdk::Pixbuf clipboard contents
81 #define CLIPBOARD_GDK_PIXBUF_TARGET "image/x-gdk-pixbuf"
83 #define CLIPBOARD_TEXT_TARGET "text/plain"
85 #ifdef WIN32
86 #include <windows.h>
87 // Clipboard Formats: http://msdn.microsoft.com/en-us/library/ms649013(VS.85).aspx
88 // On Windows, most graphical applications can handle CF_DIB/CF_BITMAP and/or CF_ENHMETAFILE
89 // GTK automatically presents an "image/bmp" target as CF_DIB/CF_BITMAP
90 // Presenting "image/x-emf" as CF_ENHMETAFILE must be done by Inkscape ?
91 #define CLIPBOARD_WIN32_EMF_TARGET "CF_ENHMETAFILE"
92 #define CLIPBOARD_WIN32_EMF_MIME   "image/x-emf"
93 #endif
95 namespace Inkscape {
96 namespace UI {
99 /**
100  * @brief Default implementation of the clipboard manager
101  */
102 class ClipboardManagerImpl : public ClipboardManager {
103 public:
104     virtual void copy();
105     virtual void copyPathParameter(Inkscape::LivePathEffect::PathParam *);
106     virtual bool paste(bool in_place);
107     virtual bool pasteStyle();
108     virtual bool pasteSize(bool, bool, bool);
109     virtual bool pastePathEffect();
110     virtual Glib::ustring getPathParameter();
111     virtual Glib::ustring getShapeOrTextObjectId();
112     virtual const gchar *getFirstObjectID();
114     ClipboardManagerImpl();
115     ~ClipboardManagerImpl();
117 private:
118     void _copySelection(Inkscape::Selection *);
119     void _copyUsedDefs(SPItem *);
120     void _copyGradient(SPGradient *);
121     void _copyPattern(SPPattern *);
122     void _copyTextPath(SPTextPath *);
123     Inkscape::XML::Node *_copyNode(Inkscape::XML::Node *, Inkscape::XML::Document *, Inkscape::XML::Node *);
125     void _pasteDocument(SPDocument *, bool in_place);
126     void _pasteDefs(SPDocument *);
127     bool _pasteImage();
128     bool _pasteText();
129     SPCSSAttr *_parseColor(const Glib::ustring &);
130     void _applyPathEffect(SPItem *, gchar const *);
131     SPDocument *_retrieveClipboard(Glib::ustring = "");
133     // clipboard callbacks
134     void _onGet(Gtk::SelectionData &, guint);
135     void _onClear();
137     // various helpers
138     void _createInternalClipboard();
139     void _discardInternalClipboard();
140     Inkscape::XML::Node *_createClipNode();
141     NR::scale _getScale(Geom::Point &, Geom::Point &, NR::Rect &, bool, bool);
142     Glib::ustring _getBestTarget();
143     void _setClipboardTargets();
144     void _setClipboardColor(guint32);
145     void _userWarn(SPDesktop *, char const *);
147     // private properites
148     SPDocument *_clipboardSPDoc; ///< Document that stores the clipboard until someone requests it
149     Inkscape::XML::Node *_defs; ///< Reference to the clipboard document's defs node
150     Inkscape::XML::Node *_root; ///< Reference to the clipboard's root node
151     Inkscape::XML::Node *_clipnode; ///< The node that holds extra information
152     Inkscape::XML::Document *_doc; ///< Reference to the clipboard's Inkscape::XML::Document
154     Glib::RefPtr<Gtk::Clipboard> _clipboard; ///< Handle to the system wide clipboard - for convenience
155     std::list<Glib::ustring> _preferred_targets; ///< List of supported clipboard targets
156 };
159 ClipboardManagerImpl::ClipboardManagerImpl()
160     : _clipboardSPDoc(NULL),
161       _defs(NULL),
162       _root(NULL),
163       _clipnode(NULL),
164       _doc(NULL),
165       _clipboard( Gtk::Clipboard::get() )
167     // push supported clipboard targets, in order of preference
168     _preferred_targets.push_back("image/x-inkscape-svg");
169     _preferred_targets.push_back("image/svg+xml");
170     _preferred_targets.push_back("image/svg+xml-compressed");
171 #ifdef WIN32
172     _preferred_targets.push_back(CLIPBOARD_WIN32_EMF_MIME);
173 #endif
174     _preferred_targets.push_back("application/pdf");
175     _preferred_targets.push_back("image/x-adobe-illustrator");
179 ClipboardManagerImpl::~ClipboardManagerImpl() {}
182 /**
183  * @brief Copy selection contents to the clipboard
184  */
185 void ClipboardManagerImpl::copy()
187     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
188     if ( desktop == NULL ) return;
189     Inkscape::Selection *selection = sp_desktop_selection(desktop);
191     // Special case for when the gradient dragger is active - copies gradient color
192     if (desktop->event_context->get_drag()) {
193         GrDrag *drag = desktop->event_context->get_drag();
194         if (drag->hasSelection()) {
195             _setClipboardColor(drag->getColor());
196             _discardInternalClipboard();
197             return;
198         }
199     }
201     // Special case for when the color picker ("dropper") is active - copies color under cursor
202     if (tools_isactive(desktop, TOOLS_DROPPER)) {
203         _setClipboardColor(sp_dropper_context_get_color(desktop->event_context));
204         _discardInternalClipboard();
205         return;
206     }
208     // Special case for when the text tool is active - if some text is selected, copy plain text,
209     // not the object that holds it
210     if (tools_isactive(desktop, TOOLS_TEXT)) {
211         Glib::ustring selected_text = sp_text_get_selected_text(desktop->event_context);
212         if (!selected_text.empty()) {
213             _clipboard->set_text(selected_text);
214             _discardInternalClipboard();
215             return;
216         }
217     }
219     if (selection->isEmpty()) {  // check whether something is selected
220         _userWarn(desktop, _("Nothing was copied."));
221         return;
222     }
223     _discardInternalClipboard();
225     _createInternalClipboard();   // construct a new clipboard document
226     _copySelection(selection);   // copy all items in the selection to the internal clipboard
227     fit_canvas_to_drawing(_clipboardSPDoc);
229     _setClipboardTargets();
233 /**
234  * @brief Copy a Live Path Effect path parameter to the clipboard
235  * @param pp The path parameter to store in the clipboard
236  */
237 void ClipboardManagerImpl::copyPathParameter(Inkscape::LivePathEffect::PathParam *pp)
239     if ( pp == NULL ) return;
240     gchar *svgd = sp_svg_write_path( pp->get_pathvector() );
241     if ( svgd == NULL || *svgd == '\0' ) return;
243     _discardInternalClipboard();
244     _createInternalClipboard();
246     Inkscape::XML::Node *pathnode = _doc->createElement("svg:path");
247     pathnode->setAttribute("d", svgd);
248     g_free(svgd);
249     _root->appendChild(pathnode);
250     Inkscape::GC::release(pathnode);
252     fit_canvas_to_drawing(_clipboardSPDoc);
253     _setClipboardTargets();
256 /**
257  * @brief Paste from the system clipboard into the active desktop
258  * @param in_place Whether to put the contents where they were when copied
259  */
260 bool ClipboardManagerImpl::paste(bool in_place)
262     // do any checking whether we really are able to paste before requesting the contents
263     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
264     if ( desktop == NULL ) return false;
265     if ( Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false ) return false;
267     Glib::ustring target = _getBestTarget();
269     // Special cases of clipboard content handling go here 00ff00
270     // Note that target priority is determined in _getBestTarget.
271     // TODO: Handle x-special/gnome-copied-files and text/uri-list to support pasting files
273     // if there is an image on the clipboard, paste it
274     if ( target == CLIPBOARD_GDK_PIXBUF_TARGET ) return _pasteImage();
275     // if there's only text, paste it into a selected text object or create a new one
276     if ( target == CLIPBOARD_TEXT_TARGET ) return _pasteText();
278     // otherwise, use the import extensions
279     SPDocument *tempdoc = _retrieveClipboard(target);
280     if ( tempdoc == NULL ) {
281         _userWarn(desktop, _("Nothing on the clipboard."));
282         return false;
283     }
285     _pasteDocument(tempdoc, in_place);
286     sp_document_unref(tempdoc);
288     return true;
291 /**
292  * @brief Returns the id of the first visible copied object
293  */
294 const gchar *ClipboardManagerImpl::getFirstObjectID()
296     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
297     if ( tempdoc == NULL ) {
298         return NULL;
299     }
301     Inkscape::XML::Node
302         *root = sp_document_repr_root(tempdoc);
304     if (!root)
305         return NULL;
307     Inkscape::XML::Node *ch = sp_repr_children(root);
308     while (ch != NULL && 
309            strcmp(ch->name(), "svg:g") &&
310            strcmp(ch->name(), "svg:path") &&
311            strcmp(ch->name(), "svg:use") &&
312            strcmp(ch->name(), "svg:text") &&
313            strcmp(ch->name(), "svg:image") &&
314            strcmp(ch->name(), "svg:rect")
315         )
316         ch = ch->next();
318     if (ch) {
319         return ch->attribute("id");
320     }
322     return NULL;
326 /**
327  * @brief Implements the Paste Style action
328  */
329 bool ClipboardManagerImpl::pasteStyle()
331     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
332     if (desktop == NULL) return false;
334     // check whether something is selected
335     Inkscape::Selection *selection = sp_desktop_selection(desktop);
336     if (selection->isEmpty()) {
337         _userWarn(desktop, _("Select <b>object(s)</b> to paste style to."));
338         return false;
339     }
341     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
342     if ( tempdoc == NULL ) {
343         _userWarn(desktop, _("No style on the clipboard."));
344         return false;
345     }
347     Inkscape::XML::Node
348         *root = sp_document_repr_root(tempdoc),
349         *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
351     bool pasted = false;
353     if (clipnode) {
354         _pasteDefs(tempdoc);
355         SPCSSAttr *style = sp_repr_css_attr(clipnode, "style");
356         sp_desktop_set_style(desktop, style);
357         pasted = true;
358     }
359     else {
360         _userWarn(desktop, _("No style on the clipboard."));
361     }
363     sp_document_unref(tempdoc);
364     return pasted;
368 /**
369  * @brief Resize the selection or each object in the selection to match the clipboard's size
370  * @param separately Whether to scale each object in the selection separately
371  * @param apply_x Whether to scale the width of objects / selection
372  * @param apply_y Whether to scale the height of objects / selection
373  */
374 bool ClipboardManagerImpl::pasteSize(bool separately, bool apply_x, bool apply_y)
376     if(!apply_x && !apply_y) return false; // pointless parameters
378     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
379     if ( desktop == NULL ) return false;
380     Inkscape::Selection *selection = sp_desktop_selection(desktop);
381     if (selection->isEmpty()) {
382         _userWarn(desktop, _("Select <b>object(s)</b> to paste size to."));
383         return false;
384     }
386     // FIXME: actually, this should accept arbitrary documents
387     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
388     if ( tempdoc == NULL ) {
389         _userWarn(desktop, _("No size on the clipboard."));
390         return false;
391     }
393     // retrieve size ifomration from the clipboard
394     Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
395     Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
396     bool pasted = false;
397     if (clipnode) {
398         Geom::Point min, max;
399         sp_repr_get_point(clipnode, "min", &min);
400         sp_repr_get_point(clipnode, "max", &max);
402         // resize each object in the selection
403         if (separately) {
404             for (GSList *i = const_cast<GSList*>(selection->itemList()) ; i ; i = i->next) {
405                 SPItem *item = SP_ITEM(i->data);
406                 NR::Maybe<NR::Rect> obj_size = sp_item_bbox_desktop(item);
407                 if ( !obj_size || obj_size->isEmpty() ) continue;
408                 sp_item_scale_rel(item, _getScale(min, max, *obj_size, apply_x, apply_y));
409             }
410         }
411         // resize the selection as a whole
412         else {
413             NR::Maybe<NR::Rect> sel_size = selection->bounds();
414             if ( sel_size && !sel_size->isEmpty() ) {
415                 sp_selection_scale_relative(selection, sel_size->midpoint(),
416                     _getScale(min, max, *sel_size, apply_x, apply_y));
417             }
418         }
419         pasted = true;
420     }
421     sp_document_unref(tempdoc);
422     return pasted;
426 /**
427  * @brief Applies a path effect from the clipboard to the selected path
428  */
429 bool ClipboardManagerImpl::pastePathEffect()
431     /** @todo FIXME: pastePathEffect crashes when moving the path with the applied effect,
432         segfaulting in fork_private_if_necessary(). */
434     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
435     if ( desktop == NULL )
436         return false;
438     Inkscape::Selection *selection = sp_desktop_selection(desktop);
439     if (selection && selection->isEmpty()) {
440         _userWarn(desktop, _("Select <b>object(s)</b> to paste live path effect to."));
441         return false;
442     }
444     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
445     if ( tempdoc ) {
446         Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
447         Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
448         if ( clipnode ) {
449             gchar const *effect = clipnode->attribute("inkscape:path-effect");
450             if ( effect ) {
451                 _pasteDefs(tempdoc);
452                 // make sure all selected items are converted to paths first (i.e. rectangles)
453                 sp_selected_path_to_curves(false);
454                 for (GSList *item = const_cast<GSList *>(selection->itemList()) ; item ; item = item->next) {
455                     _applyPathEffect(reinterpret_cast<SPItem*>(item->data), effect);
456                 }
458                 return true;
459             }
460         }
461     }
463     // no_effect:
464     _userWarn(desktop, _("No effect on the clipboard."));
465     return false;
469 /**
470  * @brief Get LPE path data from the clipboard
471  * @return The retrieved path data (contents of the d attribute), or "" if no path was found
472  */
473 Glib::ustring ClipboardManagerImpl::getPathParameter()
475     SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
476     if ( tempdoc == NULL ) {
477         _userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
478         return "";
479     }
480     Inkscape::XML::Node
481         *root = sp_document_repr_root(tempdoc),
482         *path = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
483     if ( path == NULL ) {
484         _userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
485         sp_document_unref(tempdoc);
486         return "";
487     }
488     gchar const *svgd = path->attribute("d");
489     return svgd;
493 /**
494  * @brief Get object id of a shape or text item from the clipboard
495  * @return The retrieved id string (contents of the id attribute), or "" if no shape or text item was found
496  */
497 Glib::ustring ClipboardManagerImpl::getShapeOrTextObjectId()
499     SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
500     if ( tempdoc == NULL ) {
501         _userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
502         return "";
503     }
504     Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
506     Inkscape::XML::Node *repr = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
507     if ( repr == NULL )
508         repr = sp_repr_lookup_name(root, "svg:text", -1);
510     if ( repr == NULL ) {
511         _userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
512         sp_document_unref(tempdoc);
513         return "";
514     }
515     gchar const *svgd = repr->attribute("id");
516     return svgd;
520 /**
521  * @brief Iterate over a list of items and copy them to the clipboard.
522  */
523 void ClipboardManagerImpl::_copySelection(Inkscape::Selection *selection)
525     GSList const *items = selection->itemList();
526     // copy the defs used by all items
527     for (GSList *i = const_cast<GSList *>(items) ; i != NULL ; i = i->next) {
528         _copyUsedDefs(SP_ITEM (i->data));
529     }
531     // copy the representation of the items
532     GSList *sorted_items = g_slist_copy(const_cast<GSList *>(items));
533     sorted_items = g_slist_sort(sorted_items, (GCompareFunc) sp_object_compare_position);
535     for (GSList *i = sorted_items ; i ; i = i->next) {
536         if (!SP_IS_ITEM(i->data)) continue;
537         Inkscape::XML::Node *obj = SP_OBJECT_REPR(i->data);
538         Inkscape::XML::Node *obj_copy = _copyNode(obj, _doc, _root);
540         // copy complete inherited style
541         SPCSSAttr *css = sp_repr_css_attr_inherited(obj, "style");
542         sp_repr_css_set(obj_copy, css, "style");
543         sp_repr_css_attr_unref(css);
545         // write the complete accumulated transform passed to us
546         // (we're dealing with unattached representations, so we write to their attributes
547         // instead of using sp_item_set_transform)
548         gchar *transform_str = sp_svg_transform_write(from_2geom(sp_item_i2doc_affine(SP_ITEM(i->data))));
549         obj_copy->setAttribute("transform", transform_str);
550         g_free(transform_str);
551     }
553     // copy style for Paste Style action
554     if (sorted_items) {
555         if(SP_IS_ITEM(sorted_items->data)) {
556             SPCSSAttr *style = take_style_from_item((SPItem *) sorted_items->data);
557             sp_repr_css_set(_clipnode, style, "style");
558             sp_repr_css_attr_unref(style);
559         }
561         // copy path effect from the first path
562         if (SP_IS_OBJECT(sorted_items->data)) {
563             gchar const *effect = SP_OBJECT_REPR(sorted_items->data)->attribute("inkscape:path-effect");
564             if (effect) {
565                 _clipnode->setAttribute("inkscape:path-effect", effect);
566             }
567         }
568     }
570     NR::Maybe<NR::Rect> size = selection->bounds();
571     if (size) {
572         sp_repr_set_point(_clipnode, "min", size->min().to_2geom());
573         sp_repr_set_point(_clipnode, "max", size->max().to_2geom());
574     }
576     g_slist_free(sorted_items);
580 /**
581  * @brief Recursively copy all the definitions used by a given item to the clipboard defs
582  */
583 void ClipboardManagerImpl::_copyUsedDefs(SPItem *item)
585     // copy fill and stroke styles (patterns and gradients)
586     SPStyle *style = SP_OBJECT_STYLE(item);
588     if (style && (style->fill.isPaintserver())) {
589         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
590         if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
591             _copyGradient(SP_GRADIENT(server));
592         if (SP_IS_PATTERN(server))
593             _copyPattern(SP_PATTERN(server));
594     }
595     if (style && (style->stroke.isPaintserver())) {
596         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
597         if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
598             _copyGradient(SP_GRADIENT(server));
599         if (SP_IS_PATTERN(server))
600             _copyPattern(SP_PATTERN(server));
601     }
603     // For shapes, copy all of the shape's markers
604     if (SP_IS_SHAPE(item)) {
605         SPShape *shape = SP_SHAPE (item);
606         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
607             if (shape->marker[i]) {
608                 _copyNode(SP_OBJECT_REPR(SP_OBJECT(shape->marker[i])), _doc, _defs);
609             }
610         }
611     }
612     // For lpe items, copy lpe stack if applicable
613     if (SP_IS_LPE_ITEM(item)) {
614         SPLPEItem *lpeitem = SP_LPE_ITEM (item);
615         if (sp_lpe_item_has_path_effect(lpeitem)) {
616             for (PathEffectList::iterator it = lpeitem->path_effect_list->begin(); it != lpeitem->path_effect_list->end(); ++it)
617             {
618                 LivePathEffectObject *lpeobj = (*it)->lpeobject;
619                 if (lpeobj)
620                     _copyNode(SP_OBJECT_REPR(SP_OBJECT(lpeobj)), _doc, _defs);
621             }
622         }
623     }
624     // For 3D boxes, copy perspectives
625     if (SP_IS_BOX3D(item)) {
626         _copyNode(SP_OBJECT_REPR(SP_OBJECT(box3d_get_perspective(SP_BOX3D(item)))), _doc, _defs);
627     }
628     // Copy text paths
629     if (SP_IS_TEXT_TEXTPATH(item)) {
630         _copyTextPath(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
631     }
632     // Copy clipping objects
633     if (item->clip_ref->getObject()) {
634         _copyNode(SP_OBJECT_REPR(item->clip_ref->getObject()), _doc, _defs);
635     }
636     // Copy mask objects
637     if (item->mask_ref->getObject()) {
638         SPObject *mask = item->mask_ref->getObject();
639         _copyNode(SP_OBJECT_REPR(mask), _doc, _defs);
640         // recurse into the mask for its gradients etc.
641         for (SPObject *o = SP_OBJECT(mask)->children ; o != NULL ; o = o->next) {
642             if (SP_IS_ITEM(o))
643                 _copyUsedDefs(SP_ITEM(o));
644         }
645     }
646     // Copy filters
647     if (style->getFilter()) {
648         SPObject *filter = style->getFilter();
649         if (SP_IS_FILTER(filter)) {
650             _copyNode(SP_OBJECT_REPR(filter), _doc, _defs);
651         }
652     }
654     // recurse
655     for (SPObject *o = SP_OBJECT(item)->children ; o != NULL ; o = o->next) {
656         if (SP_IS_ITEM(o))
657             _copyUsedDefs(SP_ITEM(o));
658     }
662 /**
663  * @brief Copy a single gradient to the clipboard's defs element
664  */
665 void ClipboardManagerImpl::_copyGradient(SPGradient *gradient)
667     while (gradient) {
668         // climb up the refs, copying each one in the chain
669         _copyNode(SP_OBJECT_REPR(gradient), _doc, _defs);
670         gradient = gradient->ref->getObject();
671     }
675 /**
676  * @brief Copy a single pattern to the clipboard document's defs element
677  */
678 void ClipboardManagerImpl::_copyPattern(SPPattern *pattern)
680     // climb up the references, copying each one in the chain
681     while (pattern) {
682         _copyNode(SP_OBJECT_REPR(pattern), _doc, _defs);
684         // items in the pattern may also use gradients and other patterns, so recurse
685         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL ; child = SP_OBJECT_NEXT(child) ) {
686             if (!SP_IS_ITEM (child)) continue;
687             _copyUsedDefs(SP_ITEM(child));
688         }
689         pattern = pattern->ref->getObject();
690     }
694 /**
695  * @brief Copy a text path to the clipboard's defs element
696  */
697 void ClipboardManagerImpl::_copyTextPath(SPTextPath *tp)
699     SPItem *path = sp_textpath_get_path_item(tp);
700     if(!path) return;
701     Inkscape::XML::Node *path_node = SP_OBJECT_REPR(path);
703     // Do not copy the text path to defs if it's already copied
704     if(sp_repr_lookup_child(_root, "id", path_node->attribute("id"))) return;
705     _copyNode(path_node, _doc, _defs);
709 /**
710  * @brief Copy a single XML node from one document to another
711  * @param node The node to be copied
712  * @param target_doc The document to which the node is to be copied
713  * @param parent The node in the target document which will become the parent of the copied node
714  * @return Pointer to the copied node
715  */
716 Inkscape::XML::Node *ClipboardManagerImpl::_copyNode(Inkscape::XML::Node *node, Inkscape::XML::Document *target_doc, Inkscape::XML::Node *parent)
718     Inkscape::XML::Node *dup = node->duplicate(target_doc);
719     parent->appendChild(dup);
720     Inkscape::GC::release(dup);
721     return dup;
725 /**
726  * @brief Paste the contents of a document into the active desktop
727  * @param clipdoc The document to paste
728  * @param in_place Whether to paste the selection where it was when copied
729  * @pre @c clipdoc is not empty and items can be added to the current layer
730  */
731 void ClipboardManagerImpl::_pasteDocument(SPDocument *clipdoc, bool in_place)
733     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
734     SPDocument *target_document = sp_desktop_document(desktop);
735     Inkscape::XML::Node
736         *root = sp_document_repr_root(clipdoc),
737         *target_parent = SP_OBJECT_REPR(desktop->currentLayer());
738     Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
740     // copy definitions
741     _pasteDefs(clipdoc);
743     // copy objects
744     GSList *pasted_objects = NULL;
745     for (Inkscape::XML::Node *obj = root->firstChild() ; obj ; obj = obj->next()) {
746         // Don't copy metadata, defs, named views and internal clipboard contents to the document
747         if (!strcmp(obj->name(), "svg:defs")) continue;
748         if (!strcmp(obj->name(), "svg:metadata")) continue;
749         if (!strcmp(obj->name(), "sodipodi:namedview")) continue;
750         if (!strcmp(obj->name(), "inkscape:clipboard")) continue;
751         Inkscape::XML::Node *obj_copy = _copyNode(obj, target_xmldoc, target_parent);
752         pasted_objects = g_slist_prepend(pasted_objects, (gpointer) obj_copy);
753     }
755     Inkscape::Selection *selection = sp_desktop_selection(desktop);
756     selection->setReprList(pasted_objects);
758     // move the selection to the right position
759     if(in_place)
760     {
761         Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
762         if (clipnode) {
763             Geom::Point min, max;
764             sp_repr_get_point(clipnode, "min", &min);
765             sp_repr_get_point(clipnode, "max", &max);
767             // this formula was discovered empyrically
768             min[Geom::Y] += ((max[Geom::Y] - min[Geom::Y]) - sp_document_height(target_document));
769             sp_selection_move_relative(selection, NR::Point(min));
770         }
771     }
772     // copied from former sp_selection_paste in selection-chemistry.cpp
773     else {
774         sp_document_ensure_up_to_date(target_document);
775         NR::Maybe<NR::Rect> sel_size = selection->bounds();
777         NR::Point m( desktop->point() );
778         if (sel_size) {
779             m -= sel_size->midpoint();
780         }
781         sp_selection_move_relative(selection, m);
782     }
784     g_slist_free(pasted_objects);
788 /**
789  * @brief Paste SVG defs from the document retrieved from the clipboard into the active document
790  * @param clipdoc The document to paste
791  * @pre @c clipdoc != NULL and pasting into the active document is possible
792  */
793 void ClipboardManagerImpl::_pasteDefs(SPDocument *clipdoc)
795     // boilerplate vars copied from _pasteDocument
796     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
797     SPDocument *target_document = sp_desktop_document(desktop);
798     Inkscape::XML::Node
799         *root = sp_document_repr_root(clipdoc),
800         *defs = sp_repr_lookup_name(root, "svg:defs", 1),
801         *target_defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(target_document));
802     Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
804     prevent_id_clashes(clipdoc, target_document);
805     
806     for (Inkscape::XML::Node *def = defs->firstChild() ; def ; def = def->next()) {
807         _copyNode(def, target_xmldoc, target_defs);
808     }
812 /**
813  * @brief Retrieve a bitmap image from the clipboard and paste it into the active document
814  */
815 bool ClipboardManagerImpl::_pasteImage()
817     SPDocument *doc = SP_ACTIVE_DOCUMENT;
818     if ( doc == NULL ) return false;
820     // retrieve image data
821     Glib::RefPtr<Gdk::Pixbuf> img = _clipboard->wait_for_image();
822     if (!img) return false;
824     // Very stupid hack: Write into a file, then import the file into the document.
825     // To avoid using tmpfile and POSIX file handles, make the filename based on current time.
826     // This wasn't my idea, I just copied this from selection-chemistry.cpp
827     // and just can't think of something saner at the moment. Pasting more than
828     // one image per second will overwrite the image.
829     // However, I don't think anyone is able to copy a _different_ image into inkscape
830     // in 1 second.
831     time_t rawtime;
832     char image_filename[128];
833     gchar const *save_folder;
835     time(&rawtime);
836     strftime(image_filename, 128, "inkscape_pasted_image_%Y%m%d_%H%M%S.png", localtime( &rawtime ));
837     save_folder = (gchar const *) prefs_get_string_attribute("dialogs.save_as", "path");
839     gchar *image_path = g_build_filename(save_folder, image_filename, NULL);
840     img->save(image_path, "png");
841     file_import(doc, image_path, NULL);
842     g_free(image_path);
844     return true;
847 /**
848  * @brief Paste text into the selected text object or create a new one to hold it
849  */
850 bool ClipboardManagerImpl::_pasteText()
852     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
853     if ( desktop == NULL ) return false;
855     // if the text editing tool is active, paste the text into the active text object
856     if (tools_isactive(desktop, TOOLS_TEXT))
857         return sp_text_paste_inline(desktop->event_context);
859     // try to parse the text as a color and, if successful, apply it as the current style
860     SPCSSAttr *css = _parseColor(_clipboard->wait_for_text());
861     if (css) {
862         sp_desktop_set_style(desktop, css);
863         return true;
864     }
866     return false;
870 /**
871  * @brief Attempt to parse the passed string as a hexadecimal RGB or RGBA color
872  * @param text The Glib::ustring to parse
873  * @return New CSS style representation if the parsing was successful, NULL otherwise
874  */
875 SPCSSAttr *ClipboardManagerImpl::_parseColor(const Glib::ustring &text)
877     Glib::ustring::size_type len = text.bytes();
878     char *str = const_cast<char *>(text.data());
879     bool attempt_alpha = false;
880     if ( !str || ( *str == '\0' ) ) return NULL; // this is OK due to boolean short-circuit
882     // those conditionals guard against parsing e.g. the string "fab" as "fab000"
883     // (incomplete color) and "45fab71" as "45fab710" (incomplete alpha)
884     if ( *str == '#' ) {
885         if ( len < 7 ) return NULL;
886         if ( len >= 9 ) attempt_alpha = true;
887     } else {
888         if ( len < 6 ) return NULL;
889         if ( len >= 8 ) attempt_alpha = true;
890     }
892     unsigned int color = 0, alpha = 0xff;
894     // skip a leading #, if present
895     if ( *str == '#' ) ++str;
897     // try to parse first 6 digits
898     int res = sscanf(str, "%6x", &color);
899     if ( res && ( res != EOF ) ) {
900         if (attempt_alpha) {// try to parse alpha if there's enough characters
901             sscanf(str + 6, "%2x", &alpha);
902             if ( !res || res == EOF ) alpha = 0xff;
903         }
905         SPCSSAttr *color_css = sp_repr_css_attr_new();
907         // print and set properties
908         gchar color_str[16];
909         g_snprintf(color_str, 16, "#%06x", color);
910         sp_repr_css_set_property(color_css, "fill", color_str);
912         float opacity = static_cast<float>(alpha)/static_cast<float>(0xff);
913         if (opacity > 1.0) opacity = 1.0; // safeguard
914         Inkscape::CSSOStringStream opcss;
915         opcss << opacity;
916         sp_repr_css_set_property(color_css, "fill-opacity", opcss.str().data());
917         return color_css;
918     }
919     return NULL;
923 /**
924  * @brief Applies a pasted path effect to a given item
925  */
926 void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effect)
928     if ( item == NULL ) return;
929     if ( SP_IS_RECT(item) ) return;
931     if (SP_IS_LPE_ITEM(item))
932     {
933         SPLPEItem *lpeitem = SP_LPE_ITEM(item);
934         SPObject *obj = sp_uri_reference_resolve(_clipboardSPDoc, effect);
935         if (!obj) return;
936         // if the effect is not used by anyone, we might as well take it
937         LivePathEffectObject *lpeobj = LIVEPATHEFFECT(obj)->fork_private_if_necessary(1);
938         sp_lpe_item_add_path_effect(lpeitem, lpeobj);
939     }
943 /**
944  * @brief Retrieve the clipboard contents as a document
945  * @return Clipboard contents converted to SPDocument, or NULL if no suitable content was present
946  */
947 SPDocument *ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_target)
949     Glib::ustring best_target;
950     if ( required_target == "" )
951         best_target = _getBestTarget();
952     else
953         best_target = required_target;
955     if ( best_target == "" ) {
956         return NULL;
957     }
959     // FIXME: Temporary hack until we add memory input.
960     // Save the clipboard contents to some file, then read it
961     gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-import", NULL );
963     bool file_saved = false;
964     Glib::ustring target = best_target;
966 #ifdef WIN32
967     if (best_target == CLIPBOARD_WIN32_EMF_TARGET)
968     {   // Try to save clipboard data as en emf file (using win32 api)
969         if (OpenClipboard(NULL)) {
970             HGLOBAL hglb = GetClipboardData(CF_ENHMETAFILE);
971             if (hglb) {
972                 HENHMETAFILE hemf = CopyEnhMetaFile((HENHMETAFILE) hglb, filename);
973                 if (hemf) {
974                     file_saved = true;
975                     target = CLIPBOARD_WIN32_EMF_MIME;
976                     DeleteEnhMetaFile(hemf);
977                 }
978             }
979             CloseClipboard();
980         }
981     }
982 #endif
984     if (!file_saved) {
985         if ( !_clipboard->wait_is_target_available(best_target) ) {
986             return NULL;
987         }
989         // doing this synchronously makes better sense
990         // TODO: use another method because this one is badly broken imo.
991         // from documentation: "Returns: A SelectionData object, which will be invalid if retrieving the given target failed."
992         // I don't know how to check whether an object is 'valid' or not, unusable if that's not possible...
993         Gtk::SelectionData sel = _clipboard->wait_for_contents(best_target);
994         target = sel.get_target();  // this can crash if the result was invalid of last function. No way to check for this :(
996         // FIXME: Temporary hack until we add memory input.
997         // Save the clipboard contents to some file, then read it
998         g_file_set_contents(filename, (const gchar *) sel.get_data(), sel.get_length(), NULL);
999     }
1001     // there is no specific plain SVG input extension, so if we can paste the Inkscape SVG format,
1002     // we use the image/svg+xml mimetype to look up the input extension
1003     if(target == "image/x-inkscape-svg")
1004         target = "image/svg+xml";
1006     Inkscape::Extension::DB::InputList inlist;
1007     Inkscape::Extension::db.get_input_list(inlist);
1008     Inkscape::Extension::DB::InputList::const_iterator in = inlist.begin();
1009     for (; in != inlist.end() && target != (*in)->get_mimetype() ; ++in);
1010     if ( in == inlist.end() )
1011         return NULL; // this shouldn't happen unless _getBestTarget returns something bogus
1013     SPDocument *tempdoc = NULL;
1014     try {
1015         tempdoc = (*in)->open(filename);
1016     } catch (...) {
1017     }
1018     g_unlink(filename);
1019     g_free(filename);
1021     return tempdoc;
1025 /**
1026  * @brief Callback called when some other application requests data from Inkscape
1027  *
1028  * Finds a suitable output extension to save the internal clipboard document,
1029  * then saves it to memory and sets the clipboard contents.
1030  */
1031 void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint /*info*/)
1033     g_assert( _clipboardSPDoc != NULL );
1035     const Glib::ustring target = sel.get_target();
1036     if(target == "") return; // this shouldn't happen
1038     Inkscape::Extension::DB::OutputList outlist;
1039     Inkscape::Extension::db.get_output_list(outlist);
1040     Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
1041     for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out);
1042     if ( out == outlist.end() && target != "image/png") return; // this also shouldn't happen
1044     // FIXME: Temporary hack until we add support for memory output.
1045     // Save to a temporary file, read it back and then set the clipboard contents
1046     gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export", NULL );
1047     gsize len; gchar *data;
1049     try {
1050         if (out == outlist.end() && target == "image/png")
1051         {
1052             NRRect area;
1053             gdouble dpi = PX_PER_IN;
1054             guint32 bgcolor = 0x00000000;
1056             area.x0 = SP_ROOT(_clipboardSPDoc->root)->x.computed;
1057             area.y0 = SP_ROOT(_clipboardSPDoc->root)->y.computed;
1058             area.x1 = area.x0 + sp_document_width (_clipboardSPDoc);
1059             area.y1 = area.y0 + sp_document_height (_clipboardSPDoc);
1061             unsigned long int width = (unsigned long int) ((area.x1 - area.x0) * dpi / PX_PER_IN + 0.5);
1062             unsigned long int height = (unsigned long int) ((area.y1 - area.y0) * dpi / PX_PER_IN + 0.5);
1064             // read from namedview
1065             Inkscape::XML::Node *nv = sp_repr_lookup_name (_clipboardSPDoc->rroot, "sodipodi:namedview");
1066             if (nv && nv->attribute("pagecolor"))
1067                 bgcolor = sp_svg_read_color(nv->attribute("pagecolor"), 0xffffff00);
1068             if (nv && nv->attribute("inkscape:pageopacity"))
1069                 bgcolor |= SP_COLOR_F_TO_U(sp_repr_get_double_attribute (nv, "inkscape:pageopacity", 1.0));
1071             sp_export_png_file(_clipboardSPDoc, filename, area.x0, area.y0, area.x1, area.y1, width, height, dpi, dpi, bgcolor, NULL, NULL, true, NULL);
1072         }
1073         else
1074         {
1075             (*out)->save(_clipboardSPDoc, filename);
1076         }
1077         g_file_get_contents(filename, &data, &len, NULL);
1079         sel.set(8, (guint8 const *) data, len);
1080     } catch (...) {
1081     }
1083     g_unlink(filename); // delete the temporary file
1084     g_free(filename);
1088 /**
1089  * @brief Callback when someone else takes the clipboard
1090  *
1091  * When the clipboard owner changes, this callback clears the internal clipboard document
1092  * to reduce memory usage.
1093  */
1094 void ClipboardManagerImpl::_onClear()
1096     // why is this called before _onGet???
1097     //_discardInternalClipboard();
1101 /**
1102  * @brief Creates an internal clipboard document from scratch
1103  */
1104 void ClipboardManagerImpl::_createInternalClipboard()
1106     if ( _clipboardSPDoc == NULL ) {
1107         _clipboardSPDoc = sp_document_new(NULL, false, true);
1108         //g_assert( _clipboardSPDoc != NULL );
1109         _defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(_clipboardSPDoc));
1110         _doc = sp_document_repr_doc(_clipboardSPDoc);
1111         _root = sp_document_repr_root(_clipboardSPDoc);
1113         _clipnode = _doc->createElement("inkscape:clipboard");
1114         _root->appendChild(_clipnode);
1115         Inkscape::GC::release(_clipnode);
1116     }
1120 /**
1121  * @brief Deletes the internal clipboard document
1122  */
1123 void ClipboardManagerImpl::_discardInternalClipboard()
1125     if ( _clipboardSPDoc != NULL ) {
1126         sp_document_unref(_clipboardSPDoc);
1127         _clipboardSPDoc = NULL;
1128         _defs = NULL;
1129         _doc = NULL;
1130         _root = NULL;
1131         _clipnode = NULL;
1132     }
1136 /**
1137  * @brief Get the scale to resize an item, based on the command and desktop state
1138  */
1139 NR::scale ClipboardManagerImpl::_getScale(Geom::Point &min, Geom::Point &max, NR::Rect &obj_rect, bool apply_x, bool apply_y)
1141     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1142     double scale_x = 1.0;
1143     double scale_y = 1.0;
1145     if (apply_x) {
1146         scale_x = (max[Geom::X] - min[Geom::X]) / obj_rect.extent(NR::X);
1147     }
1148     if (apply_y) {
1149         scale_y = (max[Geom::Y] - min[Geom::Y]) / obj_rect.extent(NR::Y);
1150     }
1151     // If the "lock aspect ratio" button is pressed and we paste only a single coordinate,
1152     // resize the second one by the same ratio too
1153     if (desktop->isToolboxButtonActive("lock")) {
1154         if (apply_x && !apply_y) scale_y = scale_x;
1155         if (apply_y && !apply_x) scale_x = scale_y;
1156     }
1158     return NR::scale(scale_x, scale_y);
1162 /**
1163  * @brief Find the most suitable clipboard target
1164  */
1165 Glib::ustring ClipboardManagerImpl::_getBestTarget()
1167     std::list<Glib::ustring> targets = _clipboard->wait_for_targets();
1169     // clipboard target debugging snippet
1170     /*
1171     g_debug("Begin clipboard targets");
1172     for ( std::list<Glib::ustring>::iterator x = targets.begin() ; x != targets.end(); ++x )
1173         g_debug("Clipboard target: %s", (*x).data());
1174     g_debug("End clipboard targets\n");
1175     //*/
1177     for(std::list<Glib::ustring>::iterator i = _preferred_targets.begin() ;
1178         i != _preferred_targets.end() ; ++i)
1179     {
1180         if ( std::find(targets.begin(), targets.end(), *i) != targets.end() )
1181             return *i;
1182     }
1183 #ifdef WIN32
1184     if (OpenClipboard(NULL))
1185     {   // If both bitmap and metafile are present, pick the one that was exported first.
1186         UINT format = EnumClipboardFormats(0);
1187         while (format) {
1188             if (format == CF_ENHMETAFILE || format == CF_DIB || format == CF_BITMAP)
1189                 break;
1190             format = EnumClipboardFormats(format);
1191         }
1192         CloseClipboard();
1193         
1194         if (format == CF_ENHMETAFILE)
1195             return CLIPBOARD_WIN32_EMF_TARGET;
1196         if (format == CF_DIB || format == CF_BITMAP)
1197             return CLIPBOARD_GDK_PIXBUF_TARGET;
1198     }
1199     
1200     if (IsClipboardFormatAvailable(CF_ENHMETAFILE))
1201         return CLIPBOARD_WIN32_EMF_TARGET;
1202 #endif
1203     if (_clipboard->wait_is_image_available())
1204         return CLIPBOARD_GDK_PIXBUF_TARGET;
1205     if (_clipboard->wait_is_text_available())
1206         return CLIPBOARD_TEXT_TARGET;
1208     return "";
1212 /**
1213  * @brief Set the clipboard targets to reflect the mimetypes Inkscape can output
1214  */
1215 void ClipboardManagerImpl::_setClipboardTargets()
1217     Inkscape::Extension::DB::OutputList outlist;
1218     Inkscape::Extension::db.get_output_list(outlist);
1219     std::list<Gtk::TargetEntry> target_list;
1220     for (Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin() ; out != outlist.end() ; ++out) {
1221         target_list.push_back(Gtk::TargetEntry( (*out)->get_mimetype() ));
1222     }
1224     // Add PNG export explicitly since there is no extension for this...
1225     // On Windows, GTK will also present this as a CF_DIB/CF_BITMAP
1226     target_list.push_back(Gtk::TargetEntry( "image/png" ));
1228     _clipboard->set(target_list,
1229         sigc::mem_fun(*this, &ClipboardManagerImpl::_onGet),
1230         sigc::mem_fun(*this, &ClipboardManagerImpl::_onClear));
1232 #ifdef WIN32
1233     // If the "image/x-emf" target handled by the emf extension would be
1234     // presented as a CF_ENHMETAFILE automatically (just like an "image/bmp"
1235     // is presented as a CF_BITMAP) this code would not be needed.. ???
1236     // Or maybe there is some other way to achieve the same?
1238     // Note: Metafile is the only format that is rendered and stored in clipboard
1239     // on Copy, all other formats are rendered only when needed by a Paste command.
1241     // FIXME: This should at least be rewritten to use "delayed rendering".
1242     //        If possible make it delayed rendering by using GTK API only.
1244     if (OpenClipboard(NULL)) {
1245         if ( _clipboardSPDoc != NULL ) {
1246             const Glib::ustring target = CLIPBOARD_WIN32_EMF_MIME;
1248             Inkscape::Extension::DB::OutputList outlist;
1249             Inkscape::Extension::db.get_output_list(outlist);
1250             Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
1251             for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out);
1252             if ( out != outlist.end() ) {
1253                 // FIXME: Temporary hack until we add support for memory output.
1254                 // Save to a temporary file, read it back and then set the clipboard contents
1255                 gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export.emf", NULL );
1257                 try {
1258                     (*out)->save(_clipboardSPDoc, filename);
1259                     HENHMETAFILE hemf = GetEnhMetaFileA(filename);
1260                     if (hemf) {
1261                         SetClipboardData(CF_ENHMETAFILE, hemf);
1262                         DeleteEnhMetaFile(hemf);
1263                     }
1264                 } catch (...) {
1265                 }
1266                 g_unlink(filename); // delete the temporary file
1267                 g_free(filename);
1268             }
1269         }
1270         CloseClipboard();
1271     }
1272 #endif
1276 /**
1277  * @brief Set the string representation of a 32-bit RGBA color as the clipboard contents
1278  */
1279 void ClipboardManagerImpl::_setClipboardColor(guint32 color)
1281     gchar colorstr[16];
1282     g_snprintf(colorstr, 16, "%08x", color);
1283     _clipboard->set_text(colorstr);
1287 /**
1288  * @brief Put a notification on the mesage stack
1289  */
1290 void ClipboardManagerImpl::_userWarn(SPDesktop *desktop, char const *msg)
1292     desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, msg);
1297 /* #######################################
1298           ClipboardManager class
1299    ####################################### */
1301 ClipboardManager *ClipboardManager::_instance = NULL;
1303 ClipboardManager::ClipboardManager() {}
1304 ClipboardManager::~ClipboardManager() {}
1305 ClipboardManager *ClipboardManager::get()
1307     if ( _instance == NULL )
1308         _instance = new ClipboardManagerImpl;
1309     return _instance;
1312 } // namespace Inkscape
1313 } // namespace IO
1315 /*
1316   Local Variables:
1317   mode:c++
1318   c-file-style:"stroustrup"
1319   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1320   indent-tabs-mode:nil
1321   fill-column:99
1322   End:
1323 */
1324 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :