Code

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