1 /** @file
2 * @brief System-wide clipboard management - implementation
3 */
4 /* Authors:
5 * Krzysztof KosiĆski <tweenk@o2.pl>
6 * Incorporates some code from selection-chemistry.cpp, see that file for more credits.
7 *
8 * Copyright (C) 2008 authors
9 *
10 * This program is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License
12 * as published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * See the file COPYING for details.
16 */
18 #include "ui/clipboard.h"
20 // TODO: reduce header bloat if possible
22 #include <list>
23 #include <algorithm>
24 #include <gtkmm/clipboard.h>
25 #include <glibmm/ustring.h>
26 #include <glibmm/i18n.h>
27 #include <glib/gstdio.h> // for g_file_set_contents etc., used in _onGet and paste
28 #include "gc-core.h"
29 #include "xml/repr.h"
30 #include "inkscape.h"
31 #include "io/stringstream.h"
32 #include "desktop.h"
33 #include "desktop-handles.h"
34 #include "desktop-style.h" // for sp_desktop_set_style, used in _pasteStyle
35 #include "document.h"
36 #include "document-private.h"
37 #include "selection.h"
38 #include "message-stack.h"
39 #include "context-fns.h"
40 #include "dropper-context.h" // used in copy()
41 #include "style.h"
42 #include "extension/db.h" // extension database
43 #include "extension/input.h"
44 #include "extension/output.h"
45 #include "selection-chemistry.h"
46 #include "libnr/nr-rect.h"
47 #include "libnr/nr-convert2geom.h"
48 #include <2geom/rect.h>
49 #include <2geom/transforms.h>
50 #include "box3d.h"
51 #include "gradient-drag.h"
52 #include "sp-item.h"
53 #include "sp-item-transform.h" // for sp_item_scale_rel, used in _pasteSize
54 #include "sp-path.h"
55 #include "sp-pattern.h"
56 #include "sp-shape.h"
57 #include "sp-gradient.h"
58 #include "sp-gradient-reference.h"
59 #include "sp-gradient-fns.h"
60 #include "sp-linear-gradient-fns.h"
61 #include "sp-radial-gradient-fns.h"
62 #include "sp-clippath.h"
63 #include "sp-mask.h"
64 #include "sp-textpath.h"
65 #include "sp-rect.h"
66 #include "live_effects/lpeobject.h"
67 #include "live_effects/lpeobject-reference.h"
68 #include "live_effects/parameter/path.h"
69 #include "svg/svg.h" // for sp_svg_transform_write, used in _copySelection
70 #include "svg/css-ostringstream.h" // used in _parseColor
71 #include "file.h" // for file_import, used in _pasteImage
72 #include "preferences.h" // for used in _pasteImage
73 #include "text-context.h"
74 #include "text-editing.h"
75 #include "tools-switch.h"
76 #include "path-chemistry.h"
77 #include "id-clash.h"
78 #include "unit-constants.h"
79 #include "helper/png-write.h"
80 #include "svg/svg-color.h"
81 #include "sp-namedview.h"
82 #include "snap.h"
84 /// @brief Made up mimetype to represent Gdk::Pixbuf clipboard contents
85 #define CLIPBOARD_GDK_PIXBUF_TARGET "image/x-gdk-pixbuf"
87 #define CLIPBOARD_TEXT_TARGET "text/plain"
89 #ifdef WIN32
90 #include <windows.h>
91 // Clipboard Formats: http://msdn.microsoft.com/en-us/library/ms649013(VS.85).aspx
92 // On Windows, most graphical applications can handle CF_DIB/CF_BITMAP and/or CF_ENHMETAFILE
93 // GTK automatically presents an "image/bmp" target as CF_DIB/CF_BITMAP
94 // Presenting "image/x-emf" as CF_ENHMETAFILE must be done by Inkscape ?
95 #define CLIPBOARD_WIN32_EMF_TARGET "CF_ENHMETAFILE"
96 #define CLIPBOARD_WIN32_EMF_MIME "image/x-emf"
97 #endif
99 namespace Inkscape {
100 namespace UI {
103 /**
104 * @brief Default implementation of the clipboard manager
105 */
106 class ClipboardManagerImpl : public ClipboardManager {
107 public:
108 virtual void copy();
109 virtual void copyPathParameter(Inkscape::LivePathEffect::PathParam *);
110 virtual bool paste(bool in_place);
111 virtual bool pasteStyle();
112 virtual bool pasteSize(bool, bool, bool);
113 virtual bool pastePathEffect();
114 virtual Glib::ustring getPathParameter();
115 virtual Glib::ustring getShapeOrTextObjectId();
116 virtual const gchar *getFirstObjectID();
118 ClipboardManagerImpl();
119 ~ClipboardManagerImpl();
121 private:
122 void _copySelection(Inkscape::Selection *);
123 void _copyUsedDefs(SPItem *);
124 void _copyGradient(SPGradient *);
125 void _copyPattern(SPPattern *);
126 void _copyTextPath(SPTextPath *);
127 Inkscape::XML::Node *_copyNode(Inkscape::XML::Node *, Inkscape::XML::Document *, Inkscape::XML::Node *);
129 void _pasteDocument(SPDocument *, bool in_place);
130 void _pasteDefs(SPDocument *);
131 bool _pasteImage();
132 bool _pasteText();
133 SPCSSAttr *_parseColor(const Glib::ustring &);
134 void _applyPathEffect(SPItem *, gchar const *);
135 SPDocument *_retrieveClipboard(Glib::ustring = "");
137 // clipboard callbacks
138 void _onGet(Gtk::SelectionData &, guint);
139 void _onClear();
141 // various helpers
142 void _createInternalClipboard();
143 void _discardInternalClipboard();
144 Inkscape::XML::Node *_createClipNode();
145 Geom::Scale _getScale(Geom::Point const &, Geom::Point const &, Geom::Rect const &, bool, bool);
146 Glib::ustring _getBestTarget();
147 void _setClipboardTargets();
148 void _setClipboardColor(guint32);
149 void _userWarn(SPDesktop *, char const *);
151 // private properites
152 SPDocument *_clipboardSPDoc; ///< Document that stores the clipboard until someone requests it
153 Inkscape::XML::Node *_defs; ///< Reference to the clipboard document's defs node
154 Inkscape::XML::Node *_root; ///< Reference to the clipboard's root node
155 Inkscape::XML::Node *_clipnode; ///< The node that holds extra information
156 Inkscape::XML::Document *_doc; ///< Reference to the clipboard's Inkscape::XML::Document
158 Glib::RefPtr<Gtk::Clipboard> _clipboard; ///< Handle to the system wide clipboard - for convenience
159 std::list<Glib::ustring> _preferred_targets; ///< List of supported clipboard targets
160 };
163 ClipboardManagerImpl::ClipboardManagerImpl()
164 : _clipboardSPDoc(NULL),
165 _defs(NULL),
166 _root(NULL),
167 _clipnode(NULL),
168 _doc(NULL),
169 _clipboard( Gtk::Clipboard::get() )
170 {
171 // push supported clipboard targets, in order of preference
172 _preferred_targets.push_back("image/x-inkscape-svg");
173 _preferred_targets.push_back("image/svg+xml");
174 _preferred_targets.push_back("image/svg+xml-compressed");
175 #ifdef WIN32
176 _preferred_targets.push_back(CLIPBOARD_WIN32_EMF_MIME);
177 #endif
178 _preferred_targets.push_back("application/pdf");
179 _preferred_targets.push_back("image/x-adobe-illustrator");
180 }
183 ClipboardManagerImpl::~ClipboardManagerImpl() {}
186 /**
187 * @brief Copy selection contents to the clipboard
188 */
189 void ClipboardManagerImpl::copy()
190 {
191 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
192 if ( desktop == NULL ) return;
193 Inkscape::Selection *selection = sp_desktop_selection(desktop);
195 // Special case for when the gradient dragger is active - copies gradient color
196 if (desktop->event_context->get_drag()) {
197 GrDrag *drag = desktop->event_context->get_drag();
198 if (drag->hasSelection()) {
199 _setClipboardColor(drag->getColor());
200 _discardInternalClipboard();
201 return;
202 }
203 }
205 // Special case for when the color picker ("dropper") is active - copies color under cursor
206 if (tools_isactive(desktop, TOOLS_DROPPER)) {
207 _setClipboardColor(sp_dropper_context_get_color(desktop->event_context));
208 _discardInternalClipboard();
209 return;
210 }
212 // Special case for when the text tool is active - if some text is selected, copy plain text,
213 // not the object that holds it
214 if (tools_isactive(desktop, TOOLS_TEXT)) {
215 Glib::ustring selected_text = sp_text_get_selected_text(desktop->event_context);
216 if (!selected_text.empty()) {
217 _clipboard->set_text(selected_text);
218 _discardInternalClipboard();
219 return;
220 }
221 }
223 if (selection->isEmpty()) { // check whether something is selected
224 _userWarn(desktop, _("Nothing was copied."));
225 return;
226 }
227 _discardInternalClipboard();
229 _createInternalClipboard(); // construct a new clipboard document
230 _copySelection(selection); // copy all items in the selection to the internal clipboard
231 fit_canvas_to_drawing(_clipboardSPDoc);
233 _setClipboardTargets();
234 }
237 /**
238 * @brief Copy a Live Path Effect path parameter to the clipboard
239 * @param pp The path parameter to store in the clipboard
240 */
241 void ClipboardManagerImpl::copyPathParameter(Inkscape::LivePathEffect::PathParam *pp)
242 {
243 if ( pp == NULL ) return;
244 gchar *svgd = sp_svg_write_path( pp->get_pathvector() );
245 if ( svgd == NULL || *svgd == '\0' ) return;
247 _discardInternalClipboard();
248 _createInternalClipboard();
250 Inkscape::XML::Node *pathnode = _doc->createElement("svg:path");
251 pathnode->setAttribute("d", svgd);
252 g_free(svgd);
253 _root->appendChild(pathnode);
254 Inkscape::GC::release(pathnode);
256 fit_canvas_to_drawing(_clipboardSPDoc);
257 _setClipboardTargets();
258 }
260 /**
261 * @brief Paste from the system clipboard into the active desktop
262 * @param in_place Whether to put the contents where they were when copied
263 */
264 bool ClipboardManagerImpl::paste(bool in_place)
265 {
266 // do any checking whether we really are able to paste before requesting the contents
267 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
268 if ( desktop == NULL ) return false;
269 if ( Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false ) return false;
271 Glib::ustring target = _getBestTarget();
273 // Special cases of clipboard content handling go here
274 // Note that target priority is determined in _getBestTarget.
275 // TODO: Handle x-special/gnome-copied-files and text/uri-list to support pasting files
277 // if there is an image on the clipboard, paste it
278 if ( target == CLIPBOARD_GDK_PIXBUF_TARGET ) return _pasteImage();
279 // if there's only text, paste it into a selected text object or create a new one
280 if ( target == CLIPBOARD_TEXT_TARGET ) return _pasteText();
282 // otherwise, use the import extensions
283 SPDocument *tempdoc = _retrieveClipboard(target);
284 if ( tempdoc == NULL ) {
285 _userWarn(desktop, _("Nothing on the clipboard."));
286 return false;
287 }
289 _pasteDocument(tempdoc, in_place);
290 sp_document_unref(tempdoc);
292 return true;
293 }
295 /**
296 * @brief Returns the id of the first visible copied object
297 */
298 const gchar *ClipboardManagerImpl::getFirstObjectID()
299 {
300 SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
301 if ( tempdoc == NULL ) {
302 return NULL;
303 }
305 Inkscape::XML::Node
306 *root = sp_document_repr_root(tempdoc);
308 if (!root)
309 return NULL;
311 Inkscape::XML::Node *ch = sp_repr_children(root);
312 while (ch != NULL &&
313 strcmp(ch->name(), "svg:g") &&
314 strcmp(ch->name(), "svg:path") &&
315 strcmp(ch->name(), "svg:use") &&
316 strcmp(ch->name(), "svg:text") &&
317 strcmp(ch->name(), "svg:image") &&
318 strcmp(ch->name(), "svg:rect")
319 )
320 ch = ch->next();
322 if (ch) {
323 return ch->attribute("id");
324 }
326 return NULL;
327 }
330 /**
331 * @brief Implements the Paste Style action
332 */
333 bool ClipboardManagerImpl::pasteStyle()
334 {
335 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
336 if (desktop == NULL) return false;
338 // check whether something is selected
339 Inkscape::Selection *selection = sp_desktop_selection(desktop);
340 if (selection->isEmpty()) {
341 _userWarn(desktop, _("Select <b>object(s)</b> to paste style to."));
342 return false;
343 }
345 SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
346 if ( tempdoc == NULL ) {
347 _userWarn(desktop, _("No style on the clipboard."));
348 return false;
349 }
351 Inkscape::XML::Node
352 *root = sp_document_repr_root(tempdoc),
353 *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
355 bool pasted = false;
357 if (clipnode) {
358 _pasteDefs(tempdoc);
359 SPCSSAttr *style = sp_repr_css_attr(clipnode, "style");
360 sp_desktop_set_style(desktop, style);
361 pasted = true;
362 }
363 else {
364 _userWarn(desktop, _("No style on the clipboard."));
365 }
367 sp_document_unref(tempdoc);
368 return pasted;
369 }
372 /**
373 * @brief Resize the selection or each object in the selection to match the clipboard's size
374 * @param separately Whether to scale each object in the selection separately
375 * @param apply_x Whether to scale the width of objects / selection
376 * @param apply_y Whether to scale the height of objects / selection
377 */
378 bool ClipboardManagerImpl::pasteSize(bool separately, bool apply_x, bool apply_y)
379 {
380 if(!apply_x && !apply_y) return false; // pointless parameters
382 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
383 if ( desktop == NULL ) return false;
384 Inkscape::Selection *selection = sp_desktop_selection(desktop);
385 if (selection->isEmpty()) {
386 _userWarn(desktop, _("Select <b>object(s)</b> to paste size to."));
387 return false;
388 }
390 // FIXME: actually, this should accept arbitrary documents
391 SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
392 if ( tempdoc == NULL ) {
393 _userWarn(desktop, _("No size on the clipboard."));
394 return false;
395 }
397 // retrieve size ifomration from the clipboard
398 Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
399 Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
400 bool pasted = false;
401 if (clipnode) {
402 Geom::Point min, max;
403 sp_repr_get_point(clipnode, "min", &min);
404 sp_repr_get_point(clipnode, "max", &max);
406 // resize each object in the selection
407 if (separately) {
408 for (GSList *i = const_cast<GSList*>(selection->itemList()) ; i ; i = i->next) {
409 SPItem *item = SP_ITEM(i->data);
410 Geom::OptRect obj_size = sp_item_bbox_desktop(item);
411 if ( !obj_size ) continue;
412 sp_item_scale_rel(item, _getScale(min, max, *obj_size, apply_x, apply_y));
413 }
414 }
415 // resize the selection as a whole
416 else {
417 Geom::OptRect sel_size = selection->bounds();
418 if ( sel_size ) {
419 sp_selection_scale_relative(selection, sel_size->midpoint(),
420 _getScale(min, max, *sel_size, apply_x, apply_y));
421 }
422 }
423 pasted = true;
424 }
425 sp_document_unref(tempdoc);
426 return pasted;
427 }
430 /**
431 * @brief Applies a path effect from the clipboard to the selected path
432 */
433 bool ClipboardManagerImpl::pastePathEffect()
434 {
435 /** @todo FIXME: pastePathEffect crashes when moving the path with the applied effect,
436 segfaulting in fork_private_if_necessary(). */
438 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
439 if ( desktop == NULL )
440 return false;
442 Inkscape::Selection *selection = sp_desktop_selection(desktop);
443 if (selection && selection->isEmpty()) {
444 _userWarn(desktop, _("Select <b>object(s)</b> to paste live path effect to."));
445 return false;
446 }
448 SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
449 if ( tempdoc ) {
450 Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
451 Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
452 if ( clipnode ) {
453 gchar const *effect = clipnode->attribute("inkscape:path-effect");
454 if ( effect ) {
455 _pasteDefs(tempdoc);
456 // make sure all selected items are converted to paths first (i.e. rectangles)
457 sp_selected_path_to_curves(desktop, false);
458 for (GSList *item = const_cast<GSList *>(selection->itemList()) ; item ; item = item->next) {
459 _applyPathEffect(reinterpret_cast<SPItem*>(item->data), effect);
460 }
462 return true;
463 }
464 }
465 }
467 // no_effect:
468 _userWarn(desktop, _("No effect on the clipboard."));
469 return false;
470 }
473 /**
474 * @brief Get LPE path data from the clipboard
475 * @return The retrieved path data (contents of the d attribute), or "" if no path was found
476 */
477 Glib::ustring ClipboardManagerImpl::getPathParameter()
478 {
479 SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
480 if ( tempdoc == NULL ) {
481 _userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
482 return "";
483 }
484 Inkscape::XML::Node
485 *root = sp_document_repr_root(tempdoc),
486 *path = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
487 if ( path == NULL ) {
488 _userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
489 sp_document_unref(tempdoc);
490 return "";
491 }
492 gchar const *svgd = path->attribute("d");
493 return svgd;
494 }
497 /**
498 * @brief Get object id of a shape or text item from the clipboard
499 * @return The retrieved id string (contents of the id attribute), or "" if no shape or text item was found
500 */
501 Glib::ustring ClipboardManagerImpl::getShapeOrTextObjectId()
502 {
503 SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
504 if ( tempdoc == NULL ) {
505 _userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
506 return "";
507 }
508 Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
510 Inkscape::XML::Node *repr = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
511 if ( repr == NULL )
512 repr = sp_repr_lookup_name(root, "svg:text", -1);
514 if ( repr == NULL ) {
515 _userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
516 sp_document_unref(tempdoc);
517 return "";
518 }
519 gchar const *svgd = repr->attribute("id");
520 return svgd;
521 }
524 /**
525 * @brief Iterate over a list of items and copy them to the clipboard.
526 */
527 void ClipboardManagerImpl::_copySelection(Inkscape::Selection *selection)
528 {
529 GSList const *items = selection->itemList();
530 // copy the defs used by all items
531 for (GSList *i = const_cast<GSList *>(items) ; i != NULL ; i = i->next) {
532 _copyUsedDefs(SP_ITEM (i->data));
533 }
535 // copy the representation of the items
536 GSList *sorted_items = g_slist_copy(const_cast<GSList *>(items));
537 sorted_items = g_slist_sort(sorted_items, (GCompareFunc) sp_object_compare_position);
539 for (GSList *i = sorted_items ; i ; i = i->next) {
540 if (!SP_IS_ITEM(i->data)) continue;
541 Inkscape::XML::Node *obj = SP_OBJECT_REPR(i->data);
542 Inkscape::XML::Node *obj_copy = _copyNode(obj, _doc, _root);
544 // copy complete inherited style
545 SPCSSAttr *css = sp_repr_css_attr_inherited(obj, "style");
546 sp_repr_css_set(obj_copy, css, "style");
547 sp_repr_css_attr_unref(css);
549 // write the complete accumulated transform passed to us
550 // (we're dealing with unattached representations, so we write to their attributes
551 // instead of using sp_item_set_transform)
552 gchar *transform_str = sp_svg_transform_write(sp_item_i2doc_affine(SP_ITEM(i->data)));
553 obj_copy->setAttribute("transform", transform_str);
554 g_free(transform_str);
555 }
557 // copy style for Paste Style action
558 if (sorted_items) {
559 if(SP_IS_ITEM(sorted_items->data)) {
560 SPCSSAttr *style = take_style_from_item((SPItem *) sorted_items->data);
561 sp_repr_css_set(_clipnode, style, "style");
562 sp_repr_css_attr_unref(style);
563 }
565 // copy path effect from the first path
566 if (SP_IS_OBJECT(sorted_items->data)) {
567 gchar const *effect = SP_OBJECT_REPR(sorted_items->data)->attribute("inkscape:path-effect");
568 if (effect) {
569 _clipnode->setAttribute("inkscape:path-effect", effect);
570 }
571 }
572 }
574 Geom::OptRect size = selection->bounds();
575 if (size) {
576 sp_repr_set_point(_clipnode, "min", size->min());
577 sp_repr_set_point(_clipnode, "max", size->max());
578 }
580 g_slist_free(sorted_items);
581 }
584 /**
585 * @brief Recursively copy all the definitions used by a given item to the clipboard defs
586 */
587 void ClipboardManagerImpl::_copyUsedDefs(SPItem *item)
588 {
589 // copy fill and stroke styles (patterns and gradients)
590 SPStyle *style = SP_OBJECT_STYLE(item);
592 if (style && (style->fill.isPaintserver())) {
593 SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
594 if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
595 _copyGradient(SP_GRADIENT(server));
596 if (SP_IS_PATTERN(server))
597 _copyPattern(SP_PATTERN(server));
598 }
599 if (style && (style->stroke.isPaintserver())) {
600 SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
601 if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
602 _copyGradient(SP_GRADIENT(server));
603 if (SP_IS_PATTERN(server))
604 _copyPattern(SP_PATTERN(server));
605 }
607 // For shapes, copy all of the shape's markers
608 if (SP_IS_SHAPE(item)) {
609 SPShape *shape = SP_SHAPE (item);
610 for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
611 if (shape->marker[i]) {
612 _copyNode(SP_OBJECT_REPR(SP_OBJECT(shape->marker[i])), _doc, _defs);
613 }
614 }
615 }
616 // For lpe items, copy lpe stack if applicable
617 if (SP_IS_LPE_ITEM(item)) {
618 SPLPEItem *lpeitem = SP_LPE_ITEM (item);
619 if (sp_lpe_item_has_path_effect(lpeitem)) {
620 for (PathEffectList::iterator it = lpeitem->path_effect_list->begin(); it != lpeitem->path_effect_list->end(); ++it)
621 {
622 LivePathEffectObject *lpeobj = (*it)->lpeobject;
623 if (lpeobj)
624 _copyNode(SP_OBJECT_REPR(SP_OBJECT(lpeobj)), _doc, _defs);
625 }
626 }
627 }
628 // For 3D boxes, copy perspectives
629 if (SP_IS_BOX3D(item)) {
630 _copyNode(SP_OBJECT_REPR(SP_OBJECT(box3d_get_perspective(SP_BOX3D(item)))), _doc, _defs);
631 }
632 // Copy text paths
633 if (SP_IS_TEXT_TEXTPATH(item)) {
634 _copyTextPath(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
635 }
636 // Copy clipping objects
637 if (item->clip_ref->getObject()) {
638 _copyNode(SP_OBJECT_REPR(item->clip_ref->getObject()), _doc, _defs);
639 }
640 // Copy mask objects
641 if (item->mask_ref->getObject()) {
642 SPObject *mask = item->mask_ref->getObject();
643 _copyNode(SP_OBJECT_REPR(mask), _doc, _defs);
644 // recurse into the mask for its gradients etc.
645 for (SPObject *o = SP_OBJECT(mask)->children ; o != NULL ; o = o->next) {
646 if (SP_IS_ITEM(o))
647 _copyUsedDefs(SP_ITEM(o));
648 }
649 }
650 // Copy filters
651 if (style->getFilter()) {
652 SPObject *filter = style->getFilter();
653 if (SP_IS_FILTER(filter)) {
654 _copyNode(SP_OBJECT_REPR(filter), _doc, _defs);
655 }
656 }
658 // recurse
659 for (SPObject *o = SP_OBJECT(item)->children ; o != NULL ; o = o->next) {
660 if (SP_IS_ITEM(o))
661 _copyUsedDefs(SP_ITEM(o));
662 }
663 }
666 /**
667 * @brief Copy a single gradient to the clipboard's defs element
668 */
669 void ClipboardManagerImpl::_copyGradient(SPGradient *gradient)
670 {
671 while (gradient) {
672 // climb up the refs, copying each one in the chain
673 _copyNode(SP_OBJECT_REPR(gradient), _doc, _defs);
674 gradient = gradient->ref->getObject();
675 }
676 }
679 /**
680 * @brief Copy a single pattern to the clipboard document's defs element
681 */
682 void ClipboardManagerImpl::_copyPattern(SPPattern *pattern)
683 {
684 // climb up the references, copying each one in the chain
685 while (pattern) {
686 _copyNode(SP_OBJECT_REPR(pattern), _doc, _defs);
688 // items in the pattern may also use gradients and other patterns, so recurse
689 for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL ; child = SP_OBJECT_NEXT(child) ) {
690 if (!SP_IS_ITEM (child)) continue;
691 _copyUsedDefs(SP_ITEM(child));
692 }
693 pattern = pattern->ref->getObject();
694 }
695 }
698 /**
699 * @brief Copy a text path to the clipboard's defs element
700 */
701 void ClipboardManagerImpl::_copyTextPath(SPTextPath *tp)
702 {
703 SPItem *path = sp_textpath_get_path_item(tp);
704 if(!path) return;
705 Inkscape::XML::Node *path_node = SP_OBJECT_REPR(path);
707 // Do not copy the text path to defs if it's already copied
708 if(sp_repr_lookup_child(_root, "id", path_node->attribute("id"))) return;
709 _copyNode(path_node, _doc, _defs);
710 }
713 /**
714 * @brief Copy a single XML node from one document to another
715 * @param node The node to be copied
716 * @param target_doc The document to which the node is to be copied
717 * @param parent The node in the target document which will become the parent of the copied node
718 * @return Pointer to the copied node
719 */
720 Inkscape::XML::Node *ClipboardManagerImpl::_copyNode(Inkscape::XML::Node *node, Inkscape::XML::Document *target_doc, Inkscape::XML::Node *parent)
721 {
722 Inkscape::XML::Node *dup = node->duplicate(target_doc);
723 parent->appendChild(dup);
724 Inkscape::GC::release(dup);
725 return dup;
726 }
729 /**
730 * @brief Paste the contents of a document into the active desktop
731 * @param clipdoc The document to paste
732 * @param in_place Whether to paste the selection where it was when copied
733 * @pre @c clipdoc is not empty and items can be added to the current layer
734 */
735 void ClipboardManagerImpl::_pasteDocument(SPDocument *clipdoc, bool in_place)
736 {
737 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
738 SPDocument *target_document = sp_desktop_document(desktop);
739 Inkscape::XML::Node
740 *root = sp_document_repr_root(clipdoc),
741 *target_parent = SP_OBJECT_REPR(desktop->currentLayer());
742 Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
744 // copy definitions
745 _pasteDefs(clipdoc);
747 // copy objects
748 GSList *pasted_objects = NULL;
749 for (Inkscape::XML::Node *obj = root->firstChild() ; obj ; obj = obj->next()) {
750 // Don't copy metadata, defs, named views and internal clipboard contents to the document
751 if (!strcmp(obj->name(), "svg:defs")) continue;
752 if (!strcmp(obj->name(), "svg:metadata")) continue;
753 if (!strcmp(obj->name(), "sodipodi:namedview")) continue;
754 if (!strcmp(obj->name(), "inkscape:clipboard")) continue;
755 Inkscape::XML::Node *obj_copy = _copyNode(obj, target_xmldoc, target_parent);
756 pasted_objects = g_slist_prepend(pasted_objects, (gpointer) obj_copy);
757 }
759 // Change the selection to the freshly pasted objects
760 Inkscape::Selection *selection = sp_desktop_selection(desktop);
761 selection->setReprList(pasted_objects);
763 // invers apply parent transform
764 Geom::Matrix doc2parent = sp_item_i2doc_affine(SP_ITEM(desktop->currentLayer())).inverse();
765 sp_selection_apply_affine(selection, doc2parent);
767 // Update (among other things) all curves in paths, for bounds() to work
768 sp_document_ensure_up_to_date(target_document);
770 // move selection either to original position (in_place) or to mouse pointer
771 Geom::OptRect sel_bbox = selection->bounds();
772 if (sel_bbox) {
773 // get offset of selection to original position of copied elements
774 Geom::Point pos_original;
775 Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
776 if (clipnode) {
777 Geom::Point min, max;
778 sp_repr_get_point(clipnode, "min", &min);
779 sp_repr_get_point(clipnode, "max", &max);
780 pos_original = Geom::Point(min[Geom::X], max[Geom::Y]);
781 }
782 Geom::Point offset = pos_original - sel_bbox->corner(3);
784 if (!in_place) {
785 SnapManager &m = desktop->namedview->snap_manager;
786 m.setup(desktop, false); // Don't display the snapindicator
788 // get offset from mouse pointer to bbox center, snap to grid if enabled
789 Geom::Point mouse_offset = desktop->point() - sel_bbox->midpoint();
790 offset = m.multipleOfGridPitch(mouse_offset - offset) + offset;
791 }
793 sp_selection_move_relative(selection, offset);
794 }
796 g_slist_free(pasted_objects);
797 }
800 /**
801 * @brief Paste SVG defs from the document retrieved from the clipboard into the active document
802 * @param clipdoc The document to paste
803 * @pre @c clipdoc != NULL and pasting into the active document is possible
804 */
805 void ClipboardManagerImpl::_pasteDefs(SPDocument *clipdoc)
806 {
807 // boilerplate vars copied from _pasteDocument
808 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
809 SPDocument *target_document = sp_desktop_document(desktop);
810 Inkscape::XML::Node
811 *root = sp_document_repr_root(clipdoc),
812 *defs = sp_repr_lookup_name(root, "svg:defs", 1),
813 *target_defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(target_document));
814 Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
816 prevent_id_clashes(clipdoc, target_document);
818 for (Inkscape::XML::Node *def = defs->firstChild() ; def ; def = def->next()) {
819 _copyNode(def, target_xmldoc, target_defs);
820 }
821 }
824 /**
825 * @brief Retrieve a bitmap image from the clipboard and paste it into the active document
826 */
827 bool ClipboardManagerImpl::_pasteImage()
828 {
829 SPDocument *doc = SP_ACTIVE_DOCUMENT;
830 if ( doc == NULL ) return false;
832 // retrieve image data
833 Glib::RefPtr<Gdk::Pixbuf> img = _clipboard->wait_for_image();
834 if (!img) return false;
836 // Very stupid hack: Write into a file, then import the file into the document.
837 // To avoid using tmpfile and POSIX file handles, make the filename based on current time.
838 // This wasn't my idea, I just copied this from selection-chemistry.cpp
839 // and just can't think of something saner at the moment. Pasting more than
840 // one image per second will overwrite the image.
841 // However, I don't think anyone is able to copy a _different_ image into inkscape
842 // in 1 second.
843 time_t rawtime;
844 char image_filename[128];
846 time(&rawtime);
847 strftime(image_filename, 128, "inkscape_pasted_image_%Y%m%d_%H%M%S.png", localtime( &rawtime ));
848 /// @todo Check whether the encoding is correct here
849 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
850 std::string save_folder = Glib::filename_from_utf8(prefs->getString("/dialogs/save_as/path"));
852 gchar *image_path = g_build_filename(save_folder.data(), image_filename, NULL);
853 img->save(image_path, "png");
854 file_import(doc, image_path, NULL);
855 g_free(image_path);
857 return true;
858 }
860 /**
861 * @brief Paste text into the selected text object or create a new one to hold it
862 */
863 bool ClipboardManagerImpl::_pasteText()
864 {
865 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
866 if ( desktop == NULL ) return false;
868 // if the text editing tool is active, paste the text into the active text object
869 if (tools_isactive(desktop, TOOLS_TEXT))
870 return sp_text_paste_inline(desktop->event_context);
872 // try to parse the text as a color and, if successful, apply it as the current style
873 SPCSSAttr *css = _parseColor(_clipboard->wait_for_text());
874 if (css) {
875 sp_desktop_set_style(desktop, css);
876 return true;
877 }
879 return false;
880 }
883 /**
884 * @brief Attempt to parse the passed string as a hexadecimal RGB or RGBA color
885 * @param text The Glib::ustring to parse
886 * @return New CSS style representation if the parsing was successful, NULL otherwise
887 */
888 SPCSSAttr *ClipboardManagerImpl::_parseColor(const Glib::ustring &text)
889 {
890 // TODO reuse existing code instead of replicating here.
891 Glib::ustring::size_type len = text.bytes();
892 char *str = const_cast<char *>(text.data());
893 bool attempt_alpha = false;
894 if ( !str || ( *str == '\0' ) ) return NULL; // this is OK due to boolean short-circuit
896 // those conditionals guard against parsing e.g. the string "fab" as "fab000"
897 // (incomplete color) and "45fab71" as "45fab710" (incomplete alpha)
898 if ( *str == '#' ) {
899 if ( len < 7 ) return NULL;
900 if ( len >= 9 ) attempt_alpha = true;
901 } else {
902 if ( len < 6 ) return NULL;
903 if ( len >= 8 ) attempt_alpha = true;
904 }
906 unsigned int color = 0, alpha = 0xff;
908 // skip a leading #, if present
909 if ( *str == '#' ) ++str;
911 // try to parse first 6 digits
912 int res = sscanf(str, "%6x", &color);
913 if ( res && ( res != EOF ) ) {
914 if (attempt_alpha) {// try to parse alpha if there's enough characters
915 sscanf(str + 6, "%2x", &alpha);
916 if ( !res || res == EOF ) alpha = 0xff;
917 }
919 SPCSSAttr *color_css = sp_repr_css_attr_new();
921 // print and set properties
922 gchar color_str[16];
923 g_snprintf(color_str, 16, "#%06x", color);
924 sp_repr_css_set_property(color_css, "fill", color_str);
926 float opacity = static_cast<float>(alpha)/static_cast<float>(0xff);
927 if (opacity > 1.0) opacity = 1.0; // safeguard
928 Inkscape::CSSOStringStream opcss;
929 opcss << opacity;
930 sp_repr_css_set_property(color_css, "fill-opacity", opcss.str().data());
931 return color_css;
932 }
933 return NULL;
934 }
937 /**
938 * @brief Applies a pasted path effect to a given item
939 */
940 void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effect)
941 {
942 if ( item == NULL ) return;
943 if ( SP_IS_RECT(item) ) return;
945 if (SP_IS_LPE_ITEM(item))
946 {
947 SPLPEItem *lpeitem = SP_LPE_ITEM(item);
948 SPObject *obj = sp_uri_reference_resolve(_clipboardSPDoc, effect);
949 if (!obj) return;
950 // if the effect is not used by anyone, we might as well take it
951 LivePathEffectObject *lpeobj = LIVEPATHEFFECT(obj)->fork_private_if_necessary(1);
952 sp_lpe_item_add_path_effect(lpeitem, lpeobj);
953 }
954 }
957 /**
958 * @brief Retrieve the clipboard contents as a document
959 * @return Clipboard contents converted to SPDocument, or NULL if no suitable content was present
960 */
961 SPDocument *ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_target)
962 {
963 Glib::ustring best_target;
964 if ( required_target == "" )
965 best_target = _getBestTarget();
966 else
967 best_target = required_target;
969 if ( best_target == "" ) {
970 return NULL;
971 }
973 // FIXME: Temporary hack until we add memory input.
974 // Save the clipboard contents to some file, then read it
975 gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-import", NULL );
977 bool file_saved = false;
978 Glib::ustring target = best_target;
980 #ifdef WIN32
981 if (best_target == CLIPBOARD_WIN32_EMF_TARGET)
982 { // Try to save clipboard data as en emf file (using win32 api)
983 if (OpenClipboard(NULL)) {
984 HGLOBAL hglb = GetClipboardData(CF_ENHMETAFILE);
985 if (hglb) {
986 HENHMETAFILE hemf = CopyEnhMetaFile((HENHMETAFILE) hglb, filename);
987 if (hemf) {
988 file_saved = true;
989 target = CLIPBOARD_WIN32_EMF_MIME;
990 DeleteEnhMetaFile(hemf);
991 }
992 }
993 CloseClipboard();
994 }
995 }
996 #endif
998 if (!file_saved) {
999 if ( !_clipboard->wait_is_target_available(best_target) ) {
1000 return NULL;
1001 }
1003 // doing this synchronously makes better sense
1004 // TODO: use another method because this one is badly broken imo.
1005 // from documentation: "Returns: A SelectionData object, which will be invalid if retrieving the given target failed."
1006 // I don't know how to check whether an object is 'valid' or not, unusable if that's not possible...
1007 Gtk::SelectionData sel = _clipboard->wait_for_contents(best_target);
1008 target = sel.get_target(); // this can crash if the result was invalid of last function. No way to check for this :(
1010 // FIXME: Temporary hack until we add memory input.
1011 // Save the clipboard contents to some file, then read it
1012 g_file_set_contents(filename, (const gchar *) sel.get_data(), sel.get_length(), NULL);
1013 }
1015 // there is no specific plain SVG input extension, so if we can paste the Inkscape SVG format,
1016 // we use the image/svg+xml mimetype to look up the input extension
1017 if(target == "image/x-inkscape-svg")
1018 target = "image/svg+xml";
1020 Inkscape::Extension::DB::InputList inlist;
1021 Inkscape::Extension::db.get_input_list(inlist);
1022 Inkscape::Extension::DB::InputList::const_iterator in = inlist.begin();
1023 for (; in != inlist.end() && target != (*in)->get_mimetype() ; ++in);
1024 if ( in == inlist.end() )
1025 return NULL; // this shouldn't happen unless _getBestTarget returns something bogus
1027 SPDocument *tempdoc = NULL;
1028 try {
1029 tempdoc = (*in)->open(filename);
1030 } catch (...) {
1031 }
1032 g_unlink(filename);
1033 g_free(filename);
1035 return tempdoc;
1036 }
1039 /**
1040 * @brief Callback called when some other application requests data from Inkscape
1041 *
1042 * Finds a suitable output extension to save the internal clipboard document,
1043 * then saves it to memory and sets the clipboard contents.
1044 */
1045 void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint /*info*/)
1046 {
1047 g_assert( _clipboardSPDoc != NULL );
1049 Glib::ustring target = sel.get_target();
1050 if(target == "") return; // this shouldn't happen
1052 if (target == CLIPBOARD_TEXT_TARGET) {
1053 target = "image/x-inkscape-svg";
1054 }
1056 Inkscape::Extension::DB::OutputList outlist;
1057 Inkscape::Extension::db.get_output_list(outlist);
1058 Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
1059 for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out);
1060 if ( out == outlist.end() && target != "image/png") return; // this also shouldn't happen
1062 // FIXME: Temporary hack until we add support for memory output.
1063 // Save to a temporary file, read it back and then set the clipboard contents
1064 gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export", NULL );
1065 gsize len; gchar *data;
1067 try {
1068 if (out == outlist.end() && target == "image/png")
1069 {
1070 gdouble dpi = PX_PER_IN;
1071 guint32 bgcolor = 0x00000000;
1073 Geom::Point origin (SP_ROOT(_clipboardSPDoc->root)->x.computed, SP_ROOT(_clipboardSPDoc->root)->y.computed);
1074 Geom::Rect area = Geom::Rect(origin, origin + sp_document_dimensions(_clipboardSPDoc));
1076 unsigned long int width = (unsigned long int) (area.width() * dpi / PX_PER_IN + 0.5);
1077 unsigned long int height = (unsigned long int) (area.height() * dpi / PX_PER_IN + 0.5);
1079 // read from namedview
1080 Inkscape::XML::Node *nv = sp_repr_lookup_name (_clipboardSPDoc->rroot, "sodipodi:namedview");
1081 if (nv && nv->attribute("pagecolor"))
1082 bgcolor = sp_svg_read_color(nv->attribute("pagecolor"), 0xffffff00);
1083 if (nv && nv->attribute("inkscape:pageopacity"))
1084 bgcolor |= SP_COLOR_F_TO_U(sp_repr_get_double_attribute (nv, "inkscape:pageopacity", 1.0));
1086 sp_export_png_file(_clipboardSPDoc, filename, area, width, height, dpi, dpi, bgcolor, NULL, NULL, true, NULL);
1087 }
1088 else
1089 {
1090 if (!(*out)->loaded()) {
1091 // Need to load the extension.
1092 (*out)->set_state(Inkscape::Extension::Extension::STATE_LOADED);
1093 }
1094 (*out)->save(_clipboardSPDoc, filename);
1095 }
1096 g_file_get_contents(filename, &data, &len, NULL);
1098 sel.set(8, (guint8 const *) data, len);
1099 } catch (...) {
1100 }
1102 g_unlink(filename); // delete the temporary file
1103 g_free(filename);
1104 }
1107 /**
1108 * @brief Callback when someone else takes the clipboard
1109 *
1110 * When the clipboard owner changes, this callback clears the internal clipboard document
1111 * to reduce memory usage.
1112 */
1113 void ClipboardManagerImpl::_onClear()
1114 {
1115 // why is this called before _onGet???
1116 //_discardInternalClipboard();
1117 }
1120 /**
1121 * @brief Creates an internal clipboard document from scratch
1122 */
1123 void ClipboardManagerImpl::_createInternalClipboard()
1124 {
1125 if ( _clipboardSPDoc == NULL ) {
1126 _clipboardSPDoc = sp_document_new(NULL, false, true);
1127 //g_assert( _clipboardSPDoc != NULL );
1128 _defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(_clipboardSPDoc));
1129 _doc = sp_document_repr_doc(_clipboardSPDoc);
1130 _root = sp_document_repr_root(_clipboardSPDoc);
1132 _clipnode = _doc->createElement("inkscape:clipboard");
1133 _root->appendChild(_clipnode);
1134 Inkscape::GC::release(_clipnode);
1135 }
1136 }
1139 /**
1140 * @brief Deletes the internal clipboard document
1141 */
1142 void ClipboardManagerImpl::_discardInternalClipboard()
1143 {
1144 if ( _clipboardSPDoc != NULL ) {
1145 sp_document_unref(_clipboardSPDoc);
1146 _clipboardSPDoc = NULL;
1147 _defs = NULL;
1148 _doc = NULL;
1149 _root = NULL;
1150 _clipnode = NULL;
1151 }
1152 }
1155 /**
1156 * @brief Get the scale to resize an item, based on the command and desktop state
1157 */
1158 Geom::Scale ClipboardManagerImpl::_getScale(Geom::Point const &min, Geom::Point const &max, Geom::Rect const &obj_rect, bool apply_x, bool apply_y)
1159 {
1160 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1161 double scale_x = 1.0;
1162 double scale_y = 1.0;
1164 if (apply_x) {
1165 scale_x = (max[Geom::X] - min[Geom::X]) / obj_rect[Geom::X].extent();
1166 }
1167 if (apply_y) {
1168 scale_y = (max[Geom::Y] - min[Geom::Y]) / obj_rect[Geom::Y].extent();
1169 }
1170 // If the "lock aspect ratio" button is pressed and we paste only a single coordinate,
1171 // resize the second one by the same ratio too
1172 if (desktop->isToolboxButtonActive("lock")) {
1173 if (apply_x && !apply_y) scale_y = scale_x;
1174 if (apply_y && !apply_x) scale_x = scale_y;
1175 }
1177 return Geom::Scale(scale_x, scale_y);
1178 }
1181 /**
1182 * @brief Find the most suitable clipboard target
1183 */
1184 Glib::ustring ClipboardManagerImpl::_getBestTarget()
1185 {
1186 std::list<Glib::ustring> targets = _clipboard->wait_for_targets();
1188 // clipboard target debugging snippet
1189 /*
1190 g_debug("Begin clipboard targets");
1191 for ( std::list<Glib::ustring>::iterator x = targets.begin() ; x != targets.end(); ++x )
1192 g_debug("Clipboard target: %s", (*x).data());
1193 g_debug("End clipboard targets\n");
1194 //*/
1196 for(std::list<Glib::ustring>::iterator i = _preferred_targets.begin() ;
1197 i != _preferred_targets.end() ; ++i)
1198 {
1199 if ( std::find(targets.begin(), targets.end(), *i) != targets.end() )
1200 return *i;
1201 }
1202 #ifdef WIN32
1203 if (OpenClipboard(NULL))
1204 { // If both bitmap and metafile are present, pick the one that was exported first.
1205 UINT format = EnumClipboardFormats(0);
1206 while (format) {
1207 if (format == CF_ENHMETAFILE || format == CF_DIB || format == CF_BITMAP)
1208 break;
1209 format = EnumClipboardFormats(format);
1210 }
1211 CloseClipboard();
1213 if (format == CF_ENHMETAFILE)
1214 return CLIPBOARD_WIN32_EMF_TARGET;
1215 if (format == CF_DIB || format == CF_BITMAP)
1216 return CLIPBOARD_GDK_PIXBUF_TARGET;
1217 }
1219 if (IsClipboardFormatAvailable(CF_ENHMETAFILE))
1220 return CLIPBOARD_WIN32_EMF_TARGET;
1221 #endif
1222 if (_clipboard->wait_is_image_available())
1223 return CLIPBOARD_GDK_PIXBUF_TARGET;
1224 if (_clipboard->wait_is_text_available())
1225 return CLIPBOARD_TEXT_TARGET;
1227 return "";
1228 }
1231 /**
1232 * @brief Set the clipboard targets to reflect the mimetypes Inkscape can output
1233 */
1234 void ClipboardManagerImpl::_setClipboardTargets()
1235 {
1236 Inkscape::Extension::DB::OutputList outlist;
1237 Inkscape::Extension::db.get_output_list(outlist);
1238 std::list<Gtk::TargetEntry> target_list;
1239 bool plaintextSet = false;
1240 for (Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin() ; out != outlist.end() ; ++out) {
1241 if ( !(*out)->deactivated() ) {
1242 Glib::ustring mime = (*out)->get_mimetype();
1243 if (mime != CLIPBOARD_TEXT_TARGET) {
1244 if ( !plaintextSet && (mime.find("svg") == Glib::ustring::npos) ) {
1245 target_list.push_back(Gtk::TargetEntry(CLIPBOARD_TEXT_TARGET));
1246 plaintextSet = true;
1247 }
1248 target_list.push_back(Gtk::TargetEntry(mime));
1249 }
1250 }
1251 }
1253 // Add PNG export explicitly since there is no extension for this...
1254 // On Windows, GTK will also present this as a CF_DIB/CF_BITMAP
1255 target_list.push_back(Gtk::TargetEntry( "image/png" ));
1257 _clipboard->set(target_list,
1258 sigc::mem_fun(*this, &ClipboardManagerImpl::_onGet),
1259 sigc::mem_fun(*this, &ClipboardManagerImpl::_onClear));
1261 #ifdef WIN32
1262 // If the "image/x-emf" target handled by the emf extension would be
1263 // presented as a CF_ENHMETAFILE automatically (just like an "image/bmp"
1264 // is presented as a CF_BITMAP) this code would not be needed.. ???
1265 // Or maybe there is some other way to achieve the same?
1267 // Note: Metafile is the only format that is rendered and stored in clipboard
1268 // on Copy, all other formats are rendered only when needed by a Paste command.
1270 // FIXME: This should at least be rewritten to use "delayed rendering".
1271 // If possible make it delayed rendering by using GTK API only.
1273 if (OpenClipboard(NULL)) {
1274 if ( _clipboardSPDoc != NULL ) {
1275 const Glib::ustring target = CLIPBOARD_WIN32_EMF_MIME;
1277 Inkscape::Extension::DB::OutputList outlist;
1278 Inkscape::Extension::db.get_output_list(outlist);
1279 Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
1280 for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out);
1281 if ( out != outlist.end() ) {
1282 // FIXME: Temporary hack until we add support for memory output.
1283 // Save to a temporary file, read it back and then set the clipboard contents
1284 gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export.emf", NULL );
1286 try {
1287 (*out)->save(_clipboardSPDoc, filename);
1288 HENHMETAFILE hemf = GetEnhMetaFileA(filename);
1289 if (hemf) {
1290 SetClipboardData(CF_ENHMETAFILE, hemf);
1291 DeleteEnhMetaFile(hemf);
1292 }
1293 } catch (...) {
1294 }
1295 g_unlink(filename); // delete the temporary file
1296 g_free(filename);
1297 }
1298 }
1299 CloseClipboard();
1300 }
1301 #endif
1302 }
1305 /**
1306 * @brief Set the string representation of a 32-bit RGBA color as the clipboard contents
1307 */
1308 void ClipboardManagerImpl::_setClipboardColor(guint32 color)
1309 {
1310 gchar colorstr[16];
1311 g_snprintf(colorstr, 16, "%08x", color);
1312 _clipboard->set_text(colorstr);
1313 }
1316 /**
1317 * @brief Put a notification on the mesage stack
1318 */
1319 void ClipboardManagerImpl::_userWarn(SPDesktop *desktop, char const *msg)
1320 {
1321 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, msg);
1322 }
1326 /* #######################################
1327 ClipboardManager class
1328 ####################################### */
1330 ClipboardManager *ClipboardManager::_instance = NULL;
1332 ClipboardManager::ClipboardManager() {}
1333 ClipboardManager::~ClipboardManager() {}
1334 ClipboardManager *ClipboardManager::get()
1335 {
1336 if ( _instance == NULL )
1337 _instance = new ClipboardManagerImpl;
1338 return _instance;
1339 }
1341 } // namespace Inkscape
1342 } // namespace IO
1344 /*
1345 Local Variables:
1346 mode:c++
1347 c-file-style:"stroustrup"
1348 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1349 indent-tabs-mode:nil
1350 fill-column:99
1351 End:
1352 */
1353 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :