2
* @brief System-wide clipboard management - implementation
5
* Krzysztof Kosiński <tweenk@o2.pl>
6
* Incorporates some code from selection-chemistry.cpp, see that file for more credits.
8
* Copyright (C) 2008 authors
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.
15
* See the file COPYING for details.
18
#include "ui/clipboard.h"
20
// TODO: reduce header bloat if possible
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
31
#include "io/stringstream.h"
33
#include "desktop-handles.h"
34
#include "desktop-style.h" // for sp_desktop_set_style, used in _pasteStyle
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()
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>
51
#include "gradient-drag.h"
53
#include "sp-item-transform.h" // for sp_item_scale_rel, used in _pasteSize
55
#include "sp-pattern.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"
64
#include "sp-textpath.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"
78
#include "unit-constants.h"
79
#include "helper/png-write.h"
80
#include "svg/svg-color.h"
81
#include "sp-namedview.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"
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"
104
* @brief Default implementation of the clipboard manager
106
class ClipboardManagerImpl : public ClipboardManager {
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();
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 *);
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);
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
167
ClipboardManagerImpl::ClipboardManagerImpl()
168
: _clipboardSPDoc(NULL),
174
_clipboard( Gtk::Clipboard::get() )
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");
181
_preferred_targets.push_back(CLIPBOARD_WIN32_EMF_MIME);
183
_preferred_targets.push_back("application/pdf");
184
_preferred_targets.push_back("image/x-adobe-illustrator");
188
ClipboardManagerImpl::~ClipboardManagerImpl() {}
192
* @brief Copy selection contents to the clipboard
194
void ClipboardManagerImpl::copy()
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
guint32 col = drag->getColor();
206
// set the color as clipboard content (text in RRGGBBAA format)
207
_setClipboardColor(col);
209
// create a style with this color on fill and opacity in master opacity, so it can be
210
// pasted on other stops or objects
212
sp_repr_css_attr_unref(_text_style);
215
_text_style = sp_repr_css_attr_new();
216
// print and set properties
218
g_snprintf(color_str, 16, "#%06x", col >> 8);
219
sp_repr_css_set_property(_text_style, "fill", color_str);
220
float opacity = SP_RGBA32_A_F(col);
221
if (opacity > 1.0) opacity = 1.0; // safeguard
222
Inkscape::CSSOStringStream opcss;
224
sp_repr_css_set_property(_text_style, "opacity", opcss.str().data());
226
_discardInternalClipboard();
231
// Special case for when the color picker ("dropper") is active - copies color under cursor
232
if (tools_isactive(desktop, TOOLS_DROPPER)) {
233
_setClipboardColor(sp_dropper_context_get_color(desktop->event_context));
234
_discardInternalClipboard();
238
// Special case for when the text tool is active - if some text is selected, copy plain text,
239
// not the object that holds it; also copy the style at cursor into
240
if (tools_isactive(desktop, TOOLS_TEXT)) {
241
_discardInternalClipboard();
242
Glib::ustring selected_text = sp_text_get_selected_text(desktop->event_context);
243
if (!selected_text.empty()) {
244
_clipboard->set_text(selected_text);
247
sp_repr_css_attr_unref(_text_style);
250
_text_style = sp_text_get_style_at_cursor(desktop->event_context);
254
if (selection->isEmpty()) { // check whether something is selected
255
_userWarn(desktop, _("Nothing was copied."));
258
_discardInternalClipboard();
260
_createInternalClipboard(); // construct a new clipboard document
261
_copySelection(selection); // copy all items in the selection to the internal clipboard
262
fit_canvas_to_drawing(_clipboardSPDoc);
264
_setClipboardTargets();
269
* @brief Copy a Live Path Effect path parameter to the clipboard
270
* @param pp The path parameter to store in the clipboard
272
void ClipboardManagerImpl::copyPathParameter(Inkscape::LivePathEffect::PathParam *pp)
274
if ( pp == NULL ) return;
275
gchar *svgd = sp_svg_write_path( pp->get_pathvector() );
276
if ( svgd == NULL || *svgd == '\0' ) return;
278
_discardInternalClipboard();
279
_createInternalClipboard();
281
Inkscape::XML::Node *pathnode = _doc->createElement("svg:path");
282
pathnode->setAttribute("d", svgd);
284
_root->appendChild(pathnode);
285
Inkscape::GC::release(pathnode);
287
fit_canvas_to_drawing(_clipboardSPDoc);
288
_setClipboardTargets();
292
* @brief Paste from the system clipboard into the active desktop
293
* @param in_place Whether to put the contents where they were when copied
295
bool ClipboardManagerImpl::paste(bool in_place)
297
// do any checking whether we really are able to paste before requesting the contents
298
SPDesktop *desktop = SP_ACTIVE_DESKTOP;
299
if ( desktop == NULL ) return false;
300
if ( Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false ) return false;
302
Glib::ustring target = _getBestTarget();
304
// Special cases of clipboard content handling go here
305
// Note that target priority is determined in _getBestTarget.
306
// TODO: Handle x-special/gnome-copied-files and text/uri-list to support pasting files
308
// if there is an image on the clipboard, paste it
309
if ( target == CLIPBOARD_GDK_PIXBUF_TARGET ) return _pasteImage();
310
// if there's only text, paste it into a selected text object or create a new one
311
if ( target == CLIPBOARD_TEXT_TARGET ) return _pasteText();
313
// otherwise, use the import extensions
314
SPDocument *tempdoc = _retrieveClipboard(target);
315
if ( tempdoc == NULL ) {
316
_userWarn(desktop, _("Nothing on the clipboard."));
320
_pasteDocument(tempdoc, in_place);
321
sp_document_unref(tempdoc);
327
* @brief Returns the id of the first visible copied object
329
const gchar *ClipboardManagerImpl::getFirstObjectID()
331
SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
332
if ( tempdoc == NULL ) {
337
*root = sp_document_repr_root(tempdoc);
342
Inkscape::XML::Node *ch = sp_repr_children(root);
344
strcmp(ch->name(), "svg:g") &&
345
strcmp(ch->name(), "svg:path") &&
346
strcmp(ch->name(), "svg:use") &&
347
strcmp(ch->name(), "svg:text") &&
348
strcmp(ch->name(), "svg:image") &&
349
strcmp(ch->name(), "svg:rect")
354
return ch->attribute("id");
362
* @brief Implements the Paste Style action
364
bool ClipboardManagerImpl::pasteStyle()
366
SPDesktop *desktop = SP_ACTIVE_DESKTOP;
367
if (desktop == NULL) return false;
369
// check whether something is selected
370
Inkscape::Selection *selection = sp_desktop_selection(desktop);
371
if (selection->isEmpty()) {
372
_userWarn(desktop, _("Select <b>object(s)</b> to paste style to."));
376
SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
377
if ( tempdoc == NULL ) {
378
// no document, but we can try _text_style
380
sp_desktop_set_style(desktop, _text_style);
383
_userWarn(desktop, _("No style on the clipboard."));
389
*root = sp_document_repr_root(tempdoc),
390
*clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
396
SPCSSAttr *style = sp_repr_css_attr(clipnode, "style");
397
sp_desktop_set_style(desktop, style);
401
_userWarn(desktop, _("No style on the clipboard."));
404
sp_document_unref(tempdoc);
410
* @brief Resize the selection or each object in the selection to match the clipboard's size
411
* @param separately Whether to scale each object in the selection separately
412
* @param apply_x Whether to scale the width of objects / selection
413
* @param apply_y Whether to scale the height of objects / selection
415
bool ClipboardManagerImpl::pasteSize(bool separately, bool apply_x, bool apply_y)
417
if(!apply_x && !apply_y) return false; // pointless parameters
419
SPDesktop *desktop = SP_ACTIVE_DESKTOP;
420
if ( desktop == NULL ) return false;
421
Inkscape::Selection *selection = sp_desktop_selection(desktop);
422
if (selection->isEmpty()) {
423
_userWarn(desktop, _("Select <b>object(s)</b> to paste size to."));
427
// FIXME: actually, this should accept arbitrary documents
428
SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
429
if ( tempdoc == NULL ) {
430
_userWarn(desktop, _("No size on the clipboard."));
434
// retrieve size ifomration from the clipboard
435
Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
436
Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
439
Geom::Point min, max;
440
sp_repr_get_point(clipnode, "min", &min);
441
sp_repr_get_point(clipnode, "max", &max);
443
// resize each object in the selection
445
for (GSList *i = const_cast<GSList*>(selection->itemList()) ; i ; i = i->next) {
446
SPItem *item = SP_ITEM(i->data);
447
Geom::OptRect obj_size = sp_item_bbox_desktop(item);
448
if ( !obj_size ) continue;
449
sp_item_scale_rel(item, _getScale(min, max, *obj_size, apply_x, apply_y));
452
// resize the selection as a whole
454
Geom::OptRect sel_size = selection->bounds();
456
sp_selection_scale_relative(selection, sel_size->midpoint(),
457
_getScale(min, max, *sel_size, apply_x, apply_y));
462
sp_document_unref(tempdoc);
468
* @brief Applies a path effect from the clipboard to the selected path
470
bool ClipboardManagerImpl::pastePathEffect()
472
/** @todo FIXME: pastePathEffect crashes when moving the path with the applied effect,
473
segfaulting in fork_private_if_necessary(). */
475
SPDesktop *desktop = SP_ACTIVE_DESKTOP;
476
if ( desktop == NULL )
479
Inkscape::Selection *selection = sp_desktop_selection(desktop);
480
if (selection && selection->isEmpty()) {
481
_userWarn(desktop, _("Select <b>object(s)</b> to paste live path effect to."));
485
SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
487
Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
488
Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
490
gchar const *effect = clipnode->attribute("inkscape:path-effect");
493
// make sure all selected items are converted to paths first (i.e. rectangles)
494
sp_selected_path_to_curves(desktop, false);
495
for (GSList *item = const_cast<GSList *>(selection->itemList()) ; item ; item = item->next) {
496
_applyPathEffect(reinterpret_cast<SPItem*>(item->data), effect);
505
_userWarn(desktop, _("No effect on the clipboard."));
511
* @brief Get LPE path data from the clipboard
512
* @return The retrieved path data (contents of the d attribute), or "" if no path was found
514
Glib::ustring ClipboardManagerImpl::getPathParameter()
516
SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
517
if ( tempdoc == NULL ) {
518
_userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
522
*root = sp_document_repr_root(tempdoc),
523
*path = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
524
if ( path == NULL ) {
525
_userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
526
sp_document_unref(tempdoc);
529
gchar const *svgd = path->attribute("d");
535
* @brief Get object id of a shape or text item from the clipboard
536
* @return The retrieved id string (contents of the id attribute), or "" if no shape or text item was found
538
Glib::ustring ClipboardManagerImpl::getShapeOrTextObjectId()
540
SPDocument *tempdoc = _retrieveClipboard(); // any target will do here
541
if ( tempdoc == NULL ) {
542
_userWarn(SP_ACTIVE_DESKTOP, _("Nothing on the clipboard."));
545
Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
547
Inkscape::XML::Node *repr = sp_repr_lookup_name(root, "svg:path", -1); // unlimited search depth
549
repr = sp_repr_lookup_name(root, "svg:text", -1);
551
if ( repr == NULL ) {
552
_userWarn(SP_ACTIVE_DESKTOP, _("Clipboard does not contain a path."));
553
sp_document_unref(tempdoc);
556
gchar const *svgd = repr->attribute("id");
562
* @brief Iterate over a list of items and copy them to the clipboard.
564
void ClipboardManagerImpl::_copySelection(Inkscape::Selection *selection)
566
GSList const *items = selection->itemList();
567
// copy the defs used by all items
568
for (GSList *i = const_cast<GSList *>(items) ; i != NULL ; i = i->next) {
569
_copyUsedDefs(SP_ITEM (i->data));
572
// copy the representation of the items
573
GSList *sorted_items = g_slist_copy(const_cast<GSList *>(items));
574
sorted_items = g_slist_sort(sorted_items, (GCompareFunc) sp_object_compare_position);
576
for (GSList *i = sorted_items ; i ; i = i->next) {
577
if (!SP_IS_ITEM(i->data)) continue;
578
Inkscape::XML::Node *obj = SP_OBJECT_REPR(i->data);
579
Inkscape::XML::Node *obj_copy = _copyNode(obj, _doc, _root);
581
// copy complete inherited style
582
SPCSSAttr *css = sp_repr_css_attr_inherited(obj, "style");
583
sp_repr_css_set(obj_copy, css, "style");
584
sp_repr_css_attr_unref(css);
586
// write the complete accumulated transform passed to us
587
// (we're dealing with unattached representations, so we write to their attributes
588
// instead of using sp_item_set_transform)
589
gchar *transform_str = sp_svg_transform_write(sp_item_i2doc_affine(SP_ITEM(i->data)));
590
obj_copy->setAttribute("transform", transform_str);
591
g_free(transform_str);
594
// copy style for Paste Style action
596
if(SP_IS_ITEM(sorted_items->data)) {
597
SPCSSAttr *style = take_style_from_item((SPItem *) sorted_items->data);
598
sp_repr_css_set(_clipnode, style, "style");
599
sp_repr_css_attr_unref(style);
602
// copy path effect from the first path
603
if (SP_IS_OBJECT(sorted_items->data)) {
604
gchar const *effect = SP_OBJECT_REPR(sorted_items->data)->attribute("inkscape:path-effect");
606
_clipnode->setAttribute("inkscape:path-effect", effect);
611
Geom::OptRect size = selection->bounds();
613
sp_repr_set_point(_clipnode, "min", size->min());
614
sp_repr_set_point(_clipnode, "max", size->max());
617
g_slist_free(sorted_items);
622
* @brief Recursively copy all the definitions used by a given item to the clipboard defs
624
void ClipboardManagerImpl::_copyUsedDefs(SPItem *item)
626
// copy fill and stroke styles (patterns and gradients)
627
SPStyle *style = SP_OBJECT_STYLE(item);
629
if (style && (style->fill.isPaintserver())) {
630
SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
631
if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
632
_copyGradient(SP_GRADIENT(server));
633
if (SP_IS_PATTERN(server))
634
_copyPattern(SP_PATTERN(server));
636
if (style && (style->stroke.isPaintserver())) {
637
SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
638
if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
639
_copyGradient(SP_GRADIENT(server));
640
if (SP_IS_PATTERN(server))
641
_copyPattern(SP_PATTERN(server));
644
// For shapes, copy all of the shape's markers
645
if (SP_IS_SHAPE(item)) {
646
SPShape *shape = SP_SHAPE (item);
647
for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
648
if (shape->marker[i]) {
649
_copyNode(SP_OBJECT_REPR(SP_OBJECT(shape->marker[i])), _doc, _defs);
653
// For lpe items, copy lpe stack if applicable
654
if (SP_IS_LPE_ITEM(item)) {
655
SPLPEItem *lpeitem = SP_LPE_ITEM (item);
656
if (sp_lpe_item_has_path_effect(lpeitem)) {
657
for (PathEffectList::iterator it = lpeitem->path_effect_list->begin(); it != lpeitem->path_effect_list->end(); ++it)
659
LivePathEffectObject *lpeobj = (*it)->lpeobject;
661
_copyNode(SP_OBJECT_REPR(SP_OBJECT(lpeobj)), _doc, _defs);
665
// For 3D boxes, copy perspectives
666
if (SP_IS_BOX3D(item)) {
667
_copyNode(SP_OBJECT_REPR(SP_OBJECT(box3d_get_perspective(SP_BOX3D(item)))), _doc, _defs);
670
if (SP_IS_TEXT_TEXTPATH(item)) {
671
_copyTextPath(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
673
// Copy clipping objects
674
if (item->clip_ref->getObject()) {
675
_copyNode(SP_OBJECT_REPR(item->clip_ref->getObject()), _doc, _defs);
678
if (item->mask_ref->getObject()) {
679
SPObject *mask = item->mask_ref->getObject();
680
_copyNode(SP_OBJECT_REPR(mask), _doc, _defs);
681
// recurse into the mask for its gradients etc.
682
for (SPObject *o = SP_OBJECT(mask)->children ; o != NULL ; o = o->next) {
684
_copyUsedDefs(SP_ITEM(o));
688
if (style->getFilter()) {
689
SPObject *filter = style->getFilter();
690
if (SP_IS_FILTER(filter)) {
691
_copyNode(SP_OBJECT_REPR(filter), _doc, _defs);
696
for (SPObject *o = SP_OBJECT(item)->children ; o != NULL ; o = o->next) {
698
_copyUsedDefs(SP_ITEM(o));
704
* @brief Copy a single gradient to the clipboard's defs element
706
void ClipboardManagerImpl::_copyGradient(SPGradient *gradient)
709
// climb up the refs, copying each one in the chain
710
_copyNode(SP_OBJECT_REPR(gradient), _doc, _defs);
711
gradient = gradient->ref->getObject();
717
* @brief Copy a single pattern to the clipboard document's defs element
719
void ClipboardManagerImpl::_copyPattern(SPPattern *pattern)
721
// climb up the references, copying each one in the chain
723
_copyNode(SP_OBJECT_REPR(pattern), _doc, _defs);
725
// items in the pattern may also use gradients and other patterns, so recurse
726
for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL ; child = SP_OBJECT_NEXT(child) ) {
727
if (!SP_IS_ITEM (child)) continue;
728
_copyUsedDefs(SP_ITEM(child));
730
pattern = pattern->ref->getObject();
736
* @brief Copy a text path to the clipboard's defs element
738
void ClipboardManagerImpl::_copyTextPath(SPTextPath *tp)
740
SPItem *path = sp_textpath_get_path_item(tp);
742
Inkscape::XML::Node *path_node = SP_OBJECT_REPR(path);
744
// Do not copy the text path to defs if it's already copied
745
if(sp_repr_lookup_child(_root, "id", path_node->attribute("id"))) return;
746
_copyNode(path_node, _doc, _defs);
751
* @brief Copy a single XML node from one document to another
752
* @param node The node to be copied
753
* @param target_doc The document to which the node is to be copied
754
* @param parent The node in the target document which will become the parent of the copied node
755
* @return Pointer to the copied node
757
Inkscape::XML::Node *ClipboardManagerImpl::_copyNode(Inkscape::XML::Node *node, Inkscape::XML::Document *target_doc, Inkscape::XML::Node *parent)
759
Inkscape::XML::Node *dup = node->duplicate(target_doc);
760
parent->appendChild(dup);
761
Inkscape::GC::release(dup);
767
* @brief Paste the contents of a document into the active desktop
768
* @param clipdoc The document to paste
769
* @param in_place Whether to paste the selection where it was when copied
770
* @pre @c clipdoc is not empty and items can be added to the current layer
772
void ClipboardManagerImpl::_pasteDocument(SPDocument *clipdoc, bool in_place)
774
SPDesktop *desktop = SP_ACTIVE_DESKTOP;
775
SPDocument *target_document = sp_desktop_document(desktop);
777
*root = sp_document_repr_root(clipdoc),
778
*target_parent = SP_OBJECT_REPR(desktop->currentLayer());
779
Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
785
GSList *pasted_objects = NULL;
786
for (Inkscape::XML::Node *obj = root->firstChild() ; obj ; obj = obj->next()) {
787
// Don't copy metadata, defs, named views and internal clipboard contents to the document
788
if (!strcmp(obj->name(), "svg:defs")) continue;
789
if (!strcmp(obj->name(), "svg:metadata")) continue;
790
if (!strcmp(obj->name(), "sodipodi:namedview")) continue;
791
if (!strcmp(obj->name(), "inkscape:clipboard")) continue;
792
Inkscape::XML::Node *obj_copy = _copyNode(obj, target_xmldoc, target_parent);
793
pasted_objects = g_slist_prepend(pasted_objects, (gpointer) obj_copy);
796
// Change the selection to the freshly pasted objects
797
Inkscape::Selection *selection = sp_desktop_selection(desktop);
798
selection->setReprList(pasted_objects);
800
// invers apply parent transform
801
Geom::Matrix doc2parent = sp_item_i2doc_affine(SP_ITEM(desktop->currentLayer())).inverse();
802
sp_selection_apply_affine(selection, desktop->dt2doc() * doc2parent * desktop->doc2dt(), true, false);
804
// Update (among other things) all curves in paths, for bounds() to work
805
sp_document_ensure_up_to_date(target_document);
807
// move selection either to original position (in_place) or to mouse pointer
808
Geom::OptRect sel_bbox = selection->bounds();
810
// get offset of selection to original position of copied elements
811
Geom::Point pos_original;
812
Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
814
Geom::Point min, max;
815
sp_repr_get_point(clipnode, "min", &min);
816
sp_repr_get_point(clipnode, "max", &max);
817
pos_original = Geom::Point(min[Geom::X], max[Geom::Y]);
819
Geom::Point offset = pos_original - sel_bbox->corner(3);
822
SnapManager &m = desktop->namedview->snap_manager;
823
m.setup(desktop, false); // Don't display the snapindicator
825
// get offset from mouse pointer to bbox center, snap to grid if enabled
826
Geom::Point mouse_offset = desktop->point() - sel_bbox->midpoint();
827
offset = m.multipleOfGridPitch(mouse_offset - offset) + offset;
830
sp_selection_move_relative(selection, offset);
833
g_slist_free(pasted_objects);
838
* @brief Paste SVG defs from the document retrieved from the clipboard into the active document
839
* @param clipdoc The document to paste
840
* @pre @c clipdoc != NULL and pasting into the active document is possible
842
void ClipboardManagerImpl::_pasteDefs(SPDocument *clipdoc)
844
// boilerplate vars copied from _pasteDocument
845
SPDesktop *desktop = SP_ACTIVE_DESKTOP;
846
SPDocument *target_document = sp_desktop_document(desktop);
848
*root = sp_document_repr_root(clipdoc),
849
*defs = sp_repr_lookup_name(root, "svg:defs", 1),
850
*target_defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(target_document));
851
Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
853
prevent_id_clashes(clipdoc, target_document);
855
for (Inkscape::XML::Node *def = defs->firstChild() ; def ; def = def->next()) {
856
_copyNode(def, target_xmldoc, target_defs);
862
* @brief Retrieve a bitmap image from the clipboard and paste it into the active document
864
bool ClipboardManagerImpl::_pasteImage()
866
SPDocument *doc = SP_ACTIVE_DOCUMENT;
867
if ( doc == NULL ) return false;
869
// retrieve image data
870
Glib::RefPtr<Gdk::Pixbuf> img = _clipboard->wait_for_image();
871
if (!img) return false;
873
// Very stupid hack: Write into a file, then import the file into the document.
874
// To avoid using tmpfile and POSIX file handles, make the filename based on current time.
875
// This wasn't my idea, I just copied this from selection-chemistry.cpp
876
// and just can't think of something saner at the moment. Pasting more than
877
// one image per second will overwrite the image.
878
// However, I don't think anyone is able to copy a _different_ image into inkscape
881
char image_filename[128];
884
strftime(image_filename, 128, "inkscape_pasted_image_%Y%m%d_%H%M%S.png", localtime( &rawtime ));
885
/// @todo Check whether the encoding is correct here
886
Inkscape::Preferences *prefs = Inkscape::Preferences::get();
887
std::string save_folder = Glib::filename_from_utf8(prefs->getString("/dialogs/save_as/path"));
889
gchar *image_path = g_build_filename(save_folder.data(), image_filename, NULL);
890
img->save(image_path, "png");
891
file_import(doc, image_path, NULL);
898
* @brief Paste text into the selected text object or create a new one to hold it
900
bool ClipboardManagerImpl::_pasteText()
902
SPDesktop *desktop = SP_ACTIVE_DESKTOP;
903
if ( desktop == NULL ) return false;
905
// if the text editing tool is active, paste the text into the active text object
906
if (tools_isactive(desktop, TOOLS_TEXT))
907
return sp_text_paste_inline(desktop->event_context);
909
// try to parse the text as a color and, if successful, apply it as the current style
910
SPCSSAttr *css = _parseColor(_clipboard->wait_for_text());
912
sp_desktop_set_style(desktop, css);
921
* @brief Attempt to parse the passed string as a hexadecimal RGB or RGBA color
922
* @param text The Glib::ustring to parse
923
* @return New CSS style representation if the parsing was successful, NULL otherwise
925
SPCSSAttr *ClipboardManagerImpl::_parseColor(const Glib::ustring &text)
927
// TODO reuse existing code instead of replicating here.
928
Glib::ustring::size_type len = text.bytes();
929
char *str = const_cast<char *>(text.data());
930
bool attempt_alpha = false;
931
if ( !str || ( *str == '\0' ) ) return NULL; // this is OK due to boolean short-circuit
933
// those conditionals guard against parsing e.g. the string "fab" as "fab000"
934
// (incomplete color) and "45fab71" as "45fab710" (incomplete alpha)
936
if ( len < 7 ) return NULL;
937
if ( len >= 9 ) attempt_alpha = true;
939
if ( len < 6 ) return NULL;
940
if ( len >= 8 ) attempt_alpha = true;
943
unsigned int color = 0, alpha = 0xff;
945
// skip a leading #, if present
946
if ( *str == '#' ) ++str;
948
// try to parse first 6 digits
949
int res = sscanf(str, "%6x", &color);
950
if ( res && ( res != EOF ) ) {
951
if (attempt_alpha) {// try to parse alpha if there's enough characters
952
sscanf(str + 6, "%2x", &alpha);
953
if ( !res || res == EOF ) alpha = 0xff;
956
SPCSSAttr *color_css = sp_repr_css_attr_new();
958
// print and set properties
960
g_snprintf(color_str, 16, "#%06x", color);
961
sp_repr_css_set_property(color_css, "fill", color_str);
963
float opacity = static_cast<float>(alpha)/static_cast<float>(0xff);
964
if (opacity > 1.0) opacity = 1.0; // safeguard
965
Inkscape::CSSOStringStream opcss;
967
sp_repr_css_set_property(color_css, "fill-opacity", opcss.str().data());
975
* @brief Applies a pasted path effect to a given item
977
void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effect)
979
if ( item == NULL ) return;
980
if ( SP_IS_RECT(item) ) return;
982
if (SP_IS_LPE_ITEM(item))
984
SPLPEItem *lpeitem = SP_LPE_ITEM(item);
985
SPObject *obj = sp_uri_reference_resolve(_clipboardSPDoc, effect);
987
// if the effect is not used by anyone, we might as well take it
988
LivePathEffectObject *lpeobj = LIVEPATHEFFECT(obj)->fork_private_if_necessary(1);
989
sp_lpe_item_add_path_effect(lpeitem, lpeobj);
995
* @brief Retrieve the clipboard contents as a document
996
* @return Clipboard contents converted to SPDocument, or NULL if no suitable content was present
998
SPDocument *ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_target)
1000
Glib::ustring best_target;
1001
if ( required_target == "" )
1002
best_target = _getBestTarget();
1004
best_target = required_target;
1006
if ( best_target == "" ) {
1010
// FIXME: Temporary hack until we add memory input.
1011
// Save the clipboard contents to some file, then read it
1012
gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-import", NULL );
1014
bool file_saved = false;
1015
Glib::ustring target = best_target;
1018
if (best_target == CLIPBOARD_WIN32_EMF_TARGET)
1019
{ // Try to save clipboard data as en emf file (using win32 api)
1020
if (OpenClipboard(NULL)) {
1021
HGLOBAL hglb = GetClipboardData(CF_ENHMETAFILE);
1023
HENHMETAFILE hemf = CopyEnhMetaFile((HENHMETAFILE) hglb, filename);
1026
target = CLIPBOARD_WIN32_EMF_MIME;
1027
DeleteEnhMetaFile(hemf);
1036
if ( !_clipboard->wait_is_target_available(best_target) ) {
1040
// doing this synchronously makes better sense
1041
// TODO: use another method because this one is badly broken imo.
1042
// from documentation: "Returns: A SelectionData object, which will be invalid if retrieving the given target failed."
1043
// I don't know how to check whether an object is 'valid' or not, unusable if that's not possible...
1044
Gtk::SelectionData sel = _clipboard->wait_for_contents(best_target);
1045
target = sel.get_target(); // this can crash if the result was invalid of last function. No way to check for this :(
1047
// FIXME: Temporary hack until we add memory input.
1048
// Save the clipboard contents to some file, then read it
1049
g_file_set_contents(filename, (const gchar *) sel.get_data(), sel.get_length(), NULL);
1052
// there is no specific plain SVG input extension, so if we can paste the Inkscape SVG format,
1053
// we use the image/svg+xml mimetype to look up the input extension
1054
if(target == "image/x-inkscape-svg")
1055
target = "image/svg+xml";
1057
Inkscape::Extension::DB::InputList inlist;
1058
Inkscape::Extension::db.get_input_list(inlist);
1059
Inkscape::Extension::DB::InputList::const_iterator in = inlist.begin();
1060
for (; in != inlist.end() && target != (*in)->get_mimetype() ; ++in){};
1061
if ( in == inlist.end() )
1062
return NULL; // this shouldn't happen unless _getBestTarget returns something bogus
1064
SPDocument *tempdoc = NULL;
1066
tempdoc = (*in)->open(filename);
1077
* @brief Callback called when some other application requests data from Inkscape
1079
* Finds a suitable output extension to save the internal clipboard document,
1080
* then saves it to memory and sets the clipboard contents.
1082
void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint /*info*/)
1084
g_assert( _clipboardSPDoc != NULL );
1086
Glib::ustring target = sel.get_target();
1087
if(target == "") return; // this shouldn't happen
1089
if (target == CLIPBOARD_TEXT_TARGET) {
1090
target = "image/x-inkscape-svg";
1093
Inkscape::Extension::DB::OutputList outlist;
1094
Inkscape::Extension::db.get_output_list(outlist);
1095
Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
1096
for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out){};
1097
if ( out == outlist.end() && target != "image/png") return; // this also shouldn't happen
1099
// FIXME: Temporary hack until we add support for memory output.
1100
// Save to a temporary file, read it back and then set the clipboard contents
1101
gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export", NULL );
1102
gsize len; gchar *data;
1105
if (out == outlist.end() && target == "image/png")
1107
gdouble dpi = PX_PER_IN;
1108
guint32 bgcolor = 0x00000000;
1110
Geom::Point origin (SP_ROOT(_clipboardSPDoc->root)->x.computed, SP_ROOT(_clipboardSPDoc->root)->y.computed);
1111
Geom::Rect area = Geom::Rect(origin, origin + sp_document_dimensions(_clipboardSPDoc));
1113
unsigned long int width = (unsigned long int) (area.width() * dpi / PX_PER_IN + 0.5);
1114
unsigned long int height = (unsigned long int) (area.height() * dpi / PX_PER_IN + 0.5);
1116
// read from namedview
1117
Inkscape::XML::Node *nv = sp_repr_lookup_name (_clipboardSPDoc->rroot, "sodipodi:namedview");
1118
if (nv && nv->attribute("pagecolor"))
1119
bgcolor = sp_svg_read_color(nv->attribute("pagecolor"), 0xffffff00);
1120
if (nv && nv->attribute("inkscape:pageopacity"))
1121
bgcolor |= SP_COLOR_F_TO_U(sp_repr_get_double_attribute (nv, "inkscape:pageopacity", 1.0));
1123
sp_export_png_file(_clipboardSPDoc, filename, area, width, height, dpi, dpi, bgcolor, NULL, NULL, true, NULL);
1127
if (!(*out)->loaded()) {
1128
// Need to load the extension.
1129
(*out)->set_state(Inkscape::Extension::Extension::STATE_LOADED);
1131
(*out)->save(_clipboardSPDoc, filename);
1133
g_file_get_contents(filename, &data, &len, NULL);
1135
sel.set(8, (guint8 const *) data, len);
1139
g_unlink(filename); // delete the temporary file
1145
* @brief Callback when someone else takes the clipboard
1147
* When the clipboard owner changes, this callback clears the internal clipboard document
1148
* to reduce memory usage.
1150
void ClipboardManagerImpl::_onClear()
1152
// why is this called before _onGet???
1153
//_discardInternalClipboard();
1158
* @brief Creates an internal clipboard document from scratch
1160
void ClipboardManagerImpl::_createInternalClipboard()
1162
if ( _clipboardSPDoc == NULL ) {
1163
_clipboardSPDoc = sp_document_new(NULL, false, true);
1164
//g_assert( _clipboardSPDoc != NULL );
1165
_defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(_clipboardSPDoc));
1166
_doc = sp_document_repr_doc(_clipboardSPDoc);
1167
_root = sp_document_repr_root(_clipboardSPDoc);
1169
_clipnode = _doc->createElement("inkscape:clipboard");
1170
_root->appendChild(_clipnode);
1171
Inkscape::GC::release(_clipnode);
1173
// once we create a SVG document, style will be stored in it, so flush _text_style
1175
sp_repr_css_attr_unref(_text_style);
1183
* @brief Deletes the internal clipboard document
1185
void ClipboardManagerImpl::_discardInternalClipboard()
1187
if ( _clipboardSPDoc != NULL ) {
1188
sp_document_unref(_clipboardSPDoc);
1189
_clipboardSPDoc = NULL;
1199
* @brief Get the scale to resize an item, based on the command and desktop state
1201
Geom::Scale ClipboardManagerImpl::_getScale(Geom::Point const &min, Geom::Point const &max, Geom::Rect const &obj_rect, bool apply_x, bool apply_y)
1203
SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1204
double scale_x = 1.0;
1205
double scale_y = 1.0;
1208
scale_x = (max[Geom::X] - min[Geom::X]) / obj_rect[Geom::X].extent();
1211
scale_y = (max[Geom::Y] - min[Geom::Y]) / obj_rect[Geom::Y].extent();
1213
// If the "lock aspect ratio" button is pressed and we paste only a single coordinate,
1214
// resize the second one by the same ratio too
1215
if (desktop->isToolboxButtonActive("lock")) {
1216
if (apply_x && !apply_y) scale_y = scale_x;
1217
if (apply_y && !apply_x) scale_x = scale_y;
1220
return Geom::Scale(scale_x, scale_y);
1225
* @brief Find the most suitable clipboard target
1227
Glib::ustring ClipboardManagerImpl::_getBestTarget()
1229
std::list<Glib::ustring> targets = _clipboard->wait_for_targets();
1231
// clipboard target debugging snippet
1233
g_debug("Begin clipboard targets");
1234
for ( std::list<Glib::ustring>::iterator x = targets.begin() ; x != targets.end(); ++x )
1235
g_debug("Clipboard target: %s", (*x).data());
1236
g_debug("End clipboard targets\n");
1239
for(std::list<Glib::ustring>::iterator i = _preferred_targets.begin() ;
1240
i != _preferred_targets.end() ; ++i)
1242
if ( std::find(targets.begin(), targets.end(), *i) != targets.end() )
1246
if (OpenClipboard(NULL))
1247
{ // If both bitmap and metafile are present, pick the one that was exported first.
1248
UINT format = EnumClipboardFormats(0);
1250
if (format == CF_ENHMETAFILE || format == CF_DIB || format == CF_BITMAP)
1252
format = EnumClipboardFormats(format);
1256
if (format == CF_ENHMETAFILE)
1257
return CLIPBOARD_WIN32_EMF_TARGET;
1258
if (format == CF_DIB || format == CF_BITMAP)
1259
return CLIPBOARD_GDK_PIXBUF_TARGET;
1262
if (IsClipboardFormatAvailable(CF_ENHMETAFILE))
1263
return CLIPBOARD_WIN32_EMF_TARGET;
1265
if (_clipboard->wait_is_image_available())
1266
return CLIPBOARD_GDK_PIXBUF_TARGET;
1267
if (_clipboard->wait_is_text_available())
1268
return CLIPBOARD_TEXT_TARGET;
1275
* @brief Set the clipboard targets to reflect the mimetypes Inkscape can output
1277
void ClipboardManagerImpl::_setClipboardTargets()
1279
Inkscape::Extension::DB::OutputList outlist;
1280
Inkscape::Extension::db.get_output_list(outlist);
1281
std::list<Gtk::TargetEntry> target_list;
1282
bool plaintextSet = false;
1283
for (Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin() ; out != outlist.end() ; ++out) {
1284
if ( !(*out)->deactivated() ) {
1285
Glib::ustring mime = (*out)->get_mimetype();
1286
if (mime != CLIPBOARD_TEXT_TARGET) {
1287
if ( !plaintextSet && (mime.find("svg") == Glib::ustring::npos) ) {
1288
target_list.push_back(Gtk::TargetEntry(CLIPBOARD_TEXT_TARGET));
1289
plaintextSet = true;
1291
target_list.push_back(Gtk::TargetEntry(mime));
1296
// Add PNG export explicitly since there is no extension for this...
1297
// On Windows, GTK will also present this as a CF_DIB/CF_BITMAP
1298
target_list.push_back(Gtk::TargetEntry( "image/png" ));
1300
_clipboard->set(target_list,
1301
sigc::mem_fun(*this, &ClipboardManagerImpl::_onGet),
1302
sigc::mem_fun(*this, &ClipboardManagerImpl::_onClear));
1305
// If the "image/x-emf" target handled by the emf extension would be
1306
// presented as a CF_ENHMETAFILE automatically (just like an "image/bmp"
1307
// is presented as a CF_BITMAP) this code would not be needed.. ???
1308
// Or maybe there is some other way to achieve the same?
1310
// Note: Metafile is the only format that is rendered and stored in clipboard
1311
// on Copy, all other formats are rendered only when needed by a Paste command.
1313
// FIXME: This should at least be rewritten to use "delayed rendering".
1314
// If possible make it delayed rendering by using GTK API only.
1316
if (OpenClipboard(NULL)) {
1317
if ( _clipboardSPDoc != NULL ) {
1318
const Glib::ustring target = CLIPBOARD_WIN32_EMF_MIME;
1320
Inkscape::Extension::DB::OutputList outlist;
1321
Inkscape::Extension::db.get_output_list(outlist);
1322
Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
1323
for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out);
1324
if ( out != outlist.end() ) {
1325
// FIXME: Temporary hack until we add support for memory output.
1326
// Save to a temporary file, read it back and then set the clipboard contents
1327
gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export.emf", NULL );
1330
(*out)->save(_clipboardSPDoc, filename);
1331
HENHMETAFILE hemf = GetEnhMetaFileA(filename);
1333
SetClipboardData(CF_ENHMETAFILE, hemf);
1334
DeleteEnhMetaFile(hemf);
1338
g_unlink(filename); // delete the temporary file
1349
* @brief Set the string representation of a 32-bit RGBA color as the clipboard contents
1351
void ClipboardManagerImpl::_setClipboardColor(guint32 color)
1354
g_snprintf(colorstr, 16, "%08x", color);
1355
_clipboard->set_text(colorstr);
1360
* @brief Put a notification on the mesage stack
1362
void ClipboardManagerImpl::_userWarn(SPDesktop *desktop, char const *msg)
1364
desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, msg);
1369
/* #######################################
1370
ClipboardManager class
1371
####################################### */
1373
ClipboardManager *ClipboardManager::_instance = NULL;
1375
ClipboardManager::ClipboardManager() {}
1376
ClipboardManager::~ClipboardManager() {}
1377
ClipboardManager *ClipboardManager::get()
1379
if ( _instance == NULL )
1380
_instance = new ClipboardManagerImpl;
1384
} // namespace Inkscape
1390
c-file-style:"stroustrup"
1391
c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1392
indent-tabs-mode:nil
1396
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :