Code

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