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 // we need a way to copy plain text AND remember its style;
159 // the standard _clipnode is only available in an SVG tree, hence this special storage
160 SPCSSAttr *_text_style; ///< Style copied along with plain text fragment
162 Glib::RefPtr<Gtk::Clipboard> _clipboard; ///< Handle to the system wide clipboard - for convenience
163 std::list<Glib::ustring> _preferred_targets; ///< List of supported clipboard targets
164 };
167 ClipboardManagerImpl::ClipboardManagerImpl()
168 : _clipboardSPDoc(NULL),
169 _defs(NULL),
170 _root(NULL),
171 _clipnode(NULL),
172 _doc(NULL),
173 _text_style(NULL),
174 _clipboard( Gtk::Clipboard::get() )
175 {
176 // push supported clipboard targets, in order of preference
177 _preferred_targets.push_back("image/x-inkscape-svg");
178 _preferred_targets.push_back("image/svg+xml");
179 _preferred_targets.push_back("image/svg+xml-compressed");
180 #ifdef WIN32
181 _preferred_targets.push_back(CLIPBOARD_WIN32_EMF_MIME);
182 #endif
183 _preferred_targets.push_back("application/pdf");
184 _preferred_targets.push_back("image/x-adobe-illustrator");
185 }
188 ClipboardManagerImpl::~ClipboardManagerImpl() {}
191 /**
192 * @brief Copy selection contents to the clipboard
193 */
194 void ClipboardManagerImpl::copy()
195 {
196 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
197 if ( desktop == NULL ) return;
198 Inkscape::Selection *selection = sp_desktop_selection(desktop);
200 // Special case for when the gradient dragger is active - copies gradient color
201 if (desktop->event_context->get_drag()) {
202 GrDrag *drag = desktop->event_context->get_drag();
203 if (drag->hasSelection()) {
204 _setClipboardColor(drag->getColor());
205 _discardInternalClipboard();
206 return;
207 }
208 }
210 // Special case for when the color picker ("dropper") is active - copies color under cursor
211 if (tools_isactive(desktop, TOOLS_DROPPER)) {
212 _setClipboardColor(sp_dropper_context_get_color(desktop->event_context));
213 _discardInternalClipboard();
214 return;
215 }
217 // Special case for when the text tool is active - if some text is selected, copy plain text,
218 // not the object that holds it; also copy the style at cursor into
219 if (tools_isactive(desktop, TOOLS_TEXT)) {
220 _discardInternalClipboard();
221 Glib::ustring selected_text = sp_text_get_selected_text(desktop->event_context);
222 if (!selected_text.empty()) {
223 _clipboard->set_text(selected_text);
224 }
225 if (_text_style) {
226 sp_repr_css_attr_unref(_text_style);
227 _text_style = NULL;
228 }
229 _text_style = sp_text_get_style_at_cursor(desktop->event_context);
230 return;
231 }
233 if (selection->isEmpty()) { // check whether something is selected
234 _userWarn(desktop, _("Nothing was copied."));
235 return;
236 }
237 _discardInternalClipboard();
239 _createInternalClipboard(); // construct a new clipboard document
240 _copySelection(selection); // copy all items in the selection to the internal clipboard
241 fit_canvas_to_drawing(_clipboardSPDoc);
243 _setClipboardTargets();
244 }
247 /**
248 * @brief Copy a Live Path Effect path parameter to the clipboard
249 * @param pp The path parameter to store in the clipboard
250 */
251 void ClipboardManagerImpl::copyPathParameter(Inkscape::LivePathEffect::PathParam *pp)
252 {
253 if ( pp == NULL ) return;
254 gchar *svgd = sp_svg_write_path( pp->get_pathvector() );
255 if ( svgd == NULL || *svgd == '\0' ) return;
257 _discardInternalClipboard();
258 _createInternalClipboard();
260 Inkscape::XML::Node *pathnode = _doc->createElement("svg:path");
261 pathnode->setAttribute("d", svgd);
262 g_free(svgd);
263 _root->appendChild(pathnode);
264 Inkscape::GC::release(pathnode);
266 fit_canvas_to_drawing(_clipboardSPDoc);
267 _setClipboardTargets();
268 }
270 /**
271 * @brief Paste from the system clipboard into the active desktop
272 * @param in_place Whether to put the contents where they were when copied
273 */
274 bool ClipboardManagerImpl::paste(bool in_place)
275 {
276 // do any checking whether we really are able to paste before requesting the contents
277 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
278 if ( desktop == NULL ) return false;
279 if ( Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false ) return false;
281 Glib::ustring target = _getBestTarget();
283 // Special cases of clipboard content handling go here
284 // Note that target priority is determined in _getBestTarget.
285 // TODO: Handle x-special/gnome-copied-files and text/uri-list to support pasting files
287 // if there is an image on the clipboard, paste it
288 if ( target == CLIPBOARD_GDK_PIXBUF_TARGET ) return _pasteImage();
289 // if there's only text, paste it into a selected text object or create a new one
290 if ( target == CLIPBOARD_TEXT_TARGET ) return _pasteText();
292 // otherwise, use the import extensions
293 SPDocument *tempdoc = _retrieveClipboard(target);
294 if ( tempdoc == NULL ) {
295 _userWarn(desktop, _("Nothing on the clipboard."));
296 return false;
297 }
299 _pasteDocument(tempdoc, in_place);
300 sp_document_unref(tempdoc);
302 return true;
303 }
305 /**
306 * @brief Returns the id of the first visible copied object
307 */
308 const gchar *ClipboardManagerImpl::getFirstObjectID()
309 {
310 SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
311 if ( tempdoc == NULL ) {
312 return NULL;
313 }
315 Inkscape::XML::Node
316 *root = sp_document_repr_root(tempdoc);
318 if (!root)
319 return NULL;
321 Inkscape::XML::Node *ch = sp_repr_children(root);
322 while (ch != NULL &&
323 strcmp(ch->name(), "svg:g") &&
324 strcmp(ch->name(), "svg:path") &&
325 strcmp(ch->name(), "svg:use") &&
326 strcmp(ch->name(), "svg:text") &&
327 strcmp(ch->name(), "svg:image") &&
328 strcmp(ch->name(), "svg:rect")
329 )
330 ch = ch->next();
332 if (ch) {
333 return ch->attribute("id");
334 }
336 return NULL;
337 }
340 /**
341 * @brief Implements the Paste Style action
342 */
343 bool ClipboardManagerImpl::pasteStyle()
344 {
345 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
346 if (desktop == NULL) return false;
348 // check whether something is selected
349 Inkscape::Selection *selection = sp_desktop_selection(desktop);
350 if (selection->isEmpty()) {
351 _userWarn(desktop, _("Select <b>object(s)</b> to paste style to."));
352 return false;
353 }
355 SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
356 if ( tempdoc == NULL ) {
357 // no document, but we can try _text_style
358 if (_text_style) {
359 sp_desktop_set_style(desktop, _text_style);
360 return true;
361 } else {
362 _userWarn(desktop, _("No style on the clipboard."));
363 return false;
364 }
365 }
367 Inkscape::XML::Node
368 *root = sp_document_repr_root(tempdoc),
369 *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
371 bool pasted = false;
373 if (clipnode) {
374 _pasteDefs(tempdoc);
375 SPCSSAttr *style = sp_repr_css_attr(clipnode, "style");
376 sp_desktop_set_style(desktop, style);
377 pasted = true;
378 }
379 else {
380 _userWarn(desktop, _("No style on the clipboard."));
381 }
383 sp_document_unref(tempdoc);
384 return pasted;
385 }
388 /**
389 * @brief Resize the selection or each object in the selection to match the clipboard's size
390 * @param separately Whether to scale each object in the selection separately
391 * @param apply_x Whether to scale the width of objects / selection
392 * @param apply_y Whether to scale the height of objects / selection
393 */
394 bool ClipboardManagerImpl::pasteSize(bool separately, bool apply_x, bool apply_y)
395 {
396 if(!apply_x && !apply_y) return false; // pointless parameters
398 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
399 if ( desktop == NULL ) return false;
400 Inkscape::Selection *selection = sp_desktop_selection(desktop);
401 if (selection->isEmpty()) {
402 _userWarn(desktop, _("Select <b>object(s)</b> to paste size to."));
403 return false;
404 }
406 // FIXME: actually, this should accept arbitrary documents
407 SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
408 if ( tempdoc == NULL ) {
409 _userWarn(desktop, _("No size on the clipboard."));
410 return false;
411 }
413 // retrieve size ifomration from the clipboard
414 Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
415 Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
416 bool pasted = false;
417 if (clipnode) {
418 Geom::Point min, max;
419 sp_repr_get_point(clipnode, "min", &min);
420 sp_repr_get_point(clipnode, "max", &max);
422 // resize each object in the selection
423 if (separately) {
424 for (GSList *i = const_cast<GSList*>(selection->itemList()) ; i ; i = i->next) {
425 SPItem *item = SP_ITEM(i->data);
426 Geom::OptRect obj_size = sp_item_bbox_desktop(item);
427 if ( !obj_size ) continue;
428 sp_item_scale_rel(item, _getScale(min, max, *obj_size, apply_x, apply_y));
429 }
430 }
431 // resize the selection as a whole
432 else {
433 Geom::OptRect sel_size = selection->bounds();
434 if ( sel_size ) {
435 sp_selection_scale_relative(selection, sel_size->midpoint(),
436 _getScale(min, max, *sel_size, apply_x, apply_y));
437 }
438 }
439 pasted = true;
440 }
441 sp_document_unref(tempdoc);
442 return pasted;
443 }
446 /**
447 * @brief Applies a path effect from the clipboard to the selected path
448 */
449 bool ClipboardManagerImpl::pastePathEffect()
450 {
451 /** @todo FIXME: pastePathEffect crashes when moving the path with the applied effect,
452 segfaulting in fork_private_if_necessary(). */
454 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
455 if ( desktop == NULL )
456 return false;
458 Inkscape::Selection *selection = sp_desktop_selection(desktop);
459 if (selection && selection->isEmpty()) {
460 _userWarn(desktop, _("Select <b>object(s)</b> to paste live path effect to."));
461 return false;
462 }
464 SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
465 if ( tempdoc ) {
466 Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
467 Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
468 if ( clipnode ) {
469 gchar const *effect = clipnode->attribute("inkscape:path-effect");
470 if ( effect ) {
471 _pasteDefs(tempdoc);
472 // make sure all selected items are converted to paths first (i.e. rectangles)
473 sp_selected_path_to_curves(desktop, false);
474 for (GSList *item = const_cast<GSList *>(selection->itemList()) ; item ; item = item->next) {
475 _applyPathEffect(reinterpret_cast<SPItem*>(item->data), effect);
476 }
478 return true;
479 }
480 }
481 }
483 // no_effect:
484 _userWarn(desktop, _("No effect on the clipboard."));
485 return false;
486 }
489 /**
490 * @brief Get LPE path data from the clipboard
491 * @return The retrieved path data (contents of the d attribute), or "" if no path was found
492 */
493 Glib::ustring ClipboardManagerImpl::getPathParameter()
494 {
495 SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
496 if ( tempdoc == NULL ) {
497 _userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
498 return "";
499 }
500 Inkscape::XML::Node
501 *root = sp_document_repr_root(tempdoc),
502 *path = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
503 if ( path == NULL ) {
504 _userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
505 sp_document_unref(tempdoc);
506 return "";
507 }
508 gchar const *svgd = path->attribute("d");
509 return svgd;
510 }
513 /**
514 * @brief Get object id of a shape or text item from the clipboard
515 * @return The retrieved id string (contents of the id attribute), or "" if no shape or text item was found
516 */
517 Glib::ustring ClipboardManagerImpl::getShapeOrTextObjectId()
518 {
519 SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
520 if ( tempdoc == NULL ) {
521 _userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
522 return "";
523 }
524 Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
526 Inkscape::XML::Node *repr = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
527 if ( repr == NULL )
528 repr = sp_repr_lookup_name(root, "svg:text", -1);
530 if ( repr == NULL ) {
531 _userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
532 sp_document_unref(tempdoc);
533 return "";
534 }
535 gchar const *svgd = repr->attribute("id");
536 return svgd;
537 }
540 /**
541 * @brief Iterate over a list of items and copy them to the clipboard.
542 */
543 void ClipboardManagerImpl::_copySelection(Inkscape::Selection *selection)
544 {
545 GSList const *items = selection->itemList();
546 // copy the defs used by all items
547 for (GSList *i = const_cast<GSList *>(items) ; i != NULL ; i = i->next) {
548 _copyUsedDefs(SP_ITEM (i->data));
549 }
551 // copy the representation of the items
552 GSList *sorted_items = g_slist_copy(const_cast<GSList *>(items));
553 sorted_items = g_slist_sort(sorted_items, (GCompareFunc) sp_object_compare_position);
555 for (GSList *i = sorted_items ; i ; i = i->next) {
556 if (!SP_IS_ITEM(i->data)) continue;
557 Inkscape::XML::Node *obj = SP_OBJECT_REPR(i->data);
558 Inkscape::XML::Node *obj_copy = _copyNode(obj, _doc, _root);
560 // copy complete inherited style
561 SPCSSAttr *css = sp_repr_css_attr_inherited(obj, "style");
562 sp_repr_css_set(obj_copy, css, "style");
563 sp_repr_css_attr_unref(css);
565 // write the complete accumulated transform passed to us
566 // (we're dealing with unattached representations, so we write to their attributes
567 // instead of using sp_item_set_transform)
568 gchar *transform_str = sp_svg_transform_write(sp_item_i2doc_affine(SP_ITEM(i->data)));
569 obj_copy->setAttribute("transform", transform_str);
570 g_free(transform_str);
571 }
573 // copy style for Paste Style action
574 if (sorted_items) {
575 if(SP_IS_ITEM(sorted_items->data)) {
576 SPCSSAttr *style = take_style_from_item((SPItem *) sorted_items->data);
577 sp_repr_css_set(_clipnode, style, "style");
578 sp_repr_css_attr_unref(style);
579 }
581 // copy path effect from the first path
582 if (SP_IS_OBJECT(sorted_items->data)) {
583 gchar const *effect = SP_OBJECT_REPR(sorted_items->data)->attribute("inkscape:path-effect");
584 if (effect) {
585 _clipnode->setAttribute("inkscape:path-effect", effect);
586 }
587 }
588 }
590 Geom::OptRect size = selection->bounds();
591 if (size) {
592 sp_repr_set_point(_clipnode, "min", size->min());
593 sp_repr_set_point(_clipnode, "max", size->max());
594 }
596 g_slist_free(sorted_items);
597 }
600 /**
601 * @brief Recursively copy all the definitions used by a given item to the clipboard defs
602 */
603 void ClipboardManagerImpl::_copyUsedDefs(SPItem *item)
604 {
605 // copy fill and stroke styles (patterns and gradients)
606 SPStyle *style = SP_OBJECT_STYLE(item);
608 if (style && (style->fill.isPaintserver())) {
609 SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
610 if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
611 _copyGradient(SP_GRADIENT(server));
612 if (SP_IS_PATTERN(server))
613 _copyPattern(SP_PATTERN(server));
614 }
615 if (style && (style->stroke.isPaintserver())) {
616 SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
617 if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
618 _copyGradient(SP_GRADIENT(server));
619 if (SP_IS_PATTERN(server))
620 _copyPattern(SP_PATTERN(server));
621 }
623 // For shapes, copy all of the shape's markers
624 if (SP_IS_SHAPE(item)) {
625 SPShape *shape = SP_SHAPE (item);
626 for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
627 if (shape->marker[i]) {
628 _copyNode(SP_OBJECT_REPR(SP_OBJECT(shape->marker[i])), _doc, _defs);
629 }
630 }
631 }
632 // For lpe items, copy lpe stack if applicable
633 if (SP_IS_LPE_ITEM(item)) {
634 SPLPEItem *lpeitem = SP_LPE_ITEM (item);
635 if (sp_lpe_item_has_path_effect(lpeitem)) {
636 for (PathEffectList::iterator it = lpeitem->path_effect_list->begin(); it != lpeitem->path_effect_list->end(); ++it)
637 {
638 LivePathEffectObject *lpeobj = (*it)->lpeobject;
639 if (lpeobj)
640 _copyNode(SP_OBJECT_REPR(SP_OBJECT(lpeobj)), _doc, _defs);
641 }
642 }
643 }
644 // For 3D boxes, copy perspectives
645 if (SP_IS_BOX3D(item)) {
646 _copyNode(SP_OBJECT_REPR(SP_OBJECT(box3d_get_perspective(SP_BOX3D(item)))), _doc, _defs);
647 }
648 // Copy text paths
649 if (SP_IS_TEXT_TEXTPATH(item)) {
650 _copyTextPath(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
651 }
652 // Copy clipping objects
653 if (item->clip_ref->getObject()) {
654 _copyNode(SP_OBJECT_REPR(item->clip_ref->getObject()), _doc, _defs);
655 }
656 // Copy mask objects
657 if (item->mask_ref->getObject()) {
658 SPObject *mask = item->mask_ref->getObject();
659 _copyNode(SP_OBJECT_REPR(mask), _doc, _defs);
660 // recurse into the mask for its gradients etc.
661 for (SPObject *o = SP_OBJECT(mask)->children ; o != NULL ; o = o->next) {
662 if (SP_IS_ITEM(o))
663 _copyUsedDefs(SP_ITEM(o));
664 }
665 }
666 // Copy filters
667 if (style->getFilter()) {
668 SPObject *filter = style->getFilter();
669 if (SP_IS_FILTER(filter)) {
670 _copyNode(SP_OBJECT_REPR(filter), _doc, _defs);
671 }
672 }
674 // recurse
675 for (SPObject *o = SP_OBJECT(item)->children ; o != NULL ; o = o->next) {
676 if (SP_IS_ITEM(o))
677 _copyUsedDefs(SP_ITEM(o));
678 }
679 }
682 /**
683 * @brief Copy a single gradient to the clipboard's defs element
684 */
685 void ClipboardManagerImpl::_copyGradient(SPGradient *gradient)
686 {
687 while (gradient) {
688 // climb up the refs, copying each one in the chain
689 _copyNode(SP_OBJECT_REPR(gradient), _doc, _defs);
690 gradient = gradient->ref->getObject();
691 }
692 }
695 /**
696 * @brief Copy a single pattern to the clipboard document's defs element
697 */
698 void ClipboardManagerImpl::_copyPattern(SPPattern *pattern)
699 {
700 // climb up the references, copying each one in the chain
701 while (pattern) {
702 _copyNode(SP_OBJECT_REPR(pattern), _doc, _defs);
704 // items in the pattern may also use gradients and other patterns, so recurse
705 for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL ; child = SP_OBJECT_NEXT(child) ) {
706 if (!SP_IS_ITEM (child)) continue;
707 _copyUsedDefs(SP_ITEM(child));
708 }
709 pattern = pattern->ref->getObject();
710 }
711 }
714 /**
715 * @brief Copy a text path to the clipboard's defs element
716 */
717 void ClipboardManagerImpl::_copyTextPath(SPTextPath *tp)
718 {
719 SPItem *path = sp_textpath_get_path_item(tp);
720 if(!path) return;
721 Inkscape::XML::Node *path_node = SP_OBJECT_REPR(path);
723 // Do not copy the text path to defs if it's already copied
724 if(sp_repr_lookup_child(_root, "id", path_node->attribute("id"))) return;
725 _copyNode(path_node, _doc, _defs);
726 }
729 /**
730 * @brief Copy a single XML node from one document to another
731 * @param node The node to be copied
732 * @param target_doc The document to which the node is to be copied
733 * @param parent The node in the target document which will become the parent of the copied node
734 * @return Pointer to the copied node
735 */
736 Inkscape::XML::Node *ClipboardManagerImpl::_copyNode(Inkscape::XML::Node *node, Inkscape::XML::Document *target_doc, Inkscape::XML::Node *parent)
737 {
738 Inkscape::XML::Node *dup = node->duplicate(target_doc);
739 parent->appendChild(dup);
740 Inkscape::GC::release(dup);
741 return dup;
742 }
745 /**
746 * @brief Paste the contents of a document into the active desktop
747 * @param clipdoc The document to paste
748 * @param in_place Whether to paste the selection where it was when copied
749 * @pre @c clipdoc is not empty and items can be added to the current layer
750 */
751 void ClipboardManagerImpl::_pasteDocument(SPDocument *clipdoc, bool in_place)
752 {
753 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
754 SPDocument *target_document = sp_desktop_document(desktop);
755 Inkscape::XML::Node
756 *root = sp_document_repr_root(clipdoc),
757 *target_parent = SP_OBJECT_REPR(desktop->currentLayer());
758 Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
760 // copy definitions
761 _pasteDefs(clipdoc);
763 // copy objects
764 GSList *pasted_objects = NULL;
765 for (Inkscape::XML::Node *obj = root->firstChild() ; obj ; obj = obj->next()) {
766 // Don't copy metadata, defs, named views and internal clipboard contents to the document
767 if (!strcmp(obj->name(), "svg:defs")) continue;
768 if (!strcmp(obj->name(), "svg:metadata")) continue;
769 if (!strcmp(obj->name(), "sodipodi:namedview")) continue;
770 if (!strcmp(obj->name(), "inkscape:clipboard")) continue;
771 Inkscape::XML::Node *obj_copy = _copyNode(obj, target_xmldoc, target_parent);
772 pasted_objects = g_slist_prepend(pasted_objects, (gpointer) obj_copy);
773 }
775 // Change the selection to the freshly pasted objects
776 Inkscape::Selection *selection = sp_desktop_selection(desktop);
777 selection->setReprList(pasted_objects);
779 // invers apply parent transform
780 Geom::Matrix doc2parent = sp_item_i2doc_affine(SP_ITEM(desktop->currentLayer())).inverse();
781 sp_selection_apply_affine(selection, doc2parent);
783 // Update (among other things) all curves in paths, for bounds() to work
784 sp_document_ensure_up_to_date(target_document);
786 // move selection either to original position (in_place) or to mouse pointer
787 Geom::OptRect sel_bbox = selection->bounds();
788 if (sel_bbox) {
789 // get offset of selection to original position of copied elements
790 Geom::Point pos_original;
791 Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
792 if (clipnode) {
793 Geom::Point min, max;
794 sp_repr_get_point(clipnode, "min", &min);
795 sp_repr_get_point(clipnode, "max", &max);
796 pos_original = Geom::Point(min[Geom::X], max[Geom::Y]);
797 }
798 Geom::Point offset = pos_original - sel_bbox->corner(3);
800 if (!in_place) {
801 SnapManager &m = desktop->namedview->snap_manager;
802 m.setup(desktop, false); // Don't display the snapindicator
804 // get offset from mouse pointer to bbox center, snap to grid if enabled
805 Geom::Point mouse_offset = desktop->point() - sel_bbox->midpoint();
806 offset = m.multipleOfGridPitch(mouse_offset - offset) + offset;
807 }
809 sp_selection_move_relative(selection, offset);
810 }
812 g_slist_free(pasted_objects);
813 }
816 /**
817 * @brief Paste SVG defs from the document retrieved from the clipboard into the active document
818 * @param clipdoc The document to paste
819 * @pre @c clipdoc != NULL and pasting into the active document is possible
820 */
821 void ClipboardManagerImpl::_pasteDefs(SPDocument *clipdoc)
822 {
823 // boilerplate vars copied from _pasteDocument
824 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
825 SPDocument *target_document = sp_desktop_document(desktop);
826 Inkscape::XML::Node
827 *root = sp_document_repr_root(clipdoc),
828 *defs = sp_repr_lookup_name(root, "svg:defs", 1),
829 *target_defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(target_document));
830 Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
832 prevent_id_clashes(clipdoc, target_document);
834 for (Inkscape::XML::Node *def = defs->firstChild() ; def ; def = def->next()) {
835 _copyNode(def, target_xmldoc, target_defs);
836 }
837 }
840 /**
841 * @brief Retrieve a bitmap image from the clipboard and paste it into the active document
842 */
843 bool ClipboardManagerImpl::_pasteImage()
844 {
845 SPDocument *doc = SP_ACTIVE_DOCUMENT;
846 if ( doc == NULL ) return false;
848 // retrieve image data
849 Glib::RefPtr<Gdk::Pixbuf> img = _clipboard->wait_for_image();
850 if (!img) return false;
852 // Very stupid hack: Write into a file, then import the file into the document.
853 // To avoid using tmpfile and POSIX file handles, make the filename based on current time.
854 // This wasn't my idea, I just copied this from selection-chemistry.cpp
855 // and just can't think of something saner at the moment. Pasting more than
856 // one image per second will overwrite the image.
857 // However, I don't think anyone is able to copy a _different_ image into inkscape
858 // in 1 second.
859 time_t rawtime;
860 char image_filename[128];
862 time(&rawtime);
863 strftime(image_filename, 128, "inkscape_pasted_image_%Y%m%d_%H%M%S.png", localtime( &rawtime ));
864 /// @todo Check whether the encoding is correct here
865 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
866 std::string save_folder = Glib::filename_from_utf8(prefs->getString("/dialogs/save_as/path"));
868 gchar *image_path = g_build_filename(save_folder.data(), image_filename, NULL);
869 img->save(image_path, "png");
870 file_import(doc, image_path, NULL);
871 g_free(image_path);
873 return true;
874 }
876 /**
877 * @brief Paste text into the selected text object or create a new one to hold it
878 */
879 bool ClipboardManagerImpl::_pasteText()
880 {
881 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
882 if ( desktop == NULL ) return false;
884 // if the text editing tool is active, paste the text into the active text object
885 if (tools_isactive(desktop, TOOLS_TEXT))
886 return sp_text_paste_inline(desktop->event_context);
888 // try to parse the text as a color and, if successful, apply it as the current style
889 SPCSSAttr *css = _parseColor(_clipboard->wait_for_text());
890 if (css) {
891 sp_desktop_set_style(desktop, css);
892 return true;
893 }
895 return false;
896 }
899 /**
900 * @brief Attempt to parse the passed string as a hexadecimal RGB or RGBA color
901 * @param text The Glib::ustring to parse
902 * @return New CSS style representation if the parsing was successful, NULL otherwise
903 */
904 SPCSSAttr *ClipboardManagerImpl::_parseColor(const Glib::ustring &text)
905 {
906 // TODO reuse existing code instead of replicating here.
907 Glib::ustring::size_type len = text.bytes();
908 char *str = const_cast<char *>(text.data());
909 bool attempt_alpha = false;
910 if ( !str || ( *str == '\0' ) ) return NULL; // this is OK due to boolean short-circuit
912 // those conditionals guard against parsing e.g. the string "fab" as "fab000"
913 // (incomplete color) and "45fab71" as "45fab710" (incomplete alpha)
914 if ( *str == '#' ) {
915 if ( len < 7 ) return NULL;
916 if ( len >= 9 ) attempt_alpha = true;
917 } else {
918 if ( len < 6 ) return NULL;
919 if ( len >= 8 ) attempt_alpha = true;
920 }
922 unsigned int color = 0, alpha = 0xff;
924 // skip a leading #, if present
925 if ( *str == '#' ) ++str;
927 // try to parse first 6 digits
928 int res = sscanf(str, "%6x", &color);
929 if ( res && ( res != EOF ) ) {
930 if (attempt_alpha) {// try to parse alpha if there's enough characters
931 sscanf(str + 6, "%2x", &alpha);
932 if ( !res || res == EOF ) alpha = 0xff;
933 }
935 SPCSSAttr *color_css = sp_repr_css_attr_new();
937 // print and set properties
938 gchar color_str[16];
939 g_snprintf(color_str, 16, "#%06x", color);
940 sp_repr_css_set_property(color_css, "fill", color_str);
942 float opacity = static_cast<float>(alpha)/static_cast<float>(0xff);
943 if (opacity > 1.0) opacity = 1.0; // safeguard
944 Inkscape::CSSOStringStream opcss;
945 opcss << opacity;
946 sp_repr_css_set_property(color_css, "fill-opacity", opcss.str().data());
947 return color_css;
948 }
949 return NULL;
950 }
953 /**
954 * @brief Applies a pasted path effect to a given item
955 */
956 void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effect)
957 {
958 if ( item == NULL ) return;
959 if ( SP_IS_RECT(item) ) return;
961 if (SP_IS_LPE_ITEM(item))
962 {
963 SPLPEItem *lpeitem = SP_LPE_ITEM(item);
964 SPObject *obj = sp_uri_reference_resolve(_clipboardSPDoc, effect);
965 if (!obj) return;
966 // if the effect is not used by anyone, we might as well take it
967 LivePathEffectObject *lpeobj = LIVEPATHEFFECT(obj)->fork_private_if_necessary(1);
968 sp_lpe_item_add_path_effect(lpeitem, lpeobj);
969 }
970 }
973 /**
974 * @brief Retrieve the clipboard contents as a document
975 * @return Clipboard contents converted to SPDocument, or NULL if no suitable content was present
976 */
977 SPDocument *ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_target)
978 {
979 Glib::ustring best_target;
980 if ( required_target == "" )
981 best_target = _getBestTarget();
982 else
983 best_target = required_target;
985 if ( best_target == "" ) {
986 return NULL;
987 }
989 // FIXME: Temporary hack until we add memory input.
990 // Save the clipboard contents to some file, then read it
991 gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-import", NULL );
993 bool file_saved = false;
994 Glib::ustring target = best_target;
996 #ifdef WIN32
997 if (best_target == CLIPBOARD_WIN32_EMF_TARGET)
998 { // Try to save clipboard data as en emf file (using win32 api)
999 if (OpenClipboard(NULL)) {
1000 HGLOBAL hglb = GetClipboardData(CF_ENHMETAFILE);
1001 if (hglb) {
1002 HENHMETAFILE hemf = CopyEnhMetaFile((HENHMETAFILE) hglb, filename);
1003 if (hemf) {
1004 file_saved = true;
1005 target = CLIPBOARD_WIN32_EMF_MIME;
1006 DeleteEnhMetaFile(hemf);
1007 }
1008 }
1009 CloseClipboard();
1010 }
1011 }
1012 #endif
1014 if (!file_saved) {
1015 if ( !_clipboard->wait_is_target_available(best_target) ) {
1016 return NULL;
1017 }
1019 // doing this synchronously makes better sense
1020 // TODO: use another method because this one is badly broken imo.
1021 // from documentation: "Returns: A SelectionData object, which will be invalid if retrieving the given target failed."
1022 // I don't know how to check whether an object is 'valid' or not, unusable if that's not possible...
1023 Gtk::SelectionData sel = _clipboard->wait_for_contents(best_target);
1024 target = sel.get_target(); // this can crash if the result was invalid of last function. No way to check for this :(
1026 // FIXME: Temporary hack until we add memory input.
1027 // Save the clipboard contents to some file, then read it
1028 g_file_set_contents(filename, (const gchar *) sel.get_data(), sel.get_length(), NULL);
1029 }
1031 // there is no specific plain SVG input extension, so if we can paste the Inkscape SVG format,
1032 // we use the image/svg+xml mimetype to look up the input extension
1033 if(target == "image/x-inkscape-svg")
1034 target = "image/svg+xml";
1036 Inkscape::Extension::DB::InputList inlist;
1037 Inkscape::Extension::db.get_input_list(inlist);
1038 Inkscape::Extension::DB::InputList::const_iterator in = inlist.begin();
1039 for (; in != inlist.end() && target != (*in)->get_mimetype() ; ++in){};
1040 if ( in == inlist.end() )
1041 return NULL; // this shouldn't happen unless _getBestTarget returns something bogus
1043 SPDocument *tempdoc = NULL;
1044 try {
1045 tempdoc = (*in)->open(filename);
1046 } catch (...) {
1047 }
1048 g_unlink(filename);
1049 g_free(filename);
1051 return tempdoc;
1052 }
1055 /**
1056 * @brief Callback called when some other application requests data from Inkscape
1057 *
1058 * Finds a suitable output extension to save the internal clipboard document,
1059 * then saves it to memory and sets the clipboard contents.
1060 */
1061 void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint /*info*/)
1062 {
1063 g_assert( _clipboardSPDoc != NULL );
1065 Glib::ustring target = sel.get_target();
1066 if(target == "") return; // this shouldn't happen
1068 if (target == CLIPBOARD_TEXT_TARGET) {
1069 target = "image/x-inkscape-svg";
1070 }
1072 Inkscape::Extension::DB::OutputList outlist;
1073 Inkscape::Extension::db.get_output_list(outlist);
1074 Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
1075 for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out){};
1076 if ( out == outlist.end() && target != "image/png") return; // this also shouldn't happen
1078 // FIXME: Temporary hack until we add support for memory output.
1079 // Save to a temporary file, read it back and then set the clipboard contents
1080 gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export", NULL );
1081 gsize len; gchar *data;
1083 try {
1084 if (out == outlist.end() && target == "image/png")
1085 {
1086 gdouble dpi = PX_PER_IN;
1087 guint32 bgcolor = 0x00000000;
1089 Geom::Point origin (SP_ROOT(_clipboardSPDoc->root)->x.computed, SP_ROOT(_clipboardSPDoc->root)->y.computed);
1090 Geom::Rect area = Geom::Rect(origin, origin + sp_document_dimensions(_clipboardSPDoc));
1092 unsigned long int width = (unsigned long int) (area.width() * dpi / PX_PER_IN + 0.5);
1093 unsigned long int height = (unsigned long int) (area.height() * dpi / PX_PER_IN + 0.5);
1095 // read from namedview
1096 Inkscape::XML::Node *nv = sp_repr_lookup_name (_clipboardSPDoc->rroot, "sodipodi:namedview");
1097 if (nv && nv->attribute("pagecolor"))
1098 bgcolor = sp_svg_read_color(nv->attribute("pagecolor"), 0xffffff00);
1099 if (nv && nv->attribute("inkscape:pageopacity"))
1100 bgcolor |= SP_COLOR_F_TO_U(sp_repr_get_double_attribute (nv, "inkscape:pageopacity", 1.0));
1102 sp_export_png_file(_clipboardSPDoc, filename, area, width, height, dpi, dpi, bgcolor, NULL, NULL, true, NULL);
1103 }
1104 else
1105 {
1106 if (!(*out)->loaded()) {
1107 // Need to load the extension.
1108 (*out)->set_state(Inkscape::Extension::Extension::STATE_LOADED);
1109 }
1110 (*out)->save(_clipboardSPDoc, filename);
1111 }
1112 g_file_get_contents(filename, &data, &len, NULL);
1114 sel.set(8, (guint8 const *) data, len);
1115 } catch (...) {
1116 }
1118 g_unlink(filename); // delete the temporary file
1119 g_free(filename);
1120 }
1123 /**
1124 * @brief Callback when someone else takes the clipboard
1125 *
1126 * When the clipboard owner changes, this callback clears the internal clipboard document
1127 * to reduce memory usage.
1128 */
1129 void ClipboardManagerImpl::_onClear()
1130 {
1131 // why is this called before _onGet???
1132 //_discardInternalClipboard();
1133 }
1136 /**
1137 * @brief Creates an internal clipboard document from scratch
1138 */
1139 void ClipboardManagerImpl::_createInternalClipboard()
1140 {
1141 if ( _clipboardSPDoc == NULL ) {
1142 _clipboardSPDoc = sp_document_new(NULL, false, true);
1143 //g_assert( _clipboardSPDoc != NULL );
1144 _defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(_clipboardSPDoc));
1145 _doc = sp_document_repr_doc(_clipboardSPDoc);
1146 _root = sp_document_repr_root(_clipboardSPDoc);
1148 _clipnode = _doc->createElement("inkscape:clipboard");
1149 _root->appendChild(_clipnode);
1150 Inkscape::GC::release(_clipnode);
1152 // once we create a SVG document, style will be stored in it, so flush _text_style
1153 if (_text_style) {
1154 sp_repr_css_attr_unref(_text_style);
1155 _text_style = NULL;
1156 }
1157 }
1158 }
1161 /**
1162 * @brief Deletes the internal clipboard document
1163 */
1164 void ClipboardManagerImpl::_discardInternalClipboard()
1165 {
1166 if ( _clipboardSPDoc != NULL ) {
1167 sp_document_unref(_clipboardSPDoc);
1168 _clipboardSPDoc = NULL;
1169 _defs = NULL;
1170 _doc = NULL;
1171 _root = NULL;
1172 _clipnode = NULL;
1173 }
1174 }
1177 /**
1178 * @brief Get the scale to resize an item, based on the command and desktop state
1179 */
1180 Geom::Scale ClipboardManagerImpl::_getScale(Geom::Point const &min, Geom::Point const &max, Geom::Rect const &obj_rect, bool apply_x, bool apply_y)
1181 {
1182 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1183 double scale_x = 1.0;
1184 double scale_y = 1.0;
1186 if (apply_x) {
1187 scale_x = (max[Geom::X] - min[Geom::X]) / obj_rect[Geom::X].extent();
1188 }
1189 if (apply_y) {
1190 scale_y = (max[Geom::Y] - min[Geom::Y]) / obj_rect[Geom::Y].extent();
1191 }
1192 // If the "lock aspect ratio" button is pressed and we paste only a single coordinate,
1193 // resize the second one by the same ratio too
1194 if (desktop->isToolboxButtonActive("lock")) {
1195 if (apply_x && !apply_y) scale_y = scale_x;
1196 if (apply_y && !apply_x) scale_x = scale_y;
1197 }
1199 return Geom::Scale(scale_x, scale_y);
1200 }
1203 /**
1204 * @brief Find the most suitable clipboard target
1205 */
1206 Glib::ustring ClipboardManagerImpl::_getBestTarget()
1207 {
1208 std::list<Glib::ustring> targets = _clipboard->wait_for_targets();
1210 // clipboard target debugging snippet
1211 /*
1212 g_debug("Begin clipboard targets");
1213 for ( std::list<Glib::ustring>::iterator x = targets.begin() ; x != targets.end(); ++x )
1214 g_debug("Clipboard target: %s", (*x).data());
1215 g_debug("End clipboard targets\n");
1216 //*/
1218 for(std::list<Glib::ustring>::iterator i = _preferred_targets.begin() ;
1219 i != _preferred_targets.end() ; ++i)
1220 {
1221 if ( std::find(targets.begin(), targets.end(), *i) != targets.end() )
1222 return *i;
1223 }
1224 #ifdef WIN32
1225 if (OpenClipboard(NULL))
1226 { // If both bitmap and metafile are present, pick the one that was exported first.
1227 UINT format = EnumClipboardFormats(0);
1228 while (format) {
1229 if (format == CF_ENHMETAFILE || format == CF_DIB || format == CF_BITMAP)
1230 break;
1231 format = EnumClipboardFormats(format);
1232 }
1233 CloseClipboard();
1235 if (format == CF_ENHMETAFILE)
1236 return CLIPBOARD_WIN32_EMF_TARGET;
1237 if (format == CF_DIB || format == CF_BITMAP)
1238 return CLIPBOARD_GDK_PIXBUF_TARGET;
1239 }
1241 if (IsClipboardFormatAvailable(CF_ENHMETAFILE))
1242 return CLIPBOARD_WIN32_EMF_TARGET;
1243 #endif
1244 if (_clipboard->wait_is_image_available())
1245 return CLIPBOARD_GDK_PIXBUF_TARGET;
1246 if (_clipboard->wait_is_text_available())
1247 return CLIPBOARD_TEXT_TARGET;
1249 return "";
1250 }
1253 /**
1254 * @brief Set the clipboard targets to reflect the mimetypes Inkscape can output
1255 */
1256 void ClipboardManagerImpl::_setClipboardTargets()
1257 {
1258 Inkscape::Extension::DB::OutputList outlist;
1259 Inkscape::Extension::db.get_output_list(outlist);
1260 std::list<Gtk::TargetEntry> target_list;
1261 bool plaintextSet = false;
1262 for (Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin() ; out != outlist.end() ; ++out) {
1263 if ( !(*out)->deactivated() ) {
1264 Glib::ustring mime = (*out)->get_mimetype();
1265 if (mime != CLIPBOARD_TEXT_TARGET) {
1266 if ( !plaintextSet && (mime.find("svg") == Glib::ustring::npos) ) {
1267 target_list.push_back(Gtk::TargetEntry(CLIPBOARD_TEXT_TARGET));
1268 plaintextSet = true;
1269 }
1270 target_list.push_back(Gtk::TargetEntry(mime));
1271 }
1272 }
1273 }
1275 // Add PNG export explicitly since there is no extension for this...
1276 // On Windows, GTK will also present this as a CF_DIB/CF_BITMAP
1277 target_list.push_back(Gtk::TargetEntry( "image/png" ));
1279 _clipboard->set(target_list,
1280 sigc::mem_fun(*this, &ClipboardManagerImpl::_onGet),
1281 sigc::mem_fun(*this, &ClipboardManagerImpl::_onClear));
1283 #ifdef WIN32
1284 // If the "image/x-emf" target handled by the emf extension would be
1285 // presented as a CF_ENHMETAFILE automatically (just like an "image/bmp"
1286 // is presented as a CF_BITMAP) this code would not be needed.. ???
1287 // Or maybe there is some other way to achieve the same?
1289 // Note: Metafile is the only format that is rendered and stored in clipboard
1290 // on Copy, all other formats are rendered only when needed by a Paste command.
1292 // FIXME: This should at least be rewritten to use "delayed rendering".
1293 // If possible make it delayed rendering by using GTK API only.
1295 if (OpenClipboard(NULL)) {
1296 if ( _clipboardSPDoc != NULL ) {
1297 const Glib::ustring target = CLIPBOARD_WIN32_EMF_MIME;
1299 Inkscape::Extension::DB::OutputList outlist;
1300 Inkscape::Extension::db.get_output_list(outlist);
1301 Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
1302 for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out);
1303 if ( out != outlist.end() ) {
1304 // FIXME: Temporary hack until we add support for memory output.
1305 // Save to a temporary file, read it back and then set the clipboard contents
1306 gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export.emf", NULL );
1308 try {
1309 (*out)->save(_clipboardSPDoc, filename);
1310 HENHMETAFILE hemf = GetEnhMetaFileA(filename);
1311 if (hemf) {
1312 SetClipboardData(CF_ENHMETAFILE, hemf);
1313 DeleteEnhMetaFile(hemf);
1314 }
1315 } catch (...) {
1316 }
1317 g_unlink(filename); // delete the temporary file
1318 g_free(filename);
1319 }
1320 }
1321 CloseClipboard();
1322 }
1323 #endif
1324 }
1327 /**
1328 * @brief Set the string representation of a 32-bit RGBA color as the clipboard contents
1329 */
1330 void ClipboardManagerImpl::_setClipboardColor(guint32 color)
1331 {
1332 gchar colorstr[16];
1333 g_snprintf(colorstr, 16, "%08x", color);
1334 _clipboard->set_text(colorstr);
1335 }
1338 /**
1339 * @brief Put a notification on the mesage stack
1340 */
1341 void ClipboardManagerImpl::_userWarn(SPDesktop *desktop, char const *msg)
1342 {
1343 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, msg);
1344 }
1348 /* #######################################
1349 ClipboardManager class
1350 ####################################### */
1352 ClipboardManager *ClipboardManager::_instance = NULL;
1354 ClipboardManager::ClipboardManager() {}
1355 ClipboardManager::~ClipboardManager() {}
1356 ClipboardManager *ClipboardManager::get()
1357 {
1358 if ( _instance == NULL )
1359 _instance = new ClipboardManagerImpl;
1360 return _instance;
1361 }
1363 } // namespace Inkscape
1364 } // namespace IO
1366 /*
1367 Local Variables:
1368 mode:c++
1369 c-file-style:"stroustrup"
1370 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1371 indent-tabs-mode:nil
1372 fill-column:99
1373 End:
1374 */
1375 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :