Code

2d38f5ccd227909ed44b289618749aa962f99972
[inkscape.git] / src / ui / clipboard.cpp
1 /** @file
2  * @brief System-wide clipboard management - implementation
3  */
4 /* Authors:
5  *   Krzysztof KosiƄski <tweenk@o2.pl>
6  *   Incorporates some code from selection-chemistry.cpp, see that file for more credits.
7  *
8  * Copyright (C) 2008 authors
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * See the file COPYING for details.
16  */
18 #include "ui/clipboard.h"
20 // TODO: reduce header bloat if possible
22 #include <list>
23 #include <algorithm>
24 #include <gtkmm/clipboard.h>
25 #include <glibmm/ustring.h>
26 #include <glibmm/i18n.h>
27 #include <glib/gstdio.h> // for g_file_set_contents etc., used in _onGet and paste
28 #include "gc-core.h"
29 #include "xml/repr.h"
30 #include "inkscape.h"
31 #include "io/stringstream.h"
32 #include "desktop.h"
33 #include "desktop-handles.h"
34 #include "desktop-style.h" // for sp_desktop_set_style, used in _pasteStyle
35 #include "document.h"
36 #include "document-private.h"
37 #include "selection.h"
38 #include "message-stack.h"
39 #include "context-fns.h"
40 #include "dropper-context.h" // used in copy()
41 #include "style.h"
42 #include "extension/db.h" // extension database
43 #include "extension/input.h"
44 #include "extension/output.h"
45 #include "selection-chemistry.h"
46 #include "libnr/nr-rect.h"
47 #include "box3d.h"
48 #include "gradient-drag.h"
49 #include "sp-item.h"
50 #include "sp-item-transform.h" // for sp_item_scale_rel, used in _pasteSize
51 #include "sp-path.h"
52 #include "sp-pattern.h"
53 #include "sp-shape.h"
54 #include "sp-gradient.h"
55 #include "sp-gradient-reference.h"
56 #include "sp-gradient-fns.h"
57 #include "sp-linear-gradient-fns.h"
58 #include "sp-radial-gradient-fns.h"
59 #include "sp-clippath.h"
60 #include "sp-mask.h"
61 #include "sp-textpath.h"
62 #include "sp-rect.h"
63 #include "live_effects/lpeobject.h"
64 #include "live_effects/lpeobject-reference.h"
65 #include "live_effects/parameter/path.h"
66 #include "svg/svg.h" // for sp_svg_transform_write, used in _copySelection
67 #include "svg/css-ostringstream.h" // used in _parseColor
68 #include "file.h" // for file_import, used in _pasteImage
69 #include "prefs-utils.h" // for prefs_get_string_attribute, used in _pasteImage
70 #include "text-context.h"
71 #include "text-editing.h"
72 #include "tools-switch.h"
73 #include "libnr/n-art-bpath-2geom.h"
74 #include "path-chemistry.h"
76 /// @brief Made up mimetype to represent Gdk::Pixbuf clipboard contents
77 #define CLIPBOARD_GDK_PIXBUF_TARGET "image/x-gdk-pixbuf"
79 #define CLIPBOARD_TEXT_TARGET "text/plain"
81 namespace Inkscape {
82 namespace UI {
85 /**
86  * @brief Default implementation of the clipboard manager
87  */
88 class ClipboardManagerImpl : public ClipboardManager {
89 public:
90     virtual void copy();
91     virtual void copyPathParameter(Inkscape::LivePathEffect::PathParam *);
92     virtual bool paste(bool in_place);
93     virtual bool pasteStyle();
94     virtual bool pasteSize(bool, bool, bool);
95     virtual bool pastePathEffect();
96     virtual Glib::ustring getPathParameter();
97     virtual Glib::ustring getShapeOrTextObjectId();
99     ClipboardManagerImpl();
100     ~ClipboardManagerImpl();
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 *);
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 = "");
118     // clipboard callbacks
119     void _onGet(Gtk::SelectionData &, guint);
120     void _onClear();
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
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);
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     }
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     }
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     }
204     if (selection->isEmpty()) {  // check whether something is selected
205         _userWarn(desktop, _("Nothing was copied."));
206         return;
207     }
208     _discardInternalClipboard();
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);
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 = SVGD_from_2GeomPath( pp->get_pathvector() );
226     if ( svgd == NULL || *svgd == '\0' ) return;
228     _discardInternalClipboard();
229     _createInternalClipboard();
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);
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;
252     Glib::ustring target = _getBestTarget();
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
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();
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     }
270     _pasteDocument(tempdoc, in_place);
271     sp_document_unref(tempdoc);
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     }
292     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
293     if ( tempdoc == NULL ) {
294         _userWarn(desktop, _("No style on the clipboard."));
295         return false;
296     }
298     Inkscape::XML::Node
299         *root = sp_document_repr_root(tempdoc),
300         *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
302     bool pasted = false;
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
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     }
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     }
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);
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(). */
385     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
386     if ( desktop == NULL )
387         return false;
389     Inkscape::Selection *selection = sp_desktop_selection(desktop);
390     if (selection && selection->isEmpty()) {
391         _userWarn(desktop, _("Select <b>object(s)</b> to paste live path effect to."));
392         return false;
393     }
395     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
396     if ( tempdoc ) {
397         Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
398         Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
399         if ( clipnode ) {
400             gchar const *effect = clipnode->attribute("inkscape:path-effect");
401             if ( effect ) {
402                 _pasteDefs(tempdoc);
403                 // make sure all selected items are converted to paths first (i.e. rectangles)
404                 sp_selected_path_to_curves(false);
405                 for (GSList *item = const_cast<GSList *>(selection->itemList()) ; item ; item = item->next) {
406                     _applyPathEffect(reinterpret_cast<SPItem*>(item->data), effect);
407                 }
409                 return true;
410             }
411         }
412     }
414     // no_effect:
415     _userWarn(desktop, _("No effect on the clipboard."));
416     return false;
420 /**
421  * @brief Get LPE path data from the clipboard
422  * @return The retrieved path data (contents of the d attribute), or "" if no path was found
423  */
424 Glib::ustring ClipboardManagerImpl::getPathParameter()
426     SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
427     if ( tempdoc == NULL ) {
428         _userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
429         return "";
430     }
431     Inkscape::XML::Node
432         *root = sp_document_repr_root(tempdoc),
433         *path = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
434     if ( path == NULL ) {
435         _userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
436         sp_document_unref(tempdoc);
437         return "";
438     }
439     gchar const *svgd = path->attribute("d");
440     return svgd;
444 /**
445  * @brief Get object id of a shape or text item from the clipboard
446  * @return The retrieved id string (contents of the id attribute), or "" if no shape or text item was found
447  */
448 Glib::ustring ClipboardManagerImpl::getShapeOrTextObjectId()
450     SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
451     if ( tempdoc == NULL ) {
452         _userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
453         return "";
454     }
455     Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
457     Inkscape::XML::Node *repr = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
458     if ( repr == NULL )
459         repr = sp_repr_lookup_name(root, "svg:text", -1);
461     if ( repr == NULL ) {
462         _userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
463         sp_document_unref(tempdoc);
464         return "";
465     }
466     gchar const *svgd = repr->attribute("id");
467     return svgd;
471 /**
472  * @brief Iterate over a list of items and copy them to the clipboard.
473  */
474 void ClipboardManagerImpl::_copySelection(Inkscape::Selection *selection)
476     GSList const *items = selection->itemList();
477     // copy the defs used by all items
478     for (GSList *i = const_cast<GSList *>(items) ; i != NULL ; i = i->next) {
479         _copyUsedDefs(SP_ITEM (i->data));
480     }
482     // copy the representation of the items
483     GSList *sorted_items = g_slist_copy(const_cast<GSList *>(items));
484     sorted_items = g_slist_sort(sorted_items, (GCompareFunc) sp_object_compare_position);
486     for (GSList *i = sorted_items ; i ; i = i->next) {
487         if (!SP_IS_ITEM(i->data)) continue;
488         Inkscape::XML::Node *obj = SP_OBJECT_REPR(i->data);
489         Inkscape::XML::Node *obj_copy = _copyNode(obj, _doc, _root);
491         // copy complete inherited style
492         SPCSSAttr *css = sp_repr_css_attr_inherited(obj, "style");
493         sp_repr_css_set(obj_copy, css, "style");
494         sp_repr_css_attr_unref(css);
496         // write the complete accumulated transform passed to us
497         // (we're dealing with unattached representations, so we write to their attributes
498         // instead of using sp_item_set_transform)
499         gchar *transform_str = sp_svg_transform_write(sp_item_i2doc_affine(SP_ITEM(i->data)));
500         obj_copy->setAttribute("transform", transform_str);
501         g_free(transform_str);
502     }
504     // copy style for Paste Style action
505     if (sorted_items) {
506         if(SP_IS_ITEM(sorted_items->data)) {
507             SPCSSAttr *style = take_style_from_item((SPItem *) sorted_items->data);
508             sp_repr_css_set(_clipnode, style, "style");
509             sp_repr_css_attr_unref(style);
510         }
512         // copy path effect from the first path
513         if (SP_IS_OBJECT(sorted_items->data)) {
514             gchar const *effect = SP_OBJECT_REPR(sorted_items->data)->attribute("inkscape:path-effect");
515             if (effect) {
516                 _clipnode->setAttribute("inkscape:path-effect", effect);
517             }
518         }
519     }
521     NR::Maybe<NR::Rect> size = selection->bounds();
522     if (size) {
523         sp_repr_set_point(_clipnode, "min", size->min().to_2geom());
524         sp_repr_set_point(_clipnode, "max", size->max().to_2geom());
525     }
527     g_slist_free(sorted_items);
531 /**
532  * @brief Recursively copy all the definitions used by a given item to the clipboard defs
533  */
534 void ClipboardManagerImpl::_copyUsedDefs(SPItem *item)
536     // copy fill and stroke styles (patterns and gradients)
537     SPStyle *style = SP_OBJECT_STYLE(item);
539     if (style && (style->fill.isPaintserver())) {
540         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
541         if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
542             _copyGradient(SP_GRADIENT(server));
543         if (SP_IS_PATTERN(server))
544             _copyPattern(SP_PATTERN(server));
545     }
546     if (style && (style->stroke.isPaintserver())) {
547         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
548         if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
549             _copyGradient(SP_GRADIENT(server));
550         if (SP_IS_PATTERN(server))
551             _copyPattern(SP_PATTERN(server));
552     }
554     // For shapes, copy all of the shape's markers
555     if (SP_IS_SHAPE(item)) {
556         SPShape *shape = SP_SHAPE (item);
557         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
558             if (shape->marker[i]) {
559                 _copyNode(SP_OBJECT_REPR(SP_OBJECT(shape->marker[i])), _doc, _defs);
560             }
561         }
562     }
563     // For lpe items, copy liveeffect if applicable
564     // TODO: copy the whole effect stack. now it only copies current selected effect
565     if (SP_IS_LPE_ITEM(item)) {
566         SPLPEItem *lpeitem = SP_LPE_ITEM (item);
567         if (sp_lpe_item_has_path_effect(lpeitem)) {
568             Inkscape::LivePathEffect::LPEObjectReference* lperef = sp_lpe_item_get_current_lpereference(lpeitem);
569             if (lperef && lperef->lpeobject) {
570                 _copyNode(SP_OBJECT_REPR(SP_OBJECT(lperef->lpeobject)), _doc, _defs);
571             }
572         }
573     }
574     // For 3D boxes, copy perspectives
575     if (SP_IS_BOX3D(item)) {
576         _copyNode(SP_OBJECT_REPR(SP_OBJECT(box3d_get_perspective(SP_BOX3D(item)))), _doc, _defs);
577     }
578     // Copy text paths
579     if (SP_IS_TEXT_TEXTPATH(item)) {
580         _copyTextPath(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
581     }
582     // Copy clipping objects
583     if (item->clip_ref->getObject()) {
584         _copyNode(SP_OBJECT_REPR(item->clip_ref->getObject()), _doc, _defs);
585     }
586     // Copy mask objects
587     if (item->mask_ref->getObject()) {
588         SPObject *mask = item->mask_ref->getObject();
589         _copyNode(SP_OBJECT_REPR(mask), _doc, _defs);
590         // recurse into the mask for its gradients etc.
591         for (SPObject *o = SP_OBJECT(mask)->children ; o != NULL ; o = o->next) {
592             if (SP_IS_ITEM(o))
593                 _copyUsedDefs(SP_ITEM(o));
594         }
595     }
596     // Copy filters
597     if (style->getFilter()) {
598         SPObject *filter = style->getFilter();
599         if (SP_IS_FILTER(filter)) {
600             _copyNode(SP_OBJECT_REPR(filter), _doc, _defs);
601         }
602     }
604     // recurse
605     for (SPObject *o = SP_OBJECT(item)->children ; o != NULL ; o = o->next) {
606         if (SP_IS_ITEM(o))
607             _copyUsedDefs(SP_ITEM(o));
608     }
612 /**
613  * @brief Copy a single gradient to the clipboard's defs element
614  */
615 void ClipboardManagerImpl::_copyGradient(SPGradient *gradient)
617     while (gradient) {
618         // climb up the refs, copying each one in the chain
619         _copyNode(SP_OBJECT_REPR(gradient), _doc, _defs);
620         gradient = gradient->ref->getObject();
621     }
625 /**
626  * @brief Copy a single pattern to the clipboard document's defs element
627  */
628 void ClipboardManagerImpl::_copyPattern(SPPattern *pattern)
630     // climb up the references, copying each one in the chain
631     while (pattern) {
632         _copyNode(SP_OBJECT_REPR(pattern), _doc, _defs);
634         // items in the pattern may also use gradients and other patterns, so recurse
635         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL ; child = SP_OBJECT_NEXT(child) ) {
636             if (!SP_IS_ITEM (child)) continue;
637             _copyUsedDefs(SP_ITEM(child));
638         }
639         pattern = pattern->ref->getObject();
640     }
644 /**
645  * @brief Copy a text path to the clipboard's defs element
646  */
647 void ClipboardManagerImpl::_copyTextPath(SPTextPath *tp)
649     SPItem *path = sp_textpath_get_path_item(tp);
650     if(!path) return;
651     Inkscape::XML::Node *path_node = SP_OBJECT_REPR(path);
653     // Do not copy the text path to defs if it's already copied
654     if(sp_repr_lookup_child(_root, "id", path_node->attribute("id"))) return;
655     _copyNode(path_node, _doc, _defs);
659 /**
660  * @brief Copy a single XML node from one document to another
661  * @param node The node to be copied
662  * @param target_doc The document to which the node is to be copied
663  * @param parent The node in the target document which will become the parent of the copied node
664  * @return Pointer to the copied node
665  */
666 Inkscape::XML::Node *ClipboardManagerImpl::_copyNode(Inkscape::XML::Node *node, Inkscape::XML::Document *target_doc, Inkscape::XML::Node *parent)
668     Inkscape::XML::Node *dup = node->duplicate(target_doc);
669     parent->appendChild(dup);
670     Inkscape::GC::release(dup);
671     return dup;
675 /**
676  * @brief Paste the contents of a document into the active desktop
677  * @param clipdoc The document to paste
678  * @param in_place Whether to paste the selection where it was when copied
679  * @pre @c clipdoc is not empty and items can be added to the current layer
680  */
681 void ClipboardManagerImpl::_pasteDocument(SPDocument *clipdoc, bool in_place)
683     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
684     SPDocument *target_document = sp_desktop_document(desktop);
685     Inkscape::XML::Node
686         *root = sp_document_repr_root(clipdoc),
687         *target_parent = SP_OBJECT_REPR(desktop->currentLayer());
688     Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
690     // copy definitions
691     _pasteDefs(clipdoc);
693     // copy objects
694     GSList *pasted_objects = NULL;
695     for (Inkscape::XML::Node *obj = root->firstChild() ; obj ; obj = obj->next()) {
696         // Don't copy metadata, defs, named views and internal clipboard contents to the document
697         if (!strcmp(obj->name(), "svg:defs")) continue;
698         if (!strcmp(obj->name(), "svg:metadata")) continue;
699         if (!strcmp(obj->name(), "sodipodi:namedview")) continue;
700         if (!strcmp(obj->name(), "inkscape:clipboard")) continue;
701         Inkscape::XML::Node *obj_copy = _copyNode(obj, target_xmldoc, target_parent);
702         pasted_objects = g_slist_prepend(pasted_objects, (gpointer) obj_copy);
703     }
705     Inkscape::Selection *selection = sp_desktop_selection(desktop);
706     selection->setReprList(pasted_objects);
708     // move the selection to the right position
709     if(in_place)
710     {
711         Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
712         if (clipnode) {
713             Geom::Point min, max;
714             sp_repr_get_point(clipnode, "min", &min);
715             sp_repr_get_point(clipnode, "max", &max);
717             // this formula was discovered empyrically
718             min[Geom::Y] += ((max[Geom::Y] - min[Geom::Y]) - sp_document_height(target_document));
719             sp_selection_move_relative(selection, NR::Point(min));
720         }
721     }
722     // copied from former sp_selection_paste in selection-chemistry.cpp
723     else {
724         sp_document_ensure_up_to_date(target_document);
725         NR::Maybe<NR::Rect> sel_size = selection->bounds();
727         NR::Point m( desktop->point() );
728         if (sel_size) {
729             m -= sel_size->midpoint();
730         }
731         sp_selection_move_relative(selection, m);
732     }
734     g_slist_free(pasted_objects);
738 /**
739  * @brief Paste SVG defs from the document retrieved from the clipboard into the active document
740  * @param clipdoc The document to paste
741  * @pre @c clipdoc != NULL and pasting into the active document is possible
742  */
743 void ClipboardManagerImpl::_pasteDefs(SPDocument *clipdoc)
745     // boilerplate vars copied from _pasteDocument
746     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
747     SPDocument *target_document = sp_desktop_document(desktop);
748     Inkscape::XML::Node
749         *root = sp_document_repr_root(clipdoc),
750         *defs = sp_repr_lookup_name(root, "svg:defs", 1),
751         *target_defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(target_document));
752     Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
754     for (Inkscape::XML::Node *def = defs->firstChild() ; def ; def = def->next()) {
755         /// @todo TODO: implement def id collision resolution in ClipboardManagerImpl::_pasteDefs()
757         /*
758         // simplistic solution: when a collision occurs, add "a" to id until it's unique
759         Glib::ustring pasted_id = def->attribute("id");
760         if ( pasted_id.empty() ) continue; // defs without id are useless
761         Glib::ustring pasted_id_original = pasted_id;
763         while(sp_repr_lookup_child(target_defs, "id", pasted_id.data())) {
764             pasted_id.append("a");
765         }
767         if ( pasted_id != pasted_id_original ) {
768             def->setAttribute("id", pasted_id.data());
769             // Update the id in the rest of the document so there are no dangling references
770             // How to do that?
771             _changeIdReferences(clipdoc, pasted_id_original, pasted_id);
772         }
773         */
774         if (sp_repr_lookup_child(target_defs, "id", def->attribute("id")))
775             continue; // skip duplicate defs - temporary non-solution
777         _copyNode(def, target_xmldoc, target_defs);
778     }
782 /**
783  * @brief Retrieve a bitmap image from the clipboard and paste it into the active document
784  */
785 bool ClipboardManagerImpl::_pasteImage()
787     SPDocument *doc = SP_ACTIVE_DOCUMENT;
788     if ( doc == NULL ) return false;
790     // retrieve image data
791     Glib::RefPtr<Gdk::Pixbuf> img = _clipboard->wait_for_image();
792     if (!img) return false;
794     // Very stupid hack: Write into a file, then import the file into the document.
795     // To avoid using tmpfile and POSIX file handles, make the filename based on current time.
796     // This wasn't my idea, I just copied this from selection-chemistry.cpp
797     // and just can't think of something saner at the moment. Pasting more than
798     // one image per second will overwrite the image.
799     // However, I don't think anyone is able to copy a _different_ image into inkscape
800     // in 1 second.
801     time_t rawtime;
802     char image_filename[128];
803     gchar const *save_folder;
805     time(&rawtime);
806     strftime(image_filename, 128, "inkscape_pasted_image_%Y%m%d_%H%M%S.png", localtime( &rawtime ));
807     save_folder = (gchar const *) prefs_get_string_attribute("dialogs.save_as", "path");
809     gchar *image_path = g_build_filename(save_folder, image_filename, NULL);
810     img->save(image_path, "png");
811     file_import(doc, image_path, NULL);
812     g_free(image_path);
814     return true;
817 /**
818  * @brief Paste text into the selected text object or create a new one to hold it
819  */
820 bool ClipboardManagerImpl::_pasteText()
822     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
823     if ( desktop == NULL ) return false;
825     // if the text editing tool is active, paste the text into the active text object
826     if (tools_isactive(desktop, TOOLS_TEXT))
827         return sp_text_paste_inline(desktop->event_context);
829     // try to parse the text as a color and, if successful, apply it as the current style
830     SPCSSAttr *css = _parseColor(_clipboard->wait_for_text());
831     if (css) {
832         sp_desktop_set_style(desktop, css);
833         return true;
834     }
836     return false;
840 /**
841  * @brief Attempt to parse the passed string as a hexadecimal RGB or RGBA color
842  * @param text The Glib::ustring to parse
843  * @return New CSS style representation if the parsing was successful, NULL otherwise
844  */
845 SPCSSAttr *ClipboardManagerImpl::_parseColor(const Glib::ustring &text)
847     Glib::ustring::size_type len = text.bytes();
848     char *str = const_cast<char *>(text.data());
849     bool attempt_alpha = false;
850     if ( !str || ( *str == '\0' ) ) return NULL; // this is OK due to boolean short-circuit
852     // those conditionals guard against parsing e.g. the string "fab" as "fab000"
853     // (incomplete color) and "45fab71" as "45fab710" (incomplete alpha)
854     if ( *str == '#' ) {
855         if ( len < 7 ) return NULL;
856         if ( len >= 9 ) attempt_alpha = true;
857     } else {
858         if ( len < 6 ) return NULL;
859         if ( len >= 8 ) attempt_alpha = true;
860     }
862     unsigned int color = 0, alpha = 0xff;
864     // skip a leading #, if present
865     if ( *str == '#' ) ++str;
867     // try to parse first 6 digits
868     int res = sscanf(str, "%6x", &color);
869     if ( res && ( res != EOF ) ) {
870         if (attempt_alpha) {// try to parse alpha if there's enough characters
871             sscanf(str + 6, "%2x", &alpha);
872             if ( !res || res == EOF ) alpha = 0xff;
873         }
875         SPCSSAttr *color_css = sp_repr_css_attr_new();
877         // print and set properties
878         gchar color_str[16];
879         g_snprintf(color_str, 16, "#%06x", color);
880         sp_repr_css_set_property(color_css, "fill", color_str);
882         float opacity = static_cast<float>(alpha)/static_cast<float>(0xff);
883         if (opacity > 1.0) opacity = 1.0; // safeguard
884         Inkscape::CSSOStringStream opcss;
885         opcss << opacity;
886         sp_repr_css_set_property(color_css, "fill-opacity", opcss.str().data());
887         return color_css;
888     }
889     return NULL;
893 /**
894  * @brief Applies a pasted path effect to a given item
895  */
896 void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effect)
898     if ( item == NULL ) return;
899     if ( SP_IS_RECT(item) ) return;
901     if (SP_IS_LPE_ITEM(item))
902     {
903         SPLPEItem *lpeitem = SP_LPE_ITEM(item);
904         SPObject *obj = sp_uri_reference_resolve(_clipboardSPDoc, effect);
905         if (!obj) return;
906         // if the effect is not used by anyone, we might as well take it
907         LivePathEffectObject *lpeobj = LIVEPATHEFFECT(obj)->fork_private_if_necessary(1);
908         sp_lpe_item_add_path_effect(lpeitem, lpeobj);
909     }
913 /**
914  * @brief Retrieve the clipboard contents as a document
915  * @return Clipboard contents converted to SPDocument, or NULL if no suitable content was present
916  */
917 SPDocument *ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_target)
919     Glib::ustring best_target;
920     if ( required_target == "" )
921         best_target = _getBestTarget();
922     else
923         best_target = required_target;
925     if ( best_target == "" ) {
926         return NULL;
927     }
929     if ( !_clipboard->wait_is_target_available(best_target) ) {
930         return NULL;
931     }
933     // doing this synchronously makes better sense
934     // TODO: use another method because this one is badly broken imo.
935     // from documentation: "Returns: A SelectionData object, which will be invalid if retrieving the given target failed."
936     // I don't know how to check whether an object is 'valid' or not, unusable if that's not possible...
937     Gtk::SelectionData sel = _clipboard->wait_for_contents(best_target);
938     Glib::ustring target = sel.get_target();  // this can crash if the result was invalid of last function. No way to check for this :(
940     // there is no specific plain SVG input extension, so if we can paste the Inkscape SVG format,
941     // we use the image/svg+xml mimetype to look up the input extension
942     if(target == "image/x-inkscape-svg")
943         target = "image/svg+xml";
945     Inkscape::Extension::DB::InputList inlist;
946     Inkscape::Extension::db.get_input_list(inlist);
947     Inkscape::Extension::DB::InputList::const_iterator in = inlist.begin();
948     for (; in != inlist.end() && target != (*in)->get_mimetype() ; ++in);
949     if ( in == inlist.end() )
950         return NULL; // this shouldn't happen unless _getBestTarget returns something bogus
952     // FIXME: Temporary hack until we add memory input.
953     // Save the clipboard contents to some file, then read it
954     gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-import", NULL );
955     g_file_set_contents(filename, (const gchar *) sel.get_data(), sel.get_length(), NULL);
957     SPDocument *tempdoc = (*in)->open(filename);
958     g_unlink(filename);
959     g_free(filename);
961     return tempdoc;
965 /**
966  * @brief Callback called when some other application requests data from Inkscape
967  *
968  * Finds a suitable output extension to save the internal clipboard document,
969  * then saves it to memory and sets the clipboard contents.
970  */
971 void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint /*info*/)
973     g_assert( _clipboardSPDoc != NULL );
975     const Glib::ustring target = sel.get_target();
976     if(target == "") return; // this shouldn't happen
978     Inkscape::Extension::DB::OutputList outlist;
979     Inkscape::Extension::db.get_output_list(outlist);
980     Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
981     for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out);
982     if ( out == outlist.end() ) return; // this also shouldn't happen
984     // FIXME: Temporary hack until we add support for memory output.
985     // Save to a temporary file, read it back and then set the clipboard contents
986     gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export", NULL );
987     gsize len; gchar *data;
989     (*out)->save(_clipboardSPDoc, filename);
990     g_file_get_contents(filename, &data, &len, NULL);
991     g_unlink(filename); // delete the temporary file
992     g_free(filename);
994     sel.set(8, (guint8 const *) data, len);
998 /**
999  * @brief Callback when someone else takes the clipboard
1000  *
1001  * When the clipboard owner changes, this callback clears the internal clipboard document
1002  * to reduce memory usage.
1003  */
1004 void ClipboardManagerImpl::_onClear()
1006     // why is this called before _onGet???
1007     //_discardInternalClipboard();
1011 /**
1012  * @brief Creates an internal clipboard document from scratch
1013  */
1014 void ClipboardManagerImpl::_createInternalClipboard()
1016     if ( _clipboardSPDoc == NULL ) {
1017         _clipboardSPDoc = sp_document_new(NULL, false, true);
1018         //g_assert( _clipboardSPDoc != NULL );
1019         _defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(_clipboardSPDoc));
1020         _doc = sp_document_repr_doc(_clipboardSPDoc);
1021         _root = sp_document_repr_root(_clipboardSPDoc);
1023         _clipnode = _doc->createElement("inkscape:clipboard");
1024         _root->appendChild(_clipnode);
1025         Inkscape::GC::release(_clipnode);
1026     }
1030 /**
1031  * @brief Deletes the internal clipboard document
1032  */
1033 void ClipboardManagerImpl::_discardInternalClipboard()
1035     if ( _clipboardSPDoc != NULL ) {
1036         sp_document_unref(_clipboardSPDoc);
1037         _clipboardSPDoc = NULL;
1038         _defs = NULL;
1039         _doc = NULL;
1040         _root = NULL;
1041         _clipnode = NULL;
1042     }
1046 /**
1047  * @brief Get the scale to resize an item, based on the command and desktop state
1048  */
1049 NR::scale ClipboardManagerImpl::_getScale(Geom::Point &min, Geom::Point &max, NR::Rect &obj_rect, bool apply_x, bool apply_y)
1051     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1052     double scale_x = 1.0;
1053     double scale_y = 1.0;
1055     if (apply_x) {
1056         scale_x = (max[Geom::X] - min[Geom::X]) / obj_rect.extent(NR::X);
1057     }
1058     if (apply_y) {
1059         scale_y = (max[Geom::Y] - min[Geom::Y]) / obj_rect.extent(NR::Y);
1060     }
1061     // If the "lock aspect ratio" button is pressed and we paste only a single coordinate,
1062     // resize the second one by the same ratio too
1063     if (desktop->isToolboxButtonActive("lock")) {
1064         if (apply_x && !apply_y) scale_y = scale_x;
1065         if (apply_y && !apply_x) scale_x = scale_y;
1066     }
1068     return NR::scale(scale_x, scale_y);
1072 /**
1073  * @brief Find the most suitable clipboard target
1074  */
1075 Glib::ustring ClipboardManagerImpl::_getBestTarget()
1077     std::list<Glib::ustring> targets = _clipboard->wait_for_targets();
1079     // clipboard target debugging snippet
1080     /*
1081     g_debug("Begin clipboard targets");
1082     for ( std::list<Glib::ustring>::iterator x = targets.begin() ; x != targets.end(); ++x )
1083         g_debug("Clipboard target: %s", (*x).data());
1084     g_debug("End clipboard targets\n");
1085     //*/
1087     for(std::list<Glib::ustring>::iterator i = _preferred_targets.begin() ;
1088         i != _preferred_targets.end() ; ++i)
1089     {
1090         if ( std::find(targets.begin(), targets.end(), *i) != targets.end() )
1091             return *i;
1092     }
1093     if (_clipboard->wait_is_image_available())
1094         return CLIPBOARD_GDK_PIXBUF_TARGET;
1095     if (_clipboard->wait_is_text_available())
1096         return CLIPBOARD_TEXT_TARGET;
1098     return "";
1102 /**
1103  * @brief Set the clipboard targets to reflect the mimetypes Inkscape can output
1104  */
1105 void ClipboardManagerImpl::_setClipboardTargets()
1107     Inkscape::Extension::DB::OutputList outlist;
1108     Inkscape::Extension::db.get_output_list(outlist);
1109     std::list<Gtk::TargetEntry> target_list;
1110     for (Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin() ; out != outlist.end() ; ++out) {
1111         target_list.push_back(Gtk::TargetEntry( (*out)->get_mimetype() ));
1112     }
1114     _clipboard->set(target_list,
1115         sigc::mem_fun(*this, &ClipboardManagerImpl::_onGet),
1116         sigc::mem_fun(*this, &ClipboardManagerImpl::_onClear));
1120 /**
1121  * @brief Set the string representation of a 32-bit RGBA color as the clipboard contents
1122  */
1123 void ClipboardManagerImpl::_setClipboardColor(guint32 color)
1125     gchar colorstr[16];
1126     g_snprintf(colorstr, 16, "%08x", color);
1127     _clipboard->set_text(colorstr);
1131 /**
1132  * @brief Put a notification on the mesage stack
1133  */
1134 void ClipboardManagerImpl::_userWarn(SPDesktop *desktop, char const *msg)
1136     desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, msg);
1141 /* #######################################
1142           ClipboardManager class
1143    ####################################### */
1145 ClipboardManager *ClipboardManager::_instance = NULL;
1147 ClipboardManager::ClipboardManager() {}
1148 ClipboardManager::~ClipboardManager() {}
1149 ClipboardManager *ClipboardManager::get()
1151     if ( _instance == NULL )
1152         _instance = new ClipboardManagerImpl;
1153     return _instance;
1156 } // namespace Inkscape
1157 } // namespace IO
1159 /*
1160   Local Variables:
1161   mode:c++
1162   c-file-style:"stroustrup"
1163   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1164   indent-tabs-mode:nil
1165   fill-column:99
1166   End:
1167 */
1168 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :