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