Code

system clipboard support (bug #170185) from Chris Kosiński
[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 #ifdef HAVE_CONFIG_H
19 # include "config.h"
20 #endif
21 #include "path-prefix.h"
23 #include "ui/clipboard.h"
25 // TODO: reduce header bloat if possible
27 #include <list>
28 #include <algorithm>
29 #include <gtkmm/clipboard.h>
30 #include <glibmm/ustring.h>
31 #include <glibmm/i18n.h>
32 #include <glib/gstdio.h> // for g_file_set_contents etc., used in _onGet and paste
33 #include "gc-core.h"
34 #include "xml/repr.h"
35 #include "inkscape.h"
36 #include "io/stringstream.h"
37 #include "desktop.h"
38 #include "desktop-handles.h"
39 #include "desktop-style.h" // for sp_desktop_set_style, used in _pasteStyle
40 #include "document.h"
41 #include "document-private.h"
42 #include "selection.h"
43 #include "message-stack.h"
44 #include "context-fns.h"
45 #include "dropper-context.h" // used in copy()
46 #include "style.h"
47 #include "extension/db.h" // extension database
48 #include "extension/input.h"
49 #include "extension/output.h"
50 #include "selection-chemistry.h"
51 #include "libnr/nr-rect.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 "live_effects/lpeobject.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 "prefs-utils.h" // for prefs_get_string_attribute, used in _pasteImage
73 #include "text-context.h"
74 #include "text-editing.h"
75 #include "tools-switch.h"
77 /// @brief Made up mimetype to represent Gdk::Pixbuf clipboard contents
78 #define CLIPBOARD_GDK_PIXBUF_TARGET "image/x-gdk-pixbuf"
80 #define CLIPBOARD_TEXT_TARGET "text/plain"
82 namespace Inkscape {
83 namespace UI {
86 /**
87  * @brief Default implementation of the clipboard manager
88  */
89 class ClipboardManagerImpl : public ClipboardManager {
90 public:
91     virtual void copy();
92     virtual void copyPathParameter(Inkscape::LivePathEffect::PathParam *);
93     virtual bool paste(bool in_place);
94     virtual bool pasteStyle();
95     virtual bool pasteSize(bool, bool, bool);
96     virtual bool pastePathEffect();
97     virtual Glib::ustring getPathParameter();
98     
99     ClipboardManagerImpl();
100     ~ClipboardManagerImpl();
101     
102 private:
103     void _copySelection(Inkscape::Selection *);
104     void _copyUsedDefs(SPItem *);
105     void _copyGradient(SPGradient *);
106     void _copyPattern(SPPattern *);
107     void _copyTextPath(SPTextPath *);
108     Inkscape::XML::Node *_copyNode(Inkscape::XML::Node *, Inkscape::XML::Document *, Inkscape::XML::Node *);
109     
110     void _pasteDocument(SPDocument *, bool in_place);
111     void _pasteDefs(SPDocument *);
112     bool _pasteImage();
113     bool _pasteText();
114     SPCSSAttr *_parseColor(const Glib::ustring &);
115     void _applyPathEffect(SPItem *, gchar const *);
116     SPDocument *_retrieveClipboard(Glib::ustring = "");
117     
118     // clipboard callbacks
119     void _onGet(Gtk::SelectionData &, guint);
120     void _onClear();
121     
122     // various helpers
123     void _createInternalClipboard();
124     void _discardInternalClipboard();
125     Inkscape::XML::Node *_createClipNode();
126     NR::scale _getScale(Geom::Point &, Geom::Point &, NR::Rect &, bool, bool);
127     Glib::ustring _getBestTarget();
128     void _setClipboardTargets();
129     void _setClipboardColor(guint32);
130     void _userWarn(SPDesktop *, char const *);
132     // private properites
133     SPDocument *_clipboardSPDoc; ///< Document that stores the clipboard until someone requests it
134     Inkscape::XML::Node *_defs; ///< Reference to the clipboard document's defs node
135     Inkscape::XML::Node *_root; ///< Reference to the clipboard's root node
136     Inkscape::XML::Node *_clipnode; ///< The node that holds extra information
137     Inkscape::XML::Document *_doc; ///< Reference to the clipboard's Inkscape::XML::Document
138     
139     Glib::RefPtr<Gtk::Clipboard> _clipboard; ///< Handle to the system wide clipboard - for convenience
140     std::list<Glib::ustring> _preferred_targets; ///< List of supported clipboard targets
141 };
144 ClipboardManagerImpl::ClipboardManagerImpl()
145     : _clipboardSPDoc(NULL),
146       _defs(NULL),
147       _root(NULL),
148       _clipnode(NULL),
149       _doc(NULL),
150       _clipboard( Gtk::Clipboard::get() )
152     // push supported clipboard targets, in order of preference
153     _preferred_targets.push_back("image/x-inkscape-svg");
154     _preferred_targets.push_back("image/svg+xml");
155     _preferred_targets.push_back("image/svg+xml-compressed");
156 #ifdef WIN32
157     _preferred_targets.push_back("image/x-emf");
158 #endif
159     _preferred_targets.push_back("application/pdf");
160     _preferred_targets.push_back("image/x-adobe-illustrator");
164 ClipboardManagerImpl::~ClipboardManagerImpl() {}
167 /**
168  * @brief Copy selection contents to the clipboard
169  */
170 void ClipboardManagerImpl::copy()
172     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
173     if ( desktop == NULL ) return;
174     Inkscape::Selection *selection = sp_desktop_selection(desktop);
175     
176     // Special case for when the gradient dragger is active - copies gradient color
177     if (desktop->event_context->get_drag()) {
178         GrDrag *drag = desktop->event_context->get_drag();
179         if (drag->hasSelection()) {
180             _setClipboardColor(drag->getColor());
181             _discardInternalClipboard();
182             return;
183         }
184     }
185     
186     // Special case for when the color picker ("dropper") is active - copies color under cursor
187     if (tools_isactive(desktop, TOOLS_DROPPER)) {
188         _setClipboardColor(sp_dropper_context_get_color(desktop->event_context));
189         _discardInternalClipboard();
190         return;
191     }
192     
193     // Special case for when the text tool is active - if some text is selected, copy plain text,
194     // not the object that holds it
195     if (tools_isactive(desktop, TOOLS_TEXT)) {
196         Glib::ustring selected_text = sp_text_get_selected_text(desktop->event_context);
197         if (!selected_text.empty()) {
198             _clipboard->set_text(selected_text);
199             _discardInternalClipboard();
200             return;
201         }
202     }
203     
204     if (selection->isEmpty()) {  // check whether something is selected
205         _userWarn(desktop, _("Nothing was copied."));
206         return;
207     }
208     _discardInternalClipboard();
209     
210     _createInternalClipboard();   // construct a new clipboard document
211     _copySelection(selection);   // copy all items in the selection to the internal clipboard
212     fit_canvas_to_drawing(_clipboardSPDoc);
213     
214     _setClipboardTargets();
218 /**
219  * @brief Copy a Live Path Effect path parameter to the clipboard
220  * @param pp The path parameter to store in the clipboard
221  */
222 void ClipboardManagerImpl::copyPathParameter(Inkscape::LivePathEffect::PathParam *pp)
224     if ( pp == NULL ) return;
225     gchar *svgd = pp->param_writeSVGValue();
226     if ( svgd == NULL || *svgd == '\0' ) return;
227     
228     _discardInternalClipboard();
229     _createInternalClipboard();
230     
231     Inkscape::XML::Node *pathnode = _doc->createElement("svg:path");
232     pathnode->setAttribute("d", svgd);
233     g_free(svgd);
234     _root->appendChild(pathnode);
235     Inkscape::GC::release(pathnode);
236     
237     fit_canvas_to_drawing(_clipboardSPDoc);
238     _setClipboardTargets();
241 /**
242  * @brief Paste from the system clipboard into the active desktop
243  * @param in_place Whether to put the contents where they were when copied
244  */
245 bool ClipboardManagerImpl::paste(bool in_place)
247     // do any checking whether we really are able to paste before requesting the contents
248     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
249     if ( desktop == NULL ) return false;
250     if ( Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false ) return false;
251     
252     Glib::ustring target = _getBestTarget();
253     
254     // Special cases of clipboard content handling go here 00ff00
255     // Note that target priority is determined in _getBestTarget.
256     // TODO: Handle x-special/gnome-copied-files and text/uri-list to support pasting files
257     
258     // if there is an image on the clipboard, paste it
259     if ( target == CLIPBOARD_GDK_PIXBUF_TARGET ) return _pasteImage();
260     // if there's only text, paste it into a selected text object or create a new one
261     if ( target == CLIPBOARD_TEXT_TARGET ) return _pasteText();
262     
263     // otherwise, use the import extensions
264     SPDocument *tempdoc = _retrieveClipboard(target);
265     if ( tempdoc == NULL ) {
266         _userWarn(desktop, _("Nothing on the clipboard."));
267         return false;
268     }
269     
270     _pasteDocument(tempdoc, in_place);
271     sp_document_unref(tempdoc);
272     
273     return true;
277 /**
278  * @brief Implements the Paste Style action
279  */
280 bool ClipboardManagerImpl::pasteStyle()
282     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
283     if (desktop == NULL) return false;
285     // check whether something is selected
286     Inkscape::Selection *selection = sp_desktop_selection(desktop);
287     if (selection->isEmpty()) {
288         _userWarn(desktop, _("Select <b>object(s)</b> to paste style to."));
289         return false;
290     }
291     
292     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
293     if ( tempdoc == NULL ) {
294         _userWarn(desktop, _("No style on the clipboard."));
295         return false;
296     }
297     
298     Inkscape::XML::Node
299         *root = sp_document_repr_root(tempdoc),
300         *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
301     
302     bool pasted = false;
303     
304     if (clipnode) {
305         _pasteDefs(tempdoc);
306         SPCSSAttr *style = sp_repr_css_attr(clipnode, "style");
307         sp_desktop_set_style(desktop, style);
308         pasted = true;
309     }
310     else {
311         _userWarn(desktop, _("No style on the clipboard."));
312     }
314     sp_document_unref(tempdoc);
315     return pasted;
319 /**
320  * @brief Resize the selection or each object in the selection to match the clipboard's size
321  * @param separately Whether to scale each object in the selection separately
322  * @param apply_x Whether to scale the width of objects / selection
323  * @param apply_y Whether to scale the height of objects / selection
324  */
325 bool ClipboardManagerImpl::pasteSize(bool separately, bool apply_x, bool apply_y)
327     if(!apply_x && !apply_y) return false; // pointless parameters
328     
329     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
330     if ( desktop == NULL ) return false;
331     Inkscape::Selection *selection = sp_desktop_selection(desktop);
332     if (selection->isEmpty()) {
333         _userWarn(desktop, _("Select <b>object(s)</b> to paste size to."));
334         return false;
335     }
336     
337     // FIXME: actually, this should accept arbitrary documents
338     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
339     if ( tempdoc == NULL ) {
340         _userWarn(desktop, _("No size on the clipboard."));
341         return false;
342     }
343     
344     // retrieve size ifomration from the clipboard
345     Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
346     Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
347     bool pasted = false;
348     if (clipnode) {
349         Geom::Point min, max;
350         sp_repr_get_point(clipnode, "min", &min);
351         sp_repr_get_point(clipnode, "max", &max);
352         
353         // resize each object in the selection
354         if (separately) {
355             for (GSList *i = const_cast<GSList*>(selection->itemList()) ; i ; i = i->next) {
356                 SPItem *item = SP_ITEM(i->data);
357                 NR::Maybe<NR::Rect> obj_size = sp_item_bbox_desktop(item);
358                 if ( !obj_size || obj_size->isEmpty() ) continue;
359                 sp_item_scale_rel(item, _getScale(min, max, *obj_size, apply_x, apply_y));
360             }
361         }
362         // resize the selection as a whole
363         else {
364             NR::Maybe<NR::Rect> sel_size = selection->bounds();
365             if ( sel_size && !sel_size->isEmpty() ) {
366                 sp_selection_scale_relative(selection, sel_size->midpoint(),
367                     _getScale(min, max, *sel_size, apply_x, apply_y));
368             }
369         }
370         pasted = true;
371     }
372     sp_document_unref(tempdoc);
373     return pasted;
377 /**
378  * @brief Applies a path effect from the clipboard to the selected path
379  */
380 bool ClipboardManagerImpl::pastePathEffect()
382     /** @todo FIXME: pastePathEffect crashes when moving the path with the applied effect,
383         segfaulting in fork_private_if_necessary(). */
384     
385     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
386     if ( desktop == NULL ) return false;
387     Inkscape::Selection *selection = sp_desktop_selection(desktop);
388     if (selection->isEmpty()) {
389         _userWarn(desktop, _("Select <b>object(s)</b> to paste live path effect to."));
390         return false;
391     }
392     
393     Inkscape::XML::Node *root, *clipnode;
394     gchar const *effect;
395     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
396     if ( tempdoc == NULL ) goto no_effect;
397     
398     root = sp_document_repr_root(tempdoc),
399     clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
400     if ( clipnode == NULL ) goto no_effect;
401     effect = clipnode->attribute("inkscape:path-effect");
402     if ( effect == NULL ) goto no_effect;
403     
404     _pasteDefs(tempdoc);
405     for (GSList *item = const_cast<GSList *>(selection->itemList()) ; item ; item = item->next) {
406         _applyPathEffect(reinterpret_cast<SPItem*>(item->data), effect);
407     }
408     return true;
409     
410     no_effect:
411     _userWarn(desktop, _("No effect on the clipboard."));
412     return false;
416 /**
417  * @brief Get LPE path data from the clipboard
418  * @return The retrieved path data (contents of the d attribute), or "" if no path was found
419  */
420 Glib::ustring ClipboardManagerImpl::getPathParameter()
422     SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
423     if ( tempdoc == NULL ) {
424         _userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
425         return "";
426     }
427     Inkscape::XML::Node
428         *root = sp_document_repr_root(tempdoc),
429         *path = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
430     if ( path == NULL ) {
431         _userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
432         sp_document_unref(tempdoc);
433         return "";
434     }
435     gchar const *svgd = path->attribute("d");
436     return svgd;
440 /**
441  * @brief Iterate over a list of items and copy them to the clipboard.
442  */
443 void ClipboardManagerImpl::_copySelection(Inkscape::Selection *selection)
445     GSList const *items = selection->itemList();
446     // copy the defs used by all items
447     for (GSList *i = const_cast<GSList *>(items) ; i != NULL ; i = i->next) {
448         _copyUsedDefs(SP_ITEM (i->data));
449     }
450     
451     // copy the representation of the items
452     GSList *sorted_items = g_slist_copy(const_cast<GSList *>(items));
453     sorted_items = g_slist_sort(sorted_items, (GCompareFunc) sp_object_compare_position);
454     
455     for (GSList *i = sorted_items ; i ; i = i->next) {
456         if (!SP_IS_ITEM(i->data)) continue;
457         Inkscape::XML::Node *obj = SP_OBJECT_REPR(i->data);
458         Inkscape::XML::Node *obj_copy = _copyNode(obj, _doc, _root);
460         // copy complete inherited style
461         SPCSSAttr *css = sp_repr_css_attr_inherited(obj, "style");
462         sp_repr_css_set(obj_copy, css, "style");
463         sp_repr_css_attr_unref(css);
465         // write the complete accumulated transform passed to us
466         // (we're dealing with unattached representations, so we write to their attributes
467         // instead of using sp_item_set_transform)
468         gchar *transform_str = sp_svg_transform_write(sp_item_i2doc_affine(SP_ITEM(i->data)));
469         obj_copy->setAttribute("transform", transform_str);
470         g_free(transform_str);
471     }
472     
473     // copy style for Paste Style action
474     if (sorted_items) {
475         if(SP_IS_ITEM(sorted_items->data)) {
476             SPCSSAttr *style = take_style_from_item((SPItem *) sorted_items->data);
477             sp_repr_css_set(_clipnode, style, "style");
478             sp_repr_css_attr_unref(style);
479         }
480         
481         // copy path effect from the first path
482         if (SP_IS_OBJECT(sorted_items->data)) {
483             gchar const *effect = SP_OBJECT_REPR(sorted_items->data)->attribute("inkscape:path-effect");
484             if (effect) {
485                 _clipnode->setAttribute("inkscape:path-effect", effect);
486             }
487         }
488     }
489     
490     NR::Maybe<NR::Rect> size = selection->bounds();
491     if (size) {
492         sp_repr_set_point(_clipnode, "min", size->min().to_2geom());
493         sp_repr_set_point(_clipnode, "max", size->max().to_2geom());
494     }
495     
496     g_slist_free(sorted_items);
500 /**
501  * @brief Recursively copy all the definitions used by a given item to the clipboard defs
502  */
503 void ClipboardManagerImpl::_copyUsedDefs(SPItem *item)
505     // copy fill and stroke styles (patterns and gradients)
506     SPStyle *style = SP_OBJECT_STYLE(item);
507     
508     if (style && (style->fill.isPaintserver())) {
509         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
510         if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
511             _copyGradient(SP_GRADIENT(server));
512         if (SP_IS_PATTERN(server))
513             _copyPattern(SP_PATTERN(server));
514     }
515     if (style && (style->stroke.isPaintserver())) {
516         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
517         if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
518             _copyGradient(SP_GRADIENT(server));
519         if (SP_IS_PATTERN(server))
520             _copyPattern(SP_PATTERN(server));
521     }
522     
523     // For shapes, copy all of the shape's markers
524     if (SP_IS_SHAPE(item)) {
525         SPShape *shape = SP_SHAPE (item);
526         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
527             if (shape->marker[i]) {
528                 _copyNode(SP_OBJECT_REPR(SP_OBJECT(shape->marker[i])), _doc, _defs);
529             }
530         }
531         // Also copy live effects if applicable
532         if (sp_shape_has_path_effect(shape)) {
533             _copyNode(SP_OBJECT_REPR(SP_OBJECT(sp_shape_get_livepatheffectobject(shape))), _doc, _defs);
534         }
535     }
536     // For 3D boxes, copy perspectives
537     if (SP_IS_BOX3D(item)) {
538         _copyNode(SP_OBJECT_REPR(SP_OBJECT(box3d_get_perspective(SP_BOX3D(item)))), _doc, _defs);
539     }
540     // Copy text paths
541     if (SP_IS_TEXT_TEXTPATH(item)) {
542         _copyTextPath(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
543     }
544     // Copy clipping objects
545     if (item->clip_ref->getObject()) {
546         _copyNode(SP_OBJECT_REPR(item->clip_ref->getObject()), _doc, _defs);
547     }
548     // Copy mask objects
549     if (item->mask_ref->getObject()) {
550         SPObject *mask = item->mask_ref->getObject();
551         _copyNode(SP_OBJECT_REPR(mask), _doc, _defs);
552         // recurse into the mask for its gradients etc.
553         for (SPObject *o = SP_OBJECT(mask)->children ; o != NULL ; o = o->next) {
554             if (SP_IS_ITEM(o))
555                 _copyUsedDefs(SP_ITEM(o));
556         }
557     }
558     // Copy filters
559     if (style->getFilter()) {
560         SPObject *filter = style->getFilter();
561         if (SP_IS_FILTER(filter)) {
562             _copyNode(SP_OBJECT_REPR(filter), _doc, _defs);
563         }
564     }
566     // recurse
567     for (SPObject *o = SP_OBJECT(item)->children ; o != NULL ; o = o->next) {
568         if (SP_IS_ITEM(o))
569             _copyUsedDefs(SP_ITEM(o));
570     }
574 /**
575  * @brief Copy a single gradient to the clipboard's defs element
576  */
577 void ClipboardManagerImpl::_copyGradient(SPGradient *gradient)
579     while (gradient) {
580         // climb up the refs, copying each one in the chain
581         _copyNode(SP_OBJECT_REPR(gradient), _doc, _defs);
582         gradient = gradient->ref->getObject();
583     }
587 /**
588  * @brief Copy a single pattern to the clipboard document's defs element
589  */
590 void ClipboardManagerImpl::_copyPattern(SPPattern *pattern)
592     // climb up the references, copying each one in the chain
593     while (pattern) {
594         _copyNode(SP_OBJECT_REPR(pattern), _doc, _defs);
596         // items in the pattern may also use gradients and other patterns, so recurse
597         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL ; child = SP_OBJECT_NEXT(child) ) {
598             if (!SP_IS_ITEM (child)) continue;
599             _copyUsedDefs(SP_ITEM(child));
600         }
601         pattern = pattern->ref->getObject();
602     }
606 /**
607  * @brief Copy a text path to the clipboard's defs element
608  */
609 void ClipboardManagerImpl::_copyTextPath(SPTextPath *tp)
611     SPItem *path = sp_textpath_get_path_item(tp);
612     if(!path) return;
613     Inkscape::XML::Node *path_node = SP_OBJECT_REPR(path);
614     
615     // Do not copy the text path to defs if it's already copied
616     if(sp_repr_lookup_child(_root, "id", path_node->attribute("id"))) return;
617     _copyNode(path_node, _doc, _defs);
621 /**
622  * @brief Copy a single XML node from one document to another
623  * @param node The node to be copied
624  * @param target_doc The document to which the node is to be copied
625  * @param parent The node in the target document which will become the parent of the copied node
626  * @return Pointer to the copied node
627  */
628 Inkscape::XML::Node *ClipboardManagerImpl::_copyNode(Inkscape::XML::Node *node, Inkscape::XML::Document *target_doc, Inkscape::XML::Node *parent)
630     Inkscape::XML::Node *dup = node->duplicate(target_doc);
631     parent->appendChild(dup);
632     Inkscape::GC::release(dup);
633     return dup;
637 /**
638  * @brief Paste the contents of a document into the active desktop
639  * @param clipdoc The document to paste
640  * @param in_place Whether to paste the selection where it was when copied
641  * @pre @c clipdoc is not empty and items can be added to the current layer
642  */
643 void ClipboardManagerImpl::_pasteDocument(SPDocument *clipdoc, bool in_place)
645     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
646     SPDocument *target_document = sp_desktop_document(desktop);
647     Inkscape::XML::Node
648         *root = sp_document_repr_root(clipdoc),
649         *target_parent = SP_OBJECT_REPR(desktop->currentLayer());
650     Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
651     
652     // copy definitions
653     _pasteDefs(clipdoc);
654     
655     // copy objects
656     GSList *pasted_objects = NULL;
657     for (Inkscape::XML::Node *obj = root->firstChild() ; obj ; obj = obj->next()) {
658         // Don't copy metadata, defs, named views and internal clipboard contents to the document
659         if (!strcmp(obj->name(), "svg:defs")) continue;
660         if (!strcmp(obj->name(), "svg:metadata")) continue;
661         if (!strcmp(obj->name(), "sodipodi:namedview")) continue;
662         if (!strcmp(obj->name(), "inkscape:clipboard")) continue;
663         Inkscape::XML::Node *obj_copy = _copyNode(obj, target_xmldoc, target_parent);
664         pasted_objects = g_slist_prepend(pasted_objects, (gpointer) obj_copy);
665     }
666     
667     Inkscape::Selection *selection = sp_desktop_selection(desktop);
668     selection->setReprList(pasted_objects);
669     
670     // move the selection to the right position
671     if(in_place)
672     {
673         Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
674         if (clipnode) {
675             Geom::Point min, max;
676             sp_repr_get_point(clipnode, "min", &min);
677             sp_repr_get_point(clipnode, "max", &max);
678             
679             // this formula was discovered empyrically
680             min[Geom::Y] += ((max[Geom::Y] - min[Geom::Y]) - sp_document_height(target_document));
681             sp_selection_move_relative(selection, NR::Point(min));
682         }
683     }
684     // copied from former sp_selection_paste in selection-chemistry.cpp
685     else {
686         sp_document_ensure_up_to_date(target_document);
687         NR::Maybe<NR::Rect> sel_size = selection->bounds();
689         NR::Point m( desktop->point() );
690         if (sel_size) {
691             m -= sel_size->midpoint();
692         }
693         sp_selection_move_relative(selection, m);
694     }
695     
696     g_slist_free(pasted_objects);
700 /**
701  * @brief Paste SVG defs from the document retrieved from the clipboard into the active document
702  * @param clipdoc The document to paste
703  * @pre @c clipdoc != NULL and pasting into the active document is possible
704  */
705 void ClipboardManagerImpl::_pasteDefs(SPDocument *clipdoc)
707     // boilerplate vars copied from _pasteDocument
708     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
709     SPDocument *target_document = sp_desktop_document(desktop);
710     Inkscape::XML::Node
711         *root = sp_document_repr_root(clipdoc),
712         *defs = sp_repr_lookup_name(root, "svg:defs", 1),
713         *target_defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(target_document));
714     Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
715         
716     for (Inkscape::XML::Node *def = defs->firstChild() ; def ; def = def->next()) {
717         /// @todo TODO: implement def id collision resolution in ClipboardManagerImpl::_pasteDefs()
718         
719         /*
720         // simplistic solution: when a collision occurs, add "a" to id until it's unique
721         Glib::ustring pasted_id = def->attribute("id");
722         if ( pasted_id.empty() ) continue; // defs without id are useless
723         Glib::ustring pasted_id_original = pasted_id;
724         
725         while(sp_repr_lookup_child(target_defs, "id", pasted_id.data())) {
726             pasted_id.append("a");
727         }
728         
729         if ( pasted_id != pasted_id_original ) {
730             def->setAttribute("id", pasted_id.data());
731             // Update the id in the rest of the document so there are no dangling references
732             // How to do that?
733             _changeIdReferences(clipdoc, pasted_id_original, pasted_id);
734         }
735         */
736         if (sp_repr_lookup_child(target_defs, "id", def->attribute("id")))
737             continue; // skip duplicate defs - temporary non-solution
738         
739         _copyNode(def, target_xmldoc, target_defs);
740     }
744 /**
745  * @brief Retrieve a bitmap image from the clipboard and paste it into the active document
746  */
747 bool ClipboardManagerImpl::_pasteImage()
749     SPDocument *doc = SP_ACTIVE_DOCUMENT;
750     if ( doc == NULL ) return false;
751     
752     // retrieve image data
753     Glib::RefPtr<Gdk::Pixbuf> img = _clipboard->wait_for_image();
754     if (!img) return false;
756     // Very stupid hack: Write into a file, then import the file into the document.
757     // To avoid using tmpfile and POSIX file handles, make the filename based on current time.
758     // This wasn't my idea, I just copied this from selection-chemistry.cpp
759     // and just can't think of something saner at the moment. Pasting more than
760     // one image per second will overwrite the image.
761     // However, I don't think anyone is able to copy a _different_ image into inkscape
762     // in 1 second.
763     time_t rawtime;
764     char image_filename[128];
765     gchar const *save_folder;
767     time(&rawtime);
768     strftime(image_filename, 128, "inkscape_pasted_image_%Y%m%d_%H%M%S.png", localtime( &rawtime ));
769     save_folder = (gchar const *) prefs_get_string_attribute("dialogs.save_as", "path");
770     
771     gchar *image_path = g_build_filename(save_folder, image_filename, NULL);
772     img->save(image_path, "png");
773     file_import(doc, image_path, NULL);
774     g_free(image_path);
776     return true;
779 /**
780  * @brief Paste text into the selected text object or create a new one to hold it
781  */
782 bool ClipboardManagerImpl::_pasteText()
784     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
785     if ( desktop == NULL ) return false;
786     
787     // if the text editing tool is active, paste the text into the active text object
788     if (tools_isactive(desktop, TOOLS_TEXT))
789         return sp_text_paste_inline(desktop->event_context);
790     
791     // try to parse the text as a color and, if successful, apply it as the current style
792     SPCSSAttr *css = _parseColor(_clipboard->wait_for_text());
793     if (css) {
794         sp_desktop_set_style(desktop, css);
795         return true;
796     }
797     
798     return false;
802 /**
803  * @brief Attempt to parse the passed string as a hexadecimal RGB or RGBA color
804  * @param text The Glib::ustring to parse
805  * @return New CSS style representation if the parsing was successful, NULL otherwise
806  */
807 SPCSSAttr *ClipboardManagerImpl::_parseColor(const Glib::ustring &text)
809     Glib::ustring::size_type len = text.bytes();
810     char *str = const_cast<char *>(text.data());
811     bool attempt_alpha = false;
812     if ( !str || ( *str == '\0' ) ) return NULL; // this is OK due to boolean short-circuit
813     
814     // those conditionals guard against parsing e.g. the string "fab" as "fab000"
815     // (incomplete color) and "45fab71" as "45fab710" (incomplete alpha)
816     if ( *str == '#' ) {
817         if ( len < 7 ) return NULL;
818         if ( len >= 9 ) attempt_alpha = true;
819     } else {
820         if ( len < 6 ) return NULL;
821         if ( len >= 8 ) attempt_alpha = true;
822     }
823     
824     unsigned int color = 0, alpha = 0xff;
825     
826     // skip a leading #, if present
827     if ( *str == '#' ) ++str;
828     
829     // try to parse first 6 digits
830     int res = sscanf(str, "%6x", &color);
831     if ( res && ( res != EOF ) ) {
832         if (attempt_alpha) {// try to parse alpha if there's enough characters
833             sscanf(str + 6, "%2x", &alpha);
834             if ( !res || res == EOF ) alpha = 0xff;
835         }
837         SPCSSAttr *color_css = sp_repr_css_attr_new();
838         
839         // print and set properties
840         gchar color_str[16];
841         g_snprintf(color_str, 16, "#%06x", color);
842         sp_repr_css_set_property(color_css, "fill", color_str);
843         
844         float opacity = static_cast<float>(alpha)/static_cast<float>(0xff);
845         if (opacity > 1.0) opacity = 1.0; // safeguard
846         Inkscape::CSSOStringStream opcss;
847         opcss << opacity;
848         sp_repr_css_set_property(color_css, "fill-opacity", opcss.str().data());
849         return color_css;
850     }
851     return NULL;
855 /**
856  * @brief Applies a pasted path effect to a given item
857  */
858 void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effect)
860     if ( item == NULL ) return;
861     
862     if (SP_IS_SHAPE(item))
863     {
864         SPShape *shape = SP_SHAPE(item);
865         SPObject *obj = sp_uri_reference_resolve(_clipboardSPDoc, effect);
866         if (!obj) return;
867         // if the effect is not used by anyone, we might as well take it
868         LivePathEffectObject *lpeobj = LIVEPATHEFFECT(obj)->fork_private_if_necessary(1);
869         sp_shape_set_path_effect(shape, lpeobj);
871         // set inkscape:original-d for paths. the other shapes don't need this
872         if (SP_IS_PATH(item)) {
873             Inkscape::XML::Node *pathrepr = SP_OBJECT_REPR(item);
874             if (!pathrepr->attribute("inkscape:original-d")) {
875                 pathrepr->setAttribute("inkscape:original-d", pathrepr->attribute("d"));
876             }
877         }
878     }
879     else if (SP_IS_GROUP(item))
880     {
881         for (SPObject *child = sp_object_first_child(SP_OBJECT(item)) ;
882             child != NULL ; child = SP_OBJECT_NEXT(child))
883         {
884             if (!SP_IS_ITEM(child)) continue;
885             _applyPathEffect(SP_ITEM(child), effect);
886         }
887     }
891 /**
892  * @brief Retrieve the clipboard contents as a document
893  * @return Clipboard contents converted to SPDocument, or NULL if no suitable content was present
894  */
895 SPDocument *ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_target)
897     Glib::ustring best_target;
898     if ( required_target == "" ) best_target = _getBestTarget();
899     else best_target = required_target;
901     if ( best_target == "" ) {
902         return NULL;
903     }
904     
905     // doing this synchronously makes better sense
906     Gtk::SelectionData sel = _clipboard->wait_for_contents(best_target);
907     
908     Glib::ustring target = sel.get_target();
909     
910     // there is no specific plain SVG input extension, so if we can paste the Inkscape SVG format,
911     // we use the image/svg+xml mimetype to look up the input extension
912     if(target == "image/x-inkscape-svg")
913         target = "image/svg+xml";
914     
915     Inkscape::Extension::DB::InputList inlist;
916     Inkscape::Extension::db.get_input_list(inlist);
917     Inkscape::Extension::DB::InputList::const_iterator in = inlist.begin();
918     for (; in != inlist.end() && target != (*in)->get_mimetype() ; ++in);
919     if ( in == inlist.end() ) return NULL; // this shouldn't happen unless _getBestTarget returns something bogus
920     
921     // FIXME: Temporary hack until we add memory input.
922     // Save the clipboard contents to some file, then read it
923     gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-import", NULL );
924     g_file_set_contents(filename, (const gchar *) sel.get_data(), sel.get_length(), NULL);
925     
926     SPDocument *tempdoc = (*in)->open(filename);
927     g_unlink(filename);
928     g_free(filename);
929     
930     return tempdoc;
934 /**
935  * @brief Callback called when some other application requests data from Inkscape
936  *
937  * Finds a suitable output extension to save the internal clipboard document,
938  * then saves it to memory and sets the clipboard contents.
939  */
940 void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint info)
942     g_assert( _clipboardSPDoc != NULL );
943     
944     const Glib::ustring target = sel.get_target();
945     if(target == "") return; // this shouldn't happen
946     
947     Inkscape::Extension::DB::OutputList outlist;
948     Inkscape::Extension::db.get_output_list(outlist);
949     Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
950     for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out);
951     if ( out == outlist.end() ) return; // this also shouldn't happen
952     
953     // FIXME: Temporary hack until we add support for memory output.
954     // Save to a temporary file, read it back and then set the clipboard contents
955     gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export", NULL );
956     gsize len; gchar *data;
957     
958     (*out)->save(_clipboardSPDoc, filename);
959     g_file_get_contents(filename, &data, &len, NULL);
960     g_unlink(filename); // delete the temporary file
961     g_free(filename);
962     
963     sel.set(8, (guint8 const *) data, len);
967 /**
968  * @brief Callback when someone else takes the clipboard
969  *
970  * When the clipboard owner changes, this callback clears the internal clipboard document
971  * to reduce memory usage.
972  */
973 void ClipboardManagerImpl::_onClear()
975     // why is this called before _onGet???
976     //_discardInternalClipboard();
980 /**
981  * @brief Creates an internal clipboard document from scratch
982  */
983 void ClipboardManagerImpl::_createInternalClipboard()
985     if ( _clipboardSPDoc == NULL ) {
986         _clipboardSPDoc = sp_document_new(NULL, false, true);
987         //g_assert( _clipboardSPDoc != NULL );
988         _defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(_clipboardSPDoc));
989         _doc = sp_document_repr_doc(_clipboardSPDoc);
990         _root = sp_document_repr_root(_clipboardSPDoc);
991         
992         _clipnode = _doc->createElement("inkscape:clipboard");
993         _root->appendChild(_clipnode);
994         Inkscape::GC::release(_clipnode);
995     }
999 /**
1000  * @brief Deletes the internal clipboard document
1001  */
1002 void ClipboardManagerImpl::_discardInternalClipboard()
1004     if ( _clipboardSPDoc != NULL ) {
1005         sp_document_unref(_clipboardSPDoc);
1006         _clipboardSPDoc = NULL;
1007         _defs = NULL;
1008         _doc = NULL;
1009         _root = NULL;
1010         _clipnode = NULL;
1011     }
1015 /**
1016  * @brief Get the scale to resize an item, based on the command and desktop state
1017  */
1018 NR::scale ClipboardManagerImpl::_getScale(Geom::Point &min, Geom::Point &max, NR::Rect &obj_rect, bool apply_x, bool apply_y)
1020     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1021     double scale_x = 1.0;
1022     double scale_y = 1.0;
1023     
1024     if (apply_x) {
1025         scale_x = (max[Geom::X] - min[Geom::X]) / obj_rect.extent(NR::X);
1026     }
1027     if (apply_y) {
1028         scale_y = (max[Geom::Y] - min[Geom::Y]) / obj_rect.extent(NR::Y);
1029     }
1030     // If the "lock aspect ratio" button is pressed and we paste only a single coordinate,
1031     // resize the second one by the same ratio too
1032     if (desktop->isToolboxButtonActive("lock")) {
1033         if (apply_x && !apply_y) scale_y = scale_x;
1034         if (apply_y && !apply_x) scale_x = scale_y;
1035     }
1036     
1037     return NR::scale(scale_x, scale_y);
1041 /**
1042  * @brief Find the most suitable clipboard target
1043  */
1044 Glib::ustring ClipboardManagerImpl::_getBestTarget()
1046     std::list<Glib::ustring> targets = _clipboard->wait_for_targets();
1047     
1048     // clipboard target debugging snippet
1049     /*
1050     g_debug("Begin clipboard targets");
1051     for ( std::list<Glib::ustring>::iterator x = targets.begin() ; x != targets.end(); ++x )
1052         g_debug("Clipboard target: %s", (*x).data());
1053     g_debug("End clipboard targets\n");
1054     //*/
1055     
1056     for(std::list<Glib::ustring>::iterator i = _preferred_targets.begin() ;
1057         i != _preferred_targets.end() ; ++i)
1058     {
1059         if ( std::find(targets.begin(), targets.end(), *i) != targets.end() )
1060             return *i;
1061     }
1062     if (_clipboard->wait_is_image_available())
1063         return CLIPBOARD_GDK_PIXBUF_TARGET;
1064     if (_clipboard->wait_is_text_available())
1065         return CLIPBOARD_TEXT_TARGET;
1066     
1067     return "";
1071 /**
1072  * @brief Set the clipboard targets to reflect the mimetypes Inkscape can output
1073  */
1074 void ClipboardManagerImpl::_setClipboardTargets()
1075 {   
1076     Inkscape::Extension::DB::OutputList outlist;
1077     Inkscape::Extension::db.get_output_list(outlist);
1078     std::list<Gtk::TargetEntry> target_list;
1079     for (Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin() ; out != outlist.end() ; ++out) {
1080         target_list.push_back(Gtk::TargetEntry( (*out)->get_mimetype() ));
1081     }
1082     
1083     _clipboard->set(target_list,
1084         sigc::mem_fun(*this, &ClipboardManagerImpl::_onGet),
1085         sigc::mem_fun(*this, &ClipboardManagerImpl::_onClear));
1089 /**
1090  * @brief Set the string representation of a 32-bit RGBA color as the clipboard contents
1091  */
1092 void ClipboardManagerImpl::_setClipboardColor(guint32 color)
1094     gchar colorstr[16];
1095     g_snprintf(colorstr, 16, "%08x", color);
1096     _clipboard->set_text(colorstr);
1100 /**
1101  * @brief Put a notification on the mesage stack
1102  */
1103 void ClipboardManagerImpl::_userWarn(SPDesktop *desktop, char const *msg)
1105     desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, msg);
1110 /* #######################################
1111           ClipboardManager class
1112    ####################################### */
1114 ClipboardManager *ClipboardManager::_instance = NULL;
1116 ClipboardManager::ClipboardManager() {}
1117 ClipboardManager::~ClipboardManager() {}
1118 ClipboardManager *ClipboardManager::get()
1120     if ( _instance == NULL )
1121         _instance = new ClipboardManagerImpl;
1122     return _instance;
1125 } // namespace Inkscape
1126 } // namespace IO
1128 /*
1129   Local Variables:
1130   mode:c++
1131   c-file-style:"stroustrup"
1132   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1133   indent-tabs-mode:nil
1134   fill-column:99
1135   End:
1136 */
1137 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :