7973f82af968442942037d24ce70409406857db6
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();
103 ClipboardManagerImpl();
104 ~ClipboardManagerImpl();
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 *);
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 = "");
122 // clipboard callbacks
123 void _onGet(Gtk::SelectionData &, guint);
124 void _onClear();
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
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() )
155 {
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");
165 }
168 ClipboardManagerImpl::~ClipboardManagerImpl() {}
171 /**
172 * @brief Copy selection contents to the clipboard
173 */
174 void ClipboardManagerImpl::copy()
175 {
176 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
177 if ( desktop == NULL ) return;
178 Inkscape::Selection *selection = sp_desktop_selection(desktop);
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 }
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 }
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 }
208 if (selection->isEmpty()) { // check whether something is selected
209 _userWarn(desktop, _("Nothing was copied."));
210 return;
211 }
212 _discardInternalClipboard();
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);
218 _setClipboardTargets();
219 }
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)
227 {
228 if ( pp == NULL ) return;
229 gchar *svgd = SVGD_from_2GeomPath( pp->get_pathvector() );
230 if ( svgd == NULL || *svgd == '\0' ) return;
232 _discardInternalClipboard();
233 _createInternalClipboard();
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);
241 fit_canvas_to_drawing(_clipboardSPDoc);
242 _setClipboardTargets();
243 }
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)
250 {
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;
256 Glib::ustring target = _getBestTarget();
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
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();
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 }
274 _pasteDocument(tempdoc, in_place);
275 sp_document_unref(tempdoc);
277 return true;
278 }
281 /**
282 * @brief Implements the Paste Style action
283 */
284 bool ClipboardManagerImpl::pasteStyle()
285 {
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 }
296 SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
297 if ( tempdoc == NULL ) {
298 _userWarn(desktop, _("No style on the clipboard."));
299 return false;
300 }
302 Inkscape::XML::Node
303 *root = sp_document_repr_root(tempdoc),
304 *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
306 bool pasted = false;
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;
320 }
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)
330 {
331 if(!apply_x && !apply_y) return false; // pointless parameters
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 }
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 }
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);
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;
378 }
381 /**
382 * @brief Applies a path effect from the clipboard to the selected path
383 */
384 bool ClipboardManagerImpl::pastePathEffect()
385 {
386 /** @todo FIXME: pastePathEffect crashes when moving the path with the applied effect,
387 segfaulting in fork_private_if_necessary(). */
389 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
390 if ( desktop == NULL )
391 return false;
393 Inkscape::Selection *selection = sp_desktop_selection(desktop);
394 if (selection && selection->isEmpty()) {
395 _userWarn(desktop, _("Select <b>object(s)</b> to paste live path effect to."));
396 return false;
397 }
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 }
413 return true;
414 }
415 }
416 }
418 // no_effect:
419 _userWarn(desktop, _("No effect on the clipboard."));
420 return false;
421 }
424 /**
425 * @brief Get LPE path data from the clipboard
426 * @return The retrieved path data (contents of the d attribute), or "" if no path was found
427 */
428 Glib::ustring ClipboardManagerImpl::getPathParameter()
429 {
430 SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
431 if ( tempdoc == NULL ) {
432 _userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
433 return "";
434 }
435 Inkscape::XML::Node
436 *root = sp_document_repr_root(tempdoc),
437 *path = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
438 if ( path == NULL ) {
439 _userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
440 sp_document_unref(tempdoc);
441 return "";
442 }
443 gchar const *svgd = path->attribute("d");
444 return svgd;
445 }
448 /**
449 * @brief Get object id of a shape or text item from the clipboard
450 * @return The retrieved id string (contents of the id attribute), or "" if no shape or text item was found
451 */
452 Glib::ustring ClipboardManagerImpl::getShapeOrTextObjectId()
453 {
454 SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
455 if ( tempdoc == NULL ) {
456 _userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
457 return "";
458 }
459 Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
461 Inkscape::XML::Node *repr = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
462 if ( repr == NULL )
463 repr = sp_repr_lookup_name(root, "svg:text", -1);
465 if ( repr == NULL ) {
466 _userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
467 sp_document_unref(tempdoc);
468 return "";
469 }
470 gchar const *svgd = repr->attribute("id");
471 return svgd;
472 }
475 /**
476 * @brief Iterate over a list of items and copy them to the clipboard.
477 */
478 void ClipboardManagerImpl::_copySelection(Inkscape::Selection *selection)
479 {
480 GSList const *items = selection->itemList();
481 // copy the defs used by all items
482 for (GSList *i = const_cast<GSList *>(items) ; i != NULL ; i = i->next) {
483 _copyUsedDefs(SP_ITEM (i->data));
484 }
486 // copy the representation of the items
487 GSList *sorted_items = g_slist_copy(const_cast<GSList *>(items));
488 sorted_items = g_slist_sort(sorted_items, (GCompareFunc) sp_object_compare_position);
490 for (GSList *i = sorted_items ; i ; i = i->next) {
491 if (!SP_IS_ITEM(i->data)) continue;
492 Inkscape::XML::Node *obj = SP_OBJECT_REPR(i->data);
493 Inkscape::XML::Node *obj_copy = _copyNode(obj, _doc, _root);
495 // copy complete inherited style
496 SPCSSAttr *css = sp_repr_css_attr_inherited(obj, "style");
497 sp_repr_css_set(obj_copy, css, "style");
498 sp_repr_css_attr_unref(css);
500 // write the complete accumulated transform passed to us
501 // (we're dealing with unattached representations, so we write to their attributes
502 // instead of using sp_item_set_transform)
503 gchar *transform_str = sp_svg_transform_write(sp_item_i2doc_affine(SP_ITEM(i->data)));
504 obj_copy->setAttribute("transform", transform_str);
505 g_free(transform_str);
506 }
508 // copy style for Paste Style action
509 if (sorted_items) {
510 if(SP_IS_ITEM(sorted_items->data)) {
511 SPCSSAttr *style = take_style_from_item((SPItem *) sorted_items->data);
512 sp_repr_css_set(_clipnode, style, "style");
513 sp_repr_css_attr_unref(style);
514 }
516 // copy path effect from the first path
517 if (SP_IS_OBJECT(sorted_items->data)) {
518 gchar const *effect = SP_OBJECT_REPR(sorted_items->data)->attribute("inkscape:path-effect");
519 if (effect) {
520 _clipnode->setAttribute("inkscape:path-effect", effect);
521 }
522 }
523 }
525 NR::Maybe<NR::Rect> size = selection->bounds();
526 if (size) {
527 sp_repr_set_point(_clipnode, "min", size->min().to_2geom());
528 sp_repr_set_point(_clipnode, "max", size->max().to_2geom());
529 }
531 g_slist_free(sorted_items);
532 }
535 /**
536 * @brief Recursively copy all the definitions used by a given item to the clipboard defs
537 */
538 void ClipboardManagerImpl::_copyUsedDefs(SPItem *item)
539 {
540 // copy fill and stroke styles (patterns and gradients)
541 SPStyle *style = SP_OBJECT_STYLE(item);
543 if (style && (style->fill.isPaintserver())) {
544 SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
545 if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
546 _copyGradient(SP_GRADIENT(server));
547 if (SP_IS_PATTERN(server))
548 _copyPattern(SP_PATTERN(server));
549 }
550 if (style && (style->stroke.isPaintserver())) {
551 SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
552 if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
553 _copyGradient(SP_GRADIENT(server));
554 if (SP_IS_PATTERN(server))
555 _copyPattern(SP_PATTERN(server));
556 }
558 // For shapes, copy all of the shape's markers
559 if (SP_IS_SHAPE(item)) {
560 SPShape *shape = SP_SHAPE (item);
561 for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
562 if (shape->marker[i]) {
563 _copyNode(SP_OBJECT_REPR(SP_OBJECT(shape->marker[i])), _doc, _defs);
564 }
565 }
566 }
567 // For lpe items, copy liveeffect if applicable
568 if (SP_IS_LPE_ITEM(item)) {
569 SPLPEItem *lpeitem = SP_LPE_ITEM (item);
570 if (sp_lpe_item_has_path_effect(lpeitem)) {
571 _copyNode(SP_OBJECT_REPR(SP_OBJECT(sp_lpe_item_get_livepatheffectobject(lpeitem))), _doc, _defs);
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 }
609 }
612 /**
613 * @brief Copy a single gradient to the clipboard's defs element
614 */
615 void ClipboardManagerImpl::_copyGradient(SPGradient *gradient)
616 {
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 }
622 }
625 /**
626 * @brief Copy a single pattern to the clipboard document's defs element
627 */
628 void ClipboardManagerImpl::_copyPattern(SPPattern *pattern)
629 {
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 }
641 }
644 /**
645 * @brief Copy a text path to the clipboard's defs element
646 */
647 void ClipboardManagerImpl::_copyTextPath(SPTextPath *tp)
648 {
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);
656 }
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)
667 {
668 Inkscape::XML::Node *dup = node->duplicate(target_doc);
669 parent->appendChild(dup);
670 Inkscape::GC::release(dup);
671 return dup;
672 }
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)
682 {
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);
735 }
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)
744 {
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 }
779 }
782 /**
783 * @brief Retrieve a bitmap image from the clipboard and paste it into the active document
784 */
785 bool ClipboardManagerImpl::_pasteImage()
786 {
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;
815 }
817 /**
818 * @brief Paste text into the selected text object or create a new one to hold it
819 */
820 bool ClipboardManagerImpl::_pasteText()
821 {
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;
837 }
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)
846 {
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;
890 }
893 /**
894 * @brief Applies a pasted path effect to a given item
895 */
896 void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effect)
897 {
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_set_path_effect(lpeitem, lpeobj);
909 }
910 }
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)
918 {
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;
962 }
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)
972 {
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);
995 }
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()
1005 {
1006 // why is this called before _onGet???
1007 //_discardInternalClipboard();
1008 }
1011 /**
1012 * @brief Creates an internal clipboard document from scratch
1013 */
1014 void ClipboardManagerImpl::_createInternalClipboard()
1015 {
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 }
1027 }
1030 /**
1031 * @brief Deletes the internal clipboard document
1032 */
1033 void ClipboardManagerImpl::_discardInternalClipboard()
1034 {
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 }
1043 }
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)
1050 {
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);
1069 }
1072 /**
1073 * @brief Find the most suitable clipboard target
1074 */
1075 Glib::ustring ClipboardManagerImpl::_getBestTarget()
1076 {
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 "";
1099 }
1102 /**
1103 * @brief Set the clipboard targets to reflect the mimetypes Inkscape can output
1104 */
1105 void ClipboardManagerImpl::_setClipboardTargets()
1106 {
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));
1117 }
1120 /**
1121 * @brief Set the string representation of a 32-bit RGBA color as the clipboard contents
1122 */
1123 void ClipboardManagerImpl::_setClipboardColor(guint32 color)
1124 {
1125 gchar colorstr[16];
1126 g_snprintf(colorstr, 16, "%08x", color);
1127 _clipboard->set_text(colorstr);
1128 }
1131 /**
1132 * @brief Put a notification on the mesage stack
1133 */
1134 void ClipboardManagerImpl::_userWarn(SPDesktop *desktop, char const *msg)
1135 {
1136 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, msg);
1137 }
1141 /* #######################################
1142 ClipboardManager class
1143 ####################################### */
1145 ClipboardManager *ClipboardManager::_instance = NULL;
1147 ClipboardManager::ClipboardManager() {}
1148 ClipboardManager::~ClipboardManager() {}
1149 ClipboardManager *ClipboardManager::get()
1150 {
1151 if ( _instance == NULL )
1152 _instance = new ClipboardManagerImpl;
1153 return _instance;
1154 }
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 :