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