Code

More NR ==> Geom conversion (points and some matrices/transforms)
[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     // private properites
152     SPDocument *_clipboardSPDoc; ///< Document that stores the clipboard until someone requests it
153     Inkscape::XML::Node *_defs; ///< Reference to the clipboard document's defs node
154     Inkscape::XML::Node *_root; ///< Reference to the clipboard's root node
155     Inkscape::XML::Node *_clipnode; ///< The node that holds extra information
156     Inkscape::XML::Document *_doc; ///< Reference to the clipboard's Inkscape::XML::Document
158     Glib::RefPtr<Gtk::Clipboard> _clipboard; ///< Handle to the system wide clipboard - for convenience
159     std::list<Glib::ustring> _preferred_targets; ///< List of supported clipboard targets
160 };
163 ClipboardManagerImpl::ClipboardManagerImpl()
164     : _clipboardSPDoc(NULL),
165       _defs(NULL),
166       _root(NULL),
167       _clipnode(NULL),
168       _doc(NULL),
169       _clipboard( Gtk::Clipboard::get() )
171     // push supported clipboard targets, in order of preference
172     _preferred_targets.push_back("image/x-inkscape-svg");
173     _preferred_targets.push_back("image/svg+xml");
174     _preferred_targets.push_back("image/svg+xml-compressed");
175 #ifdef WIN32
176     _preferred_targets.push_back(CLIPBOARD_WIN32_EMF_MIME);
177 #endif
178     _preferred_targets.push_back("application/pdf");
179     _preferred_targets.push_back("image/x-adobe-illustrator");
183 ClipboardManagerImpl::~ClipboardManagerImpl() {}
186 /**
187  * @brief Copy selection contents to the clipboard
188  */
189 void ClipboardManagerImpl::copy()
191     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
192     if ( desktop == NULL ) return;
193     Inkscape::Selection *selection = sp_desktop_selection(desktop);
195     // Special case for when the gradient dragger is active - copies gradient color
196     if (desktop->event_context->get_drag()) {
197         GrDrag *drag = desktop->event_context->get_drag();
198         if (drag->hasSelection()) {
199             _setClipboardColor(drag->getColor());
200             _discardInternalClipboard();
201             return;
202         }
203     }
205     // Special case for when the color picker ("dropper") is active - copies color under cursor
206     if (tools_isactive(desktop, TOOLS_DROPPER)) {
207         _setClipboardColor(sp_dropper_context_get_color(desktop->event_context));
208         _discardInternalClipboard();
209         return;
210     }
212     // Special case for when the text tool is active - if some text is selected, copy plain text,
213     // not the object that holds it
214     if (tools_isactive(desktop, TOOLS_TEXT)) {
215         Glib::ustring selected_text = sp_text_get_selected_text(desktop->event_context);
216         if (!selected_text.empty()) {
217             _clipboard->set_text(selected_text);
218             _discardInternalClipboard();
219             return;
220         }
221     }
223     if (selection->isEmpty()) {  // check whether something is selected
224         _userWarn(desktop, _("Nothing was copied."));
225         return;
226     }
227     _discardInternalClipboard();
229     _createInternalClipboard();   // construct a new clipboard document
230     _copySelection(selection);   // copy all items in the selection to the internal clipboard
231     fit_canvas_to_drawing(_clipboardSPDoc);
233     _setClipboardTargets();
237 /**
238  * @brief Copy a Live Path Effect path parameter to the clipboard
239  * @param pp The path parameter to store in the clipboard
240  */
241 void ClipboardManagerImpl::copyPathParameter(Inkscape::LivePathEffect::PathParam *pp)
243     if ( pp == NULL ) return;
244     gchar *svgd = sp_svg_write_path( pp->get_pathvector() );
245     if ( svgd == NULL || *svgd == '\0' ) return;
247     _discardInternalClipboard();
248     _createInternalClipboard();
250     Inkscape::XML::Node *pathnode = _doc->createElement("svg:path");
251     pathnode->setAttribute("d", svgd);
252     g_free(svgd);
253     _root->appendChild(pathnode);
254     Inkscape::GC::release(pathnode);
256     fit_canvas_to_drawing(_clipboardSPDoc);
257     _setClipboardTargets();
260 /**
261  * @brief Paste from the system clipboard into the active desktop
262  * @param in_place Whether to put the contents where they were when copied
263  */
264 bool ClipboardManagerImpl::paste(bool in_place)
266     // do any checking whether we really are able to paste before requesting the contents
267     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
268     if ( desktop == NULL ) return false;
269     if ( Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false ) return false;
271     Glib::ustring target = _getBestTarget();
273     // Special cases of clipboard content handling go here
274     // Note that target priority is determined in _getBestTarget.
275     // TODO: Handle x-special/gnome-copied-files and text/uri-list to support pasting files
277     // if there is an image on the clipboard, paste it
278     if ( target == CLIPBOARD_GDK_PIXBUF_TARGET ) return _pasteImage();
279     // if there's only text, paste it into a selected text object or create a new one
280     if ( target == CLIPBOARD_TEXT_TARGET ) return _pasteText();
282     // otherwise, use the import extensions
283     SPDocument *tempdoc = _retrieveClipboard(target);
284     if ( tempdoc == NULL ) {
285         _userWarn(desktop, _("Nothing on the clipboard."));
286         return false;
287     }
289     _pasteDocument(tempdoc, in_place);
290     sp_document_unref(tempdoc);
292     return true;
295 /**
296  * @brief Returns the id of the first visible copied object
297  */
298 const gchar *ClipboardManagerImpl::getFirstObjectID()
300     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
301     if ( tempdoc == NULL ) {
302         return NULL;
303     }
305     Inkscape::XML::Node
306         *root = sp_document_repr_root(tempdoc);
308     if (!root)
309         return NULL;
311     Inkscape::XML::Node *ch = sp_repr_children(root);
312     while (ch != NULL && 
313            strcmp(ch->name(), "svg:g") &&
314            strcmp(ch->name(), "svg:path") &&
315            strcmp(ch->name(), "svg:use") &&
316            strcmp(ch->name(), "svg:text") &&
317            strcmp(ch->name(), "svg:image") &&
318            strcmp(ch->name(), "svg:rect")
319         )
320         ch = ch->next();
322     if (ch) {
323         return ch->attribute("id");
324     }
326     return NULL;
330 /**
331  * @brief Implements the Paste Style action
332  */
333 bool ClipboardManagerImpl::pasteStyle()
335     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
336     if (desktop == NULL) return false;
338     // check whether something is selected
339     Inkscape::Selection *selection = sp_desktop_selection(desktop);
340     if (selection->isEmpty()) {
341         _userWarn(desktop, _("Select <b>object(s)</b> to paste style to."));
342         return false;
343     }
345     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
346     if ( tempdoc == NULL ) {
347         _userWarn(desktop, _("No style on the clipboard."));
348         return false;
349     }
351     Inkscape::XML::Node
352         *root = sp_document_repr_root(tempdoc),
353         *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
355     bool pasted = false;
357     if (clipnode) {
358         _pasteDefs(tempdoc);
359         SPCSSAttr *style = sp_repr_css_attr(clipnode, "style");
360         sp_desktop_set_style(desktop, style);
361         pasted = true;
362     }
363     else {
364         _userWarn(desktop, _("No style on the clipboard."));
365     }
367     sp_document_unref(tempdoc);
368     return pasted;
372 /**
373  * @brief Resize the selection or each object in the selection to match the clipboard's size
374  * @param separately Whether to scale each object in the selection separately
375  * @param apply_x Whether to scale the width of objects / selection
376  * @param apply_y Whether to scale the height of objects / selection
377  */
378 bool ClipboardManagerImpl::pasteSize(bool separately, bool apply_x, bool apply_y)
380     if(!apply_x && !apply_y) return false; // pointless parameters
382     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
383     if ( desktop == NULL ) return false;
384     Inkscape::Selection *selection = sp_desktop_selection(desktop);
385     if (selection->isEmpty()) {
386         _userWarn(desktop, _("Select <b>object(s)</b> to paste size to."));
387         return false;
388     }
390     // FIXME: actually, this should accept arbitrary documents
391     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
392     if ( tempdoc == NULL ) {
393         _userWarn(desktop, _("No size on the clipboard."));
394         return false;
395     }
397     // retrieve size ifomration from the clipboard
398     Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
399     Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
400     bool pasted = false;
401     if (clipnode) {
402         Geom::Point min, max;
403         sp_repr_get_point(clipnode, "min", &min);
404         sp_repr_get_point(clipnode, "max", &max);
406         // resize each object in the selection
407         if (separately) {
408             for (GSList *i = const_cast<GSList*>(selection->itemList()) ; i ; i = i->next) {
409                 SPItem *item = SP_ITEM(i->data);
410                 boost::optional<NR::Rect> obj_size = sp_item_bbox_desktop(item);
411                 if ( !obj_size || obj_size->isEmpty() ) continue;
412                 sp_item_scale_rel(item, _getScale(min, max, to_2geom(*obj_size), apply_x, apply_y));
413             }
414         }
415         // resize the selection as a whole
416         else {
417             boost::optional<NR::Rect> sel_size = selection->bounds();
418             if ( sel_size && !sel_size->isEmpty() ) {
419                 sp_selection_scale_relative(selection, sel_size->midpoint(),
420                     _getScale(min, max, to_2geom(*sel_size), apply_x, apply_y));
421             }
422         }
423         pasted = true;
424     }
425     sp_document_unref(tempdoc);
426     return pasted;
430 /**
431  * @brief Applies a path effect from the clipboard to the selected path
432  */
433 bool ClipboardManagerImpl::pastePathEffect()
435     /** @todo FIXME: pastePathEffect crashes when moving the path with the applied effect,
436         segfaulting in fork_private_if_necessary(). */
438     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
439     if ( desktop == NULL )
440         return false;
442     Inkscape::Selection *selection = sp_desktop_selection(desktop);
443     if (selection && selection->isEmpty()) {
444         _userWarn(desktop, _("Select <b>object(s)</b> to paste live path effect to."));
445         return false;
446     }
448     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
449     if ( tempdoc ) {
450         Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
451         Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
452         if ( clipnode ) {
453             gchar const *effect = clipnode->attribute("inkscape:path-effect");
454             if ( effect ) {
455                 _pasteDefs(tempdoc);
456                 // make sure all selected items are converted to paths first (i.e. rectangles)
457                 sp_selected_path_to_curves(desktop, false);
458                 for (GSList *item = const_cast<GSList *>(selection->itemList()) ; item ; item = item->next) {
459                     _applyPathEffect(reinterpret_cast<SPItem*>(item->data), effect);
460                 }
462                 return true;
463             }
464         }
465     }
467     // no_effect:
468     _userWarn(desktop, _("No effect on the clipboard."));
469     return false;
473 /**
474  * @brief Get LPE path data from the clipboard
475  * @return The retrieved path data (contents of the d attribute), or "" if no path was found
476  */
477 Glib::ustring ClipboardManagerImpl::getPathParameter()
479     SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
480     if ( tempdoc == NULL ) {
481         _userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
482         return "";
483     }
484     Inkscape::XML::Node
485         *root = sp_document_repr_root(tempdoc),
486         *path = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
487     if ( path == NULL ) {
488         _userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
489         sp_document_unref(tempdoc);
490         return "";
491     }
492     gchar const *svgd = path->attribute("d");
493     return svgd;
497 /**
498  * @brief Get object id of a shape or text item from the clipboard
499  * @return The retrieved id string (contents of the id attribute), or "" if no shape or text item was found
500  */
501 Glib::ustring ClipboardManagerImpl::getShapeOrTextObjectId()
503     SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
504     if ( tempdoc == NULL ) {
505         _userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
506         return "";
507     }
508     Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
510     Inkscape::XML::Node *repr = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
511     if ( repr == NULL )
512         repr = sp_repr_lookup_name(root, "svg:text", -1);
514     if ( repr == NULL ) {
515         _userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
516         sp_document_unref(tempdoc);
517         return "";
518     }
519     gchar const *svgd = repr->attribute("id");
520     return svgd;
524 /**
525  * @brief Iterate over a list of items and copy them to the clipboard.
526  */
527 void ClipboardManagerImpl::_copySelection(Inkscape::Selection *selection)
529     GSList const *items = selection->itemList();
530     // copy the defs used by all items
531     for (GSList *i = const_cast<GSList *>(items) ; i != NULL ; i = i->next) {
532         _copyUsedDefs(SP_ITEM (i->data));
533     }
535     // copy the representation of the items
536     GSList *sorted_items = g_slist_copy(const_cast<GSList *>(items));
537     sorted_items = g_slist_sort(sorted_items, (GCompareFunc) sp_object_compare_position);
539     for (GSList *i = sorted_items ; i ; i = i->next) {
540         if (!SP_IS_ITEM(i->data)) continue;
541         Inkscape::XML::Node *obj = SP_OBJECT_REPR(i->data);
542         Inkscape::XML::Node *obj_copy = _copyNode(obj, _doc, _root);
544         // copy complete inherited style
545         SPCSSAttr *css = sp_repr_css_attr_inherited(obj, "style");
546         sp_repr_css_set(obj_copy, css, "style");
547         sp_repr_css_attr_unref(css);
549         // write the complete accumulated transform passed to us
550         // (we're dealing with unattached representations, so we write to their attributes
551         // instead of using sp_item_set_transform)
552         gchar *transform_str = sp_svg_transform_write(sp_item_i2doc_affine(SP_ITEM(i->data)));
553         obj_copy->setAttribute("transform", transform_str);
554         g_free(transform_str);
555     }
557     // copy style for Paste Style action
558     if (sorted_items) {
559         if(SP_IS_ITEM(sorted_items->data)) {
560             SPCSSAttr *style = take_style_from_item((SPItem *) sorted_items->data);
561             sp_repr_css_set(_clipnode, style, "style");
562             sp_repr_css_attr_unref(style);
563         }
565         // copy path effect from the first path
566         if (SP_IS_OBJECT(sorted_items->data)) {
567             gchar const *effect = SP_OBJECT_REPR(sorted_items->data)->attribute("inkscape:path-effect");
568             if (effect) {
569                 _clipnode->setAttribute("inkscape:path-effect", effect);
570             }
571         }
572     }
574     boost::optional<NR::Rect> size = selection->bounds();
575     if (size) {
576         sp_repr_set_point(_clipnode, "min", size->min());
577         sp_repr_set_point(_clipnode, "max", size->max());
578     }
580     g_slist_free(sorted_items);
584 /**
585  * @brief Recursively copy all the definitions used by a given item to the clipboard defs
586  */
587 void ClipboardManagerImpl::_copyUsedDefs(SPItem *item)
589     // copy fill and stroke styles (patterns and gradients)
590     SPStyle *style = SP_OBJECT_STYLE(item);
592     if (style && (style->fill.isPaintserver())) {
593         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
594         if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
595             _copyGradient(SP_GRADIENT(server));
596         if (SP_IS_PATTERN(server))
597             _copyPattern(SP_PATTERN(server));
598     }
599     if (style && (style->stroke.isPaintserver())) {
600         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
601         if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
602             _copyGradient(SP_GRADIENT(server));
603         if (SP_IS_PATTERN(server))
604             _copyPattern(SP_PATTERN(server));
605     }
607     // For shapes, copy all of the shape's markers
608     if (SP_IS_SHAPE(item)) {
609         SPShape *shape = SP_SHAPE (item);
610         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
611             if (shape->marker[i]) {
612                 _copyNode(SP_OBJECT_REPR(SP_OBJECT(shape->marker[i])), _doc, _defs);
613             }
614         }
615     }
616     // For lpe items, copy lpe stack if applicable
617     if (SP_IS_LPE_ITEM(item)) {
618         SPLPEItem *lpeitem = SP_LPE_ITEM (item);
619         if (sp_lpe_item_has_path_effect(lpeitem)) {
620             for (PathEffectList::iterator it = lpeitem->path_effect_list->begin(); it != lpeitem->path_effect_list->end(); ++it)
621             {
622                 LivePathEffectObject *lpeobj = (*it)->lpeobject;
623                 if (lpeobj)
624                     _copyNode(SP_OBJECT_REPR(SP_OBJECT(lpeobj)), _doc, _defs);
625             }
626         }
627     }
628     // For 3D boxes, copy perspectives
629     if (SP_IS_BOX3D(item)) {
630         _copyNode(SP_OBJECT_REPR(SP_OBJECT(box3d_get_perspective(SP_BOX3D(item)))), _doc, _defs);
631     }
632     // Copy text paths
633     if (SP_IS_TEXT_TEXTPATH(item)) {
634         _copyTextPath(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
635     }
636     // Copy clipping objects
637     if (item->clip_ref->getObject()) {
638         _copyNode(SP_OBJECT_REPR(item->clip_ref->getObject()), _doc, _defs);
639     }
640     // Copy mask objects
641     if (item->mask_ref->getObject()) {
642         SPObject *mask = item->mask_ref->getObject();
643         _copyNode(SP_OBJECT_REPR(mask), _doc, _defs);
644         // recurse into the mask for its gradients etc.
645         for (SPObject *o = SP_OBJECT(mask)->children ; o != NULL ; o = o->next) {
646             if (SP_IS_ITEM(o))
647                 _copyUsedDefs(SP_ITEM(o));
648         }
649     }
650     // Copy filters
651     if (style->getFilter()) {
652         SPObject *filter = style->getFilter();
653         if (SP_IS_FILTER(filter)) {
654             _copyNode(SP_OBJECT_REPR(filter), _doc, _defs);
655         }
656     }
658     // recurse
659     for (SPObject *o = SP_OBJECT(item)->children ; o != NULL ; o = o->next) {
660         if (SP_IS_ITEM(o))
661             _copyUsedDefs(SP_ITEM(o));
662     }
666 /**
667  * @brief Copy a single gradient to the clipboard's defs element
668  */
669 void ClipboardManagerImpl::_copyGradient(SPGradient *gradient)
671     while (gradient) {
672         // climb up the refs, copying each one in the chain
673         _copyNode(SP_OBJECT_REPR(gradient), _doc, _defs);
674         gradient = gradient->ref->getObject();
675     }
679 /**
680  * @brief Copy a single pattern to the clipboard document's defs element
681  */
682 void ClipboardManagerImpl::_copyPattern(SPPattern *pattern)
684     // climb up the references, copying each one in the chain
685     while (pattern) {
686         _copyNode(SP_OBJECT_REPR(pattern), _doc, _defs);
688         // items in the pattern may also use gradients and other patterns, so recurse
689         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL ; child = SP_OBJECT_NEXT(child) ) {
690             if (!SP_IS_ITEM (child)) continue;
691             _copyUsedDefs(SP_ITEM(child));
692         }
693         pattern = pattern->ref->getObject();
694     }
698 /**
699  * @brief Copy a text path to the clipboard's defs element
700  */
701 void ClipboardManagerImpl::_copyTextPath(SPTextPath *tp)
703     SPItem *path = sp_textpath_get_path_item(tp);
704     if(!path) return;
705     Inkscape::XML::Node *path_node = SP_OBJECT_REPR(path);
707     // Do not copy the text path to defs if it's already copied
708     if(sp_repr_lookup_child(_root, "id", path_node->attribute("id"))) return;
709     _copyNode(path_node, _doc, _defs);
713 /**
714  * @brief Copy a single XML node from one document to another
715  * @param node The node to be copied
716  * @param target_doc The document to which the node is to be copied
717  * @param parent The node in the target document which will become the parent of the copied node
718  * @return Pointer to the copied node
719  */
720 Inkscape::XML::Node *ClipboardManagerImpl::_copyNode(Inkscape::XML::Node *node, Inkscape::XML::Document *target_doc, Inkscape::XML::Node *parent)
722     Inkscape::XML::Node *dup = node->duplicate(target_doc);
723     parent->appendChild(dup);
724     Inkscape::GC::release(dup);
725     return dup;
729 /**
730  * @brief Paste the contents of a document into the active desktop
731  * @param clipdoc The document to paste
732  * @param in_place Whether to paste the selection where it was when copied
733  * @pre @c clipdoc is not empty and items can be added to the current layer
734  */
735 void ClipboardManagerImpl::_pasteDocument(SPDocument *clipdoc, bool in_place)
737     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
738     SPDocument *target_document = sp_desktop_document(desktop);
739     Inkscape::XML::Node
740         *root = sp_document_repr_root(clipdoc),
741         *target_parent = SP_OBJECT_REPR(desktop->currentLayer());
742     Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
744     // copy definitions
745     _pasteDefs(clipdoc);
747     // copy objects
748     GSList *pasted_objects = NULL;
749     for (Inkscape::XML::Node *obj = root->firstChild() ; obj ; obj = obj->next()) {
750         // Don't copy metadata, defs, named views and internal clipboard contents to the document
751         if (!strcmp(obj->name(), "svg:defs")) continue;
752         if (!strcmp(obj->name(), "svg:metadata")) continue;
753         if (!strcmp(obj->name(), "sodipodi:namedview")) continue;
754         if (!strcmp(obj->name(), "inkscape:clipboard")) continue;
755         Inkscape::XML::Node *obj_copy = _copyNode(obj, target_xmldoc, target_parent);
756         pasted_objects = g_slist_prepend(pasted_objects, (gpointer) obj_copy);
757     }
758     
759     /* The pasted objects are at the origin of the document coordinates (i.e. the upper left corner
760      * of the bounding box of the pasted selection is aligned to the upper left page corner).
761      * Now we will move the pasted objects to where we want them to be, which is either at the
762      * original position ("in place") or at the location of the mouse pointer (optionaly with snapping
763      * to the grid)
764      */ 
766     Geom::Point rel_pos_original, rel_pos_mouse;
767     
768     // Calculate the relative location of the original objects
769     Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
770     if (clipnode) {
771         Geom::Point min, max;
772         // Get two bounding box corners of the data in the clipboard (still in it's original position)
773         sp_repr_get_point(clipnode, "min", &min); //In desktop coordinates
774         sp_repr_get_point(clipnode, "max", &max);        
775         // Calculate the upper-left page corner in desktop coordinates (where the pasted objects are located)
776         Geom::Point ul_page_corner = desktop->doc2dt(Geom::Point(0,0)); 
777         // Calculate the upper-left bbox corner of the original objects
778         Geom::Point ul_sel_corner = Geom::Point(min[Geom::X], max[Geom::Y]);
779         // Now calculate how far we would have to move the pasted objects to get them
780         // at the location of the original
781         rel_pos_original = ul_sel_corner - ul_page_corner; // in desktop coordinates
782     }
783     
784     // Calculate the relative location of the mouse pointer
785     Inkscape::Selection *selection = sp_desktop_selection(desktop);
786     selection->setReprList(pasted_objects);         // Change the selection to the freshly pasted objects
787     sp_document_ensure_up_to_date(target_document); // What does this do?
788     
789     boost::optional<NR::Rect> sel_bbox = selection->bounds(); //In desktop coordinates
790     // PS: We could also have used the min/max corners calculated above, instead of selection->bounds() because 
791     // we know that after pasting the upper left corner of the selection will be aligend to the corresponding 
792     // page corner. Using the boundingbox of the selection is more foolproof though
793     if (sel_bbox) {
794         Geom::Point pos_mouse = desktop->point(); //Location of mouse pointer in desktop coordinates
795         // Now calculate how far we would have to move the pasted objects to get their
796         // midpoint at the location of the mouse pointer
797         rel_pos_mouse = pos_mouse - to_2geom(sel_bbox->midpoint());
798     }
799     
800     // Determine which offset we need to apply to the pasted objects
801     Geom::Point offset;
802     if (in_place) { // Align the pasted objects with their originals
803         offset = rel_pos_original;        
804     } else { // Stick to the grid if snapping is enabled, otherwise paste at mouse position;
805         SnapManager &m = desktop->namedview->snap_manager;
806         m.setup(desktop, false); //Don't display the snapindicator
807         offset = rel_pos_original + m.multipleOfGridPitch(rel_pos_mouse - rel_pos_original); 
808     }
809     
810     // Apply the offset to the pasted objects
811     sp_selection_move_relative(selection, offset);
812     g_slist_free(pasted_objects);
816 /**
817  * @brief Paste SVG defs from the document retrieved from the clipboard into the active document
818  * @param clipdoc The document to paste
819  * @pre @c clipdoc != NULL and pasting into the active document is possible
820  */
821 void ClipboardManagerImpl::_pasteDefs(SPDocument *clipdoc)
823     // boilerplate vars copied from _pasteDocument
824     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
825     SPDocument *target_document = sp_desktop_document(desktop);
826     Inkscape::XML::Node
827         *root = sp_document_repr_root(clipdoc),
828         *defs = sp_repr_lookup_name(root, "svg:defs", 1),
829         *target_defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(target_document));
830     Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
832     prevent_id_clashes(clipdoc, target_document);
833     
834     for (Inkscape::XML::Node *def = defs->firstChild() ; def ; def = def->next()) {
835         _copyNode(def, target_xmldoc, target_defs);
836     }
840 /**
841  * @brief Retrieve a bitmap image from the clipboard and paste it into the active document
842  */
843 bool ClipboardManagerImpl::_pasteImage()
845     SPDocument *doc = SP_ACTIVE_DOCUMENT;
846     if ( doc == NULL ) return false;
848     // retrieve image data
849     Glib::RefPtr<Gdk::Pixbuf> img = _clipboard->wait_for_image();
850     if (!img) return false;
852     // Very stupid hack: Write into a file, then import the file into the document.
853     // To avoid using tmpfile and POSIX file handles, make the filename based on current time.
854     // This wasn't my idea, I just copied this from selection-chemistry.cpp
855     // and just can't think of something saner at the moment. Pasting more than
856     // one image per second will overwrite the image.
857     // However, I don't think anyone is able to copy a _different_ image into inkscape
858     // in 1 second.
859     time_t rawtime;
860     char image_filename[128];
862     time(&rawtime);
863     strftime(image_filename, 128, "inkscape_pasted_image_%Y%m%d_%H%M%S.png", localtime( &rawtime ));
864     /// @todo Check whether the encoding is correct here
865     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
866     std::string save_folder = Glib::filename_from_utf8(prefs->getString("dialogs.save_as", "path"));
868     gchar *image_path = g_build_filename(save_folder.data(), image_filename, NULL);
869     img->save(image_path, "png");
870     file_import(doc, image_path, NULL);
871     g_free(image_path);
873     return true;
876 /**
877  * @brief Paste text into the selected text object or create a new one to hold it
878  */
879 bool ClipboardManagerImpl::_pasteText()
881     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
882     if ( desktop == NULL ) return false;
884     // if the text editing tool is active, paste the text into the active text object
885     if (tools_isactive(desktop, TOOLS_TEXT))
886         return sp_text_paste_inline(desktop->event_context);
888     // try to parse the text as a color and, if successful, apply it as the current style
889     SPCSSAttr *css = _parseColor(_clipboard->wait_for_text());
890     if (css) {
891         sp_desktop_set_style(desktop, css);
892         return true;
893     }
895     return false;
899 /**
900  * @brief Attempt to parse the passed string as a hexadecimal RGB or RGBA color
901  * @param text The Glib::ustring to parse
902  * @return New CSS style representation if the parsing was successful, NULL otherwise
903  */
904 SPCSSAttr *ClipboardManagerImpl::_parseColor(const Glib::ustring &text)
906 // TODO reuse existing code instead of replicating here.
907     Glib::ustring::size_type len = text.bytes();
908     char *str = const_cast<char *>(text.data());
909     bool attempt_alpha = false;
910     if ( !str || ( *str == '\0' ) ) return NULL; // this is OK due to boolean short-circuit
912     // those conditionals guard against parsing e.g. the string "fab" as "fab000"
913     // (incomplete color) and "45fab71" as "45fab710" (incomplete alpha)
914     if ( *str == '#' ) {
915         if ( len < 7 ) return NULL;
916         if ( len >= 9 ) attempt_alpha = true;
917     } else {
918         if ( len < 6 ) return NULL;
919         if ( len >= 8 ) attempt_alpha = true;
920     }
922     unsigned int color = 0, alpha = 0xff;
924     // skip a leading #, if present
925     if ( *str == '#' ) ++str;
927     // try to parse first 6 digits
928     int res = sscanf(str, "%6x", &color);
929     if ( res && ( res != EOF ) ) {
930         if (attempt_alpha) {// try to parse alpha if there's enough characters
931             sscanf(str + 6, "%2x", &alpha);
932             if ( !res || res == EOF ) alpha = 0xff;
933         }
935         SPCSSAttr *color_css = sp_repr_css_attr_new();
937         // print and set properties
938         gchar color_str[16];
939         g_snprintf(color_str, 16, "#%06x", color);
940         sp_repr_css_set_property(color_css, "fill", color_str);
942         float opacity = static_cast<float>(alpha)/static_cast<float>(0xff);
943         if (opacity > 1.0) opacity = 1.0; // safeguard
944         Inkscape::CSSOStringStream opcss;
945         opcss << opacity;
946         sp_repr_css_set_property(color_css, "fill-opacity", opcss.str().data());
947         return color_css;
948     }
949     return NULL;
953 /**
954  * @brief Applies a pasted path effect to a given item
955  */
956 void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effect)
958     if ( item == NULL ) return;
959     if ( SP_IS_RECT(item) ) return;
961     if (SP_IS_LPE_ITEM(item))
962     {
963         SPLPEItem *lpeitem = SP_LPE_ITEM(item);
964         SPObject *obj = sp_uri_reference_resolve(_clipboardSPDoc, effect);
965         if (!obj) return;
966         // if the effect is not used by anyone, we might as well take it
967         LivePathEffectObject *lpeobj = LIVEPATHEFFECT(obj)->fork_private_if_necessary(1);
968         sp_lpe_item_add_path_effect(lpeitem, lpeobj);
969     }
973 /**
974  * @brief Retrieve the clipboard contents as a document
975  * @return Clipboard contents converted to SPDocument, or NULL if no suitable content was present
976  */
977 SPDocument *ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_target)
979     Glib::ustring best_target;
980     if ( required_target == "" )
981         best_target = _getBestTarget();
982     else
983         best_target = required_target;
985     if ( best_target == "" ) {
986         return NULL;
987     }
989     // FIXME: Temporary hack until we add memory input.
990     // Save the clipboard contents to some file, then read it
991     gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-import", NULL );
993     bool file_saved = false;
994     Glib::ustring target = best_target;
996 #ifdef WIN32
997     if (best_target == CLIPBOARD_WIN32_EMF_TARGET)
998     {   // Try to save clipboard data as en emf file (using win32 api)
999         if (OpenClipboard(NULL)) {
1000             HGLOBAL hglb = GetClipboardData(CF_ENHMETAFILE);
1001             if (hglb) {
1002                 HENHMETAFILE hemf = CopyEnhMetaFile((HENHMETAFILE) hglb, filename);
1003                 if (hemf) {
1004                     file_saved = true;
1005                     target = CLIPBOARD_WIN32_EMF_MIME;
1006                     DeleteEnhMetaFile(hemf);
1007                 }
1008             }
1009             CloseClipboard();
1010         }
1011     }
1012 #endif
1014     if (!file_saved) {
1015         if ( !_clipboard->wait_is_target_available(best_target) ) {
1016             return NULL;
1017         }
1019         // doing this synchronously makes better sense
1020         // TODO: use another method because this one is badly broken imo.
1021         // from documentation: "Returns: A SelectionData object, which will be invalid if retrieving the given target failed."
1022         // I don't know how to check whether an object is 'valid' or not, unusable if that's not possible...
1023         Gtk::SelectionData sel = _clipboard->wait_for_contents(best_target);
1024         target = sel.get_target();  // this can crash if the result was invalid of last function. No way to check for this :(
1026         // FIXME: Temporary hack until we add memory input.
1027         // Save the clipboard contents to some file, then read it
1028         g_file_set_contents(filename, (const gchar *) sel.get_data(), sel.get_length(), NULL);
1029     }
1031     // there is no specific plain SVG input extension, so if we can paste the Inkscape SVG format,
1032     // we use the image/svg+xml mimetype to look up the input extension
1033     if(target == "image/x-inkscape-svg")
1034         target = "image/svg+xml";
1036     Inkscape::Extension::DB::InputList inlist;
1037     Inkscape::Extension::db.get_input_list(inlist);
1038     Inkscape::Extension::DB::InputList::const_iterator in = inlist.begin();
1039     for (; in != inlist.end() && target != (*in)->get_mimetype() ; ++in);
1040     if ( in == inlist.end() )
1041         return NULL; // this shouldn't happen unless _getBestTarget returns something bogus
1043     SPDocument *tempdoc = NULL;
1044     try {
1045         tempdoc = (*in)->open(filename);
1046     } catch (...) {
1047     }
1048     g_unlink(filename);
1049     g_free(filename);
1051     return tempdoc;
1055 /**
1056  * @brief Callback called when some other application requests data from Inkscape
1057  *
1058  * Finds a suitable output extension to save the internal clipboard document,
1059  * then saves it to memory and sets the clipboard contents.
1060  */
1061 void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint /*info*/)
1063     g_assert( _clipboardSPDoc != NULL );
1065     Glib::ustring target = sel.get_target();
1066     if(target == "") return; // this shouldn't happen
1068     if (target == CLIPBOARD_TEXT_TARGET) {
1069         target = "image/x-inkscape-svg";
1070     }
1072     Inkscape::Extension::DB::OutputList outlist;
1073     Inkscape::Extension::db.get_output_list(outlist);
1074     Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
1075     for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out);
1076     if ( out == outlist.end() && target != "image/png") return; // this also shouldn't happen
1078     // FIXME: Temporary hack until we add support for memory output.
1079     // Save to a temporary file, read it back and then set the clipboard contents
1080     gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export", NULL );
1081     gsize len; gchar *data;
1083     try {
1084         if (out == outlist.end() && target == "image/png")
1085         {
1086             NRRect area;
1087             gdouble dpi = PX_PER_IN;
1088             guint32 bgcolor = 0x00000000;
1090             area.x0 = SP_ROOT(_clipboardSPDoc->root)->x.computed;
1091             area.y0 = SP_ROOT(_clipboardSPDoc->root)->y.computed;
1092             area.x1 = area.x0 + sp_document_width (_clipboardSPDoc);
1093             area.y1 = area.y0 + sp_document_height (_clipboardSPDoc);
1095             unsigned long int width = (unsigned long int) ((area.x1 - area.x0) * dpi / PX_PER_IN + 0.5);
1096             unsigned long int height = (unsigned long int) ((area.y1 - area.y0) * dpi / PX_PER_IN + 0.5);
1098             // read from namedview
1099             Inkscape::XML::Node *nv = sp_repr_lookup_name (_clipboardSPDoc->rroot, "sodipodi:namedview");
1100             if (nv && nv->attribute("pagecolor"))
1101                 bgcolor = sp_svg_read_color(nv->attribute("pagecolor"), 0xffffff00);
1102             if (nv && nv->attribute("inkscape:pageopacity"))
1103                 bgcolor |= SP_COLOR_F_TO_U(sp_repr_get_double_attribute (nv, "inkscape:pageopacity", 1.0));
1105             sp_export_png_file(_clipboardSPDoc, filename, area.x0, area.y0, area.x1, area.y1, width, height, dpi, dpi, bgcolor, NULL, NULL, true, NULL);
1106         }
1107         else
1108         {
1109             if (!(*out)->loaded()) {
1110                 // Need to load the extension.
1111                 (*out)->set_state(Inkscape::Extension::Extension::STATE_LOADED);
1112             }
1113             (*out)->save(_clipboardSPDoc, filename);
1114         }
1115         g_file_get_contents(filename, &data, &len, NULL);
1117         sel.set(8, (guint8 const *) data, len);
1118     } catch (...) {
1119     }
1121     g_unlink(filename); // delete the temporary file
1122     g_free(filename);
1126 /**
1127  * @brief Callback when someone else takes the clipboard
1128  *
1129  * When the clipboard owner changes, this callback clears the internal clipboard document
1130  * to reduce memory usage.
1131  */
1132 void ClipboardManagerImpl::_onClear()
1134     // why is this called before _onGet???
1135     //_discardInternalClipboard();
1139 /**
1140  * @brief Creates an internal clipboard document from scratch
1141  */
1142 void ClipboardManagerImpl::_createInternalClipboard()
1144     if ( _clipboardSPDoc == NULL ) {
1145         _clipboardSPDoc = sp_document_new(NULL, false, true);
1146         //g_assert( _clipboardSPDoc != NULL );
1147         _defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(_clipboardSPDoc));
1148         _doc = sp_document_repr_doc(_clipboardSPDoc);
1149         _root = sp_document_repr_root(_clipboardSPDoc);
1151         _clipnode = _doc->createElement("inkscape:clipboard");
1152         _root->appendChild(_clipnode);
1153         Inkscape::GC::release(_clipnode);
1154     }
1158 /**
1159  * @brief Deletes the internal clipboard document
1160  */
1161 void ClipboardManagerImpl::_discardInternalClipboard()
1163     if ( _clipboardSPDoc != NULL ) {
1164         sp_document_unref(_clipboardSPDoc);
1165         _clipboardSPDoc = NULL;
1166         _defs = NULL;
1167         _doc = NULL;
1168         _root = NULL;
1169         _clipnode = NULL;
1170     }
1174 /**
1175  * @brief Get the scale to resize an item, based on the command and desktop state
1176  */
1177 Geom::Scale ClipboardManagerImpl::_getScale(Geom::Point const &min, Geom::Point const &max, Geom::Rect const &obj_rect, bool apply_x, bool apply_y)
1179     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1180     double scale_x = 1.0;
1181     double scale_y = 1.0;
1183     if (apply_x) {
1184         scale_x = (max[Geom::X] - min[Geom::X]) / obj_rect[Geom::X].extent();
1185     }
1186     if (apply_y) {
1187         scale_y = (max[Geom::Y] - min[Geom::Y]) / obj_rect[Geom::Y].extent();
1188     }
1189     // If the "lock aspect ratio" button is pressed and we paste only a single coordinate,
1190     // resize the second one by the same ratio too
1191     if (desktop->isToolboxButtonActive("lock")) {
1192         if (apply_x && !apply_y) scale_y = scale_x;
1193         if (apply_y && !apply_x) scale_x = scale_y;
1194     }
1196     return Geom::Scale(scale_x, scale_y);
1200 /**
1201  * @brief Find the most suitable clipboard target
1202  */
1203 Glib::ustring ClipboardManagerImpl::_getBestTarget()
1205     std::list<Glib::ustring> targets = _clipboard->wait_for_targets();
1207     // clipboard target debugging snippet
1208     /*
1209     g_debug("Begin clipboard targets");
1210     for ( std::list<Glib::ustring>::iterator x = targets.begin() ; x != targets.end(); ++x )
1211         g_debug("Clipboard target: %s", (*x).data());
1212     g_debug("End clipboard targets\n");
1213     //*/
1215     for(std::list<Glib::ustring>::iterator i = _preferred_targets.begin() ;
1216         i != _preferred_targets.end() ; ++i)
1217     {
1218         if ( std::find(targets.begin(), targets.end(), *i) != targets.end() )
1219             return *i;
1220     }
1221 #ifdef WIN32
1222     if (OpenClipboard(NULL))
1223     {   // If both bitmap and metafile are present, pick the one that was exported first.
1224         UINT format = EnumClipboardFormats(0);
1225         while (format) {
1226             if (format == CF_ENHMETAFILE || format == CF_DIB || format == CF_BITMAP)
1227                 break;
1228             format = EnumClipboardFormats(format);
1229         }
1230         CloseClipboard();
1231         
1232         if (format == CF_ENHMETAFILE)
1233             return CLIPBOARD_WIN32_EMF_TARGET;
1234         if (format == CF_DIB || format == CF_BITMAP)
1235             return CLIPBOARD_GDK_PIXBUF_TARGET;
1236     }
1237     
1238     if (IsClipboardFormatAvailable(CF_ENHMETAFILE))
1239         return CLIPBOARD_WIN32_EMF_TARGET;
1240 #endif
1241     if (_clipboard->wait_is_image_available())
1242         return CLIPBOARD_GDK_PIXBUF_TARGET;
1243     if (_clipboard->wait_is_text_available())
1244         return CLIPBOARD_TEXT_TARGET;
1246     return "";
1250 /**
1251  * @brief Set the clipboard targets to reflect the mimetypes Inkscape can output
1252  */
1253 void ClipboardManagerImpl::_setClipboardTargets()
1255     Inkscape::Extension::DB::OutputList outlist;
1256     Inkscape::Extension::db.get_output_list(outlist);
1257     std::list<Gtk::TargetEntry> target_list;
1258     bool plaintextSet = false;
1259     for (Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin() ; out != outlist.end() ; ++out) {
1260         if ( !(*out)->deactivated() ) {
1261             Glib::ustring mime = (*out)->get_mimetype();
1262             if (mime != CLIPBOARD_TEXT_TARGET) {
1263                 if ( !plaintextSet && (mime.find("svg") == Glib::ustring::npos) ) {
1264                     target_list.push_back(Gtk::TargetEntry(CLIPBOARD_TEXT_TARGET));
1265                     plaintextSet = true;
1266                 }
1267                 target_list.push_back(Gtk::TargetEntry(mime));
1268             }
1269         }
1270     }
1272     // Add PNG export explicitly since there is no extension for this...
1273     // On Windows, GTK will also present this as a CF_DIB/CF_BITMAP
1274     target_list.push_back(Gtk::TargetEntry( "image/png" ));
1276     _clipboard->set(target_list,
1277         sigc::mem_fun(*this, &ClipboardManagerImpl::_onGet),
1278         sigc::mem_fun(*this, &ClipboardManagerImpl::_onClear));
1280 #ifdef WIN32
1281     // If the "image/x-emf" target handled by the emf extension would be
1282     // presented as a CF_ENHMETAFILE automatically (just like an "image/bmp"
1283     // is presented as a CF_BITMAP) this code would not be needed.. ???
1284     // Or maybe there is some other way to achieve the same?
1286     // Note: Metafile is the only format that is rendered and stored in clipboard
1287     // on Copy, all other formats are rendered only when needed by a Paste command.
1289     // FIXME: This should at least be rewritten to use "delayed rendering".
1290     //        If possible make it delayed rendering by using GTK API only.
1292     if (OpenClipboard(NULL)) {
1293         if ( _clipboardSPDoc != NULL ) {
1294             const Glib::ustring target = CLIPBOARD_WIN32_EMF_MIME;
1296             Inkscape::Extension::DB::OutputList outlist;
1297             Inkscape::Extension::db.get_output_list(outlist);
1298             Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
1299             for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out);
1300             if ( out != outlist.end() ) {
1301                 // FIXME: Temporary hack until we add support for memory output.
1302                 // Save to a temporary file, read it back and then set the clipboard contents
1303                 gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export.emf", NULL );
1305                 try {
1306                     (*out)->save(_clipboardSPDoc, filename);
1307                     HENHMETAFILE hemf = GetEnhMetaFileA(filename);
1308                     if (hemf) {
1309                         SetClipboardData(CF_ENHMETAFILE, hemf);
1310                         DeleteEnhMetaFile(hemf);
1311                     }
1312                 } catch (...) {
1313                 }
1314                 g_unlink(filename); // delete the temporary file
1315                 g_free(filename);
1316             }
1317         }
1318         CloseClipboard();
1319     }
1320 #endif
1324 /**
1325  * @brief Set the string representation of a 32-bit RGBA color as the clipboard contents
1326  */
1327 void ClipboardManagerImpl::_setClipboardColor(guint32 color)
1329     gchar colorstr[16];
1330     g_snprintf(colorstr, 16, "%08x", color);
1331     _clipboard->set_text(colorstr);
1335 /**
1336  * @brief Put a notification on the mesage stack
1337  */
1338 void ClipboardManagerImpl::_userWarn(SPDesktop *desktop, char const *msg)
1340     desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, msg);
1345 /* #######################################
1346           ClipboardManager class
1347    ####################################### */
1349 ClipboardManager *ClipboardManager::_instance = NULL;
1351 ClipboardManager::ClipboardManager() {}
1352 ClipboardManager::~ClipboardManager() {}
1353 ClipboardManager *ClipboardManager::get()
1355     if ( _instance == NULL )
1356         _instance = new ClipboardManagerImpl;
1357     return _instance;
1360 } // namespace Inkscape
1361 } // namespace IO
1363 /*
1364   Local Variables:
1365   mode:c++
1366   c-file-style:"stroustrup"
1367   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1368   indent-tabs-mode:nil
1369   fill-column:99
1370   End:
1371 */
1372 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :