Code

Changed term away from "embed" since that has specific meaning.
[inkscape.git] / src / ui / clipboard.cpp
index cc1b58a55aabe2663d985365ccf98cbc6462b181..bd3edadda28ab8487585e0c042015b0794d44a87 100644 (file)
  * See the file COPYING for details.
  */
 
-#ifdef HAVE_CONFIG_H
-# include "config.h"
-#endif
-#include "path-prefix.h"
-
 #include "ui/clipboard.h"
 
 // TODO: reduce header bloat if possible
@@ -49,6 +44,9 @@
 #include "extension/output.h"
 #include "selection-chemistry.h"
 #include "libnr/nr-rect.h"
+#include "libnr/nr-convert2geom.h"
+#include <2geom/rect.h>
+#include <2geom/transforms.h>
 #include "box3d.h"
 #include "gradient-drag.h"
 #include "sp-item.h"
 #include "sp-textpath.h"
 #include "sp-rect.h"
 #include "live_effects/lpeobject.h"
+#include "live_effects/lpeobject-reference.h"
 #include "live_effects/parameter/path.h"
 #include "svg/svg.h" // for sp_svg_transform_write, used in _copySelection
 #include "svg/css-ostringstream.h" // used in _parseColor
 #include "file.h" // for file_import, used in _pasteImage
-#include "prefs-utils.h" // for prefs_get_string_attribute, used in _pasteImage
+#include "preferences.h" // for used in _pasteImage
 #include "text-context.h"
 #include "text-editing.h"
 #include "tools-switch.h"
-#include "live_effects/n-art-bpath-2geom.h"
 #include "path-chemistry.h"
+#include "id-clash.h"
+#include "unit-constants.h"
+#include "helper/png-write.h"
+#include "svg/svg-color.h"
+#include "sp-namedview.h"
+#include "snap.h"
 
 /// @brief Made up mimetype to represent Gdk::Pixbuf clipboard contents
 #define CLIPBOARD_GDK_PIXBUF_TARGET "image/x-gdk-pixbuf"
 
 #define CLIPBOARD_TEXT_TARGET "text/plain"
 
+#ifdef WIN32
+#include <windows.h>
+// Clipboard Formats: http://msdn.microsoft.com/en-us/library/ms649013(VS.85).aspx
+// On Windows, most graphical applications can handle CF_DIB/CF_BITMAP and/or CF_ENHMETAFILE
+// GTK automatically presents an "image/bmp" target as CF_DIB/CF_BITMAP
+// Presenting "image/x-emf" as CF_ENHMETAFILE must be done by Inkscape ?
+#define CLIPBOARD_WIN32_EMF_TARGET "CF_ENHMETAFILE"
+#define CLIPBOARD_WIN32_EMF_MIME   "image/x-emf"
+#endif
+
 namespace Inkscape {
 namespace UI {
 
@@ -99,10 +113,11 @@ public:
     virtual bool pastePathEffect();
     virtual Glib::ustring getPathParameter();
     virtual Glib::ustring getShapeOrTextObjectId();
-    
+    virtual const gchar *getFirstObjectID();
+
     ClipboardManagerImpl();
     ~ClipboardManagerImpl();
-    
+
 private:
     void _copySelection(Inkscape::Selection *);
     void _copyUsedDefs(SPItem *);
@@ -110,7 +125,7 @@ private:
     void _copyPattern(SPPattern *);
     void _copyTextPath(SPTextPath *);
     Inkscape::XML::Node *_copyNode(Inkscape::XML::Node *, Inkscape::XML::Document *, Inkscape::XML::Node *);
-    
+
     void _pasteDocument(SPDocument *, bool in_place);
     void _pasteDefs(SPDocument *);
     bool _pasteImage();
@@ -118,16 +133,16 @@ private:
     SPCSSAttr *_parseColor(const Glib::ustring &);
     void _applyPathEffect(SPItem *, gchar const *);
     SPDocument *_retrieveClipboard(Glib::ustring = "");
-    
+
     // clipboard callbacks
     void _onGet(Gtk::SelectionData &, guint);
     void _onClear();
-    
+
     // various helpers
     void _createInternalClipboard();
     void _discardInternalClipboard();
     Inkscape::XML::Node *_createClipNode();
-    NR::scale _getScale(Geom::Point &, Geom::Point &, NR::Rect &, bool, bool);
+    Geom::Scale _getScale(Geom::Point const &, Geom::Point const &, Geom::Rect const &, bool, bool);
     Glib::ustring _getBestTarget();
     void _setClipboardTargets();
     void _setClipboardColor(guint32);
@@ -139,7 +154,7 @@ private:
     Inkscape::XML::Node *_root; ///< Reference to the clipboard's root node
     Inkscape::XML::Node *_clipnode; ///< The node that holds extra information
     Inkscape::XML::Document *_doc; ///< Reference to the clipboard's Inkscape::XML::Document
-    
+
     Glib::RefPtr<Gtk::Clipboard> _clipboard; ///< Handle to the system wide clipboard - for convenience
     std::list<Glib::ustring> _preferred_targets; ///< List of supported clipboard targets
 };
@@ -158,7 +173,7 @@ ClipboardManagerImpl::ClipboardManagerImpl()
     _preferred_targets.push_back("image/svg+xml");
     _preferred_targets.push_back("image/svg+xml-compressed");
 #ifdef WIN32
-    _preferred_targets.push_back("image/x-emf");
+    _preferred_targets.push_back(CLIPBOARD_WIN32_EMF_MIME);
 #endif
     _preferred_targets.push_back("application/pdf");
     _preferred_targets.push_back("image/x-adobe-illustrator");
@@ -176,7 +191,7 @@ void ClipboardManagerImpl::copy()
     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
     if ( desktop == NULL ) return;
     Inkscape::Selection *selection = sp_desktop_selection(desktop);
-    
+
     // Special case for when the gradient dragger is active - copies gradient color
     if (desktop->event_context->get_drag()) {
         GrDrag *drag = desktop->event_context->get_drag();
@@ -186,14 +201,14 @@ void ClipboardManagerImpl::copy()
             return;
         }
     }
-    
+
     // Special case for when the color picker ("dropper") is active - copies color under cursor
     if (tools_isactive(desktop, TOOLS_DROPPER)) {
         _setClipboardColor(sp_dropper_context_get_color(desktop->event_context));
         _discardInternalClipboard();
         return;
     }
-    
+
     // Special case for when the text tool is active - if some text is selected, copy plain text,
     // not the object that holds it
     if (tools_isactive(desktop, TOOLS_TEXT)) {
@@ -204,17 +219,17 @@ void ClipboardManagerImpl::copy()
             return;
         }
     }
-    
+
     if (selection->isEmpty()) {  // check whether something is selected
         _userWarn(desktop, _("Nothing was copied."));
         return;
     }
     _discardInternalClipboard();
-    
+
     _createInternalClipboard();   // construct a new clipboard document
     _copySelection(selection);   // copy all items in the selection to the internal clipboard
     fit_canvas_to_drawing(_clipboardSPDoc);
-    
+
     _setClipboardTargets();
 }
 
@@ -226,18 +241,18 @@ void ClipboardManagerImpl::copy()
 void ClipboardManagerImpl::copyPathParameter(Inkscape::LivePathEffect::PathParam *pp)
 {
     if ( pp == NULL ) return;
-    gchar *svgd = SVGD_from_2GeomPath( pp->get_pathvector() );
+    gchar *svgd = sp_svg_write_path( pp->get_pathvector() );
     if ( svgd == NULL || *svgd == '\0' ) return;
-    
+
     _discardInternalClipboard();
     _createInternalClipboard();
-    
+
     Inkscape::XML::Node *pathnode = _doc->createElement("svg:path");
     pathnode->setAttribute("d", svgd);
     g_free(svgd);
     _root->appendChild(pathnode);
     Inkscape::GC::release(pathnode);
-    
+
     fit_canvas_to_drawing(_clipboardSPDoc);
     _setClipboardTargets();
 }
@@ -252,31 +267,65 @@ bool ClipboardManagerImpl::paste(bool in_place)
     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
     if ( desktop == NULL ) return false;
     if ( Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false ) return false;
-    
+
     Glib::ustring target = _getBestTarget();
-    
-    // Special cases of clipboard content handling go here 00ff00
+
+    // Special cases of clipboard content handling go here
     // Note that target priority is determined in _getBestTarget.
     // TODO: Handle x-special/gnome-copied-files and text/uri-list to support pasting files
-    
+
     // if there is an image on the clipboard, paste it
     if ( target == CLIPBOARD_GDK_PIXBUF_TARGET ) return _pasteImage();
     // if there's only text, paste it into a selected text object or create a new one
     if ( target == CLIPBOARD_TEXT_TARGET ) return _pasteText();
-    
+
     // otherwise, use the import extensions
     SPDocument *tempdoc = _retrieveClipboard(target);
     if ( tempdoc == NULL ) {
         _userWarn(desktop, _("Nothing on the clipboard."));
         return false;
     }
-    
+
     _pasteDocument(tempdoc, in_place);
     sp_document_unref(tempdoc);
-    
+
     return true;
 }
 
+/**
+ * @brief Returns the id of the first visible copied object
+ */
+const gchar *ClipboardManagerImpl::getFirstObjectID()
+{
+    SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
+    if ( tempdoc == NULL ) {
+        return NULL;
+    }
+
+    Inkscape::XML::Node
+        *root = sp_document_repr_root(tempdoc);
+
+    if (!root)
+        return NULL;
+
+    Inkscape::XML::Node *ch = sp_repr_children(root);
+    while (ch != NULL && 
+           strcmp(ch->name(), "svg:g") &&
+           strcmp(ch->name(), "svg:path") &&
+           strcmp(ch->name(), "svg:use") &&
+           strcmp(ch->name(), "svg:text") &&
+           strcmp(ch->name(), "svg:image") &&
+           strcmp(ch->name(), "svg:rect")
+        )
+        ch = ch->next();
+
+    if (ch) {
+        return ch->attribute("id");
+    }
+
+    return NULL;
+}
+
 
 /**
  * @brief Implements the Paste Style action
@@ -292,19 +341,19 @@ bool ClipboardManagerImpl::pasteStyle()
         _userWarn(desktop, _("Select <b>object(s)</b> to paste style to."));
         return false;
     }
-    
+
     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
     if ( tempdoc == NULL ) {
         _userWarn(desktop, _("No style on the clipboard."));
         return false;
     }
-    
+
     Inkscape::XML::Node
         *root = sp_document_repr_root(tempdoc),
         *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
-    
+
     bool pasted = false;
-    
+
     if (clipnode) {
         _pasteDefs(tempdoc);
         SPCSSAttr *style = sp_repr_css_attr(clipnode, "style");
@@ -329,7 +378,7 @@ bool ClipboardManagerImpl::pasteStyle()
 bool ClipboardManagerImpl::pasteSize(bool separately, bool apply_x, bool apply_y)
 {
     if(!apply_x && !apply_y) return false; // pointless parameters
-    
+
     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
     if ( desktop == NULL ) return false;
     Inkscape::Selection *selection = sp_desktop_selection(desktop);
@@ -337,14 +386,14 @@ bool ClipboardManagerImpl::pasteSize(bool separately, bool apply_x, bool apply_y
         _userWarn(desktop, _("Select <b>object(s)</b> to paste size to."));
         return false;
     }
-    
+
     // FIXME: actually, this should accept arbitrary documents
     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
     if ( tempdoc == NULL ) {
         _userWarn(desktop, _("No size on the clipboard."));
         return false;
     }
-    
+
     // retrieve size ifomration from the clipboard
     Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
     Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
@@ -353,20 +402,20 @@ bool ClipboardManagerImpl::pasteSize(bool separately, bool apply_x, bool apply_y
         Geom::Point min, max;
         sp_repr_get_point(clipnode, "min", &min);
         sp_repr_get_point(clipnode, "max", &max);
-        
+
         // resize each object in the selection
         if (separately) {
             for (GSList *i = const_cast<GSList*>(selection->itemList()) ; i ; i = i->next) {
                 SPItem *item = SP_ITEM(i->data);
-                NR::Maybe<NR::Rect> obj_size = sp_item_bbox_desktop(item);
-                if ( !obj_size || obj_size->isEmpty() ) continue;
+                Geom::OptRect obj_size = sp_item_bbox_desktop(item);
+                if ( !obj_size ) continue;
                 sp_item_scale_rel(item, _getScale(min, max, *obj_size, apply_x, apply_y));
             }
         }
         // resize the selection as a whole
         else {
-            NR::Maybe<NR::Rect> sel_size = selection->bounds();
-            if ( sel_size && !sel_size->isEmpty() ) {
+            Geom::OptRect sel_size = selection->bounds();
+            if ( sel_size ) {
                 sp_selection_scale_relative(selection, sel_size->midpoint(),
                     _getScale(min, max, *sel_size, apply_x, apply_y));
             }
@@ -385,17 +434,17 @@ bool ClipboardManagerImpl::pastePathEffect()
 {
     /** @todo FIXME: pastePathEffect crashes when moving the path with the applied effect,
         segfaulting in fork_private_if_necessary(). */
-    
+
     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
     if ( desktop == NULL )
         return false;
-    
+
     Inkscape::Selection *selection = sp_desktop_selection(desktop);
-    if (selection->isEmpty()) {
+    if (selection && selection->isEmpty()) {
         _userWarn(desktop, _("Select <b>object(s)</b> to paste live path effect to."));
         return false;
     }
-    
+
     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
     if ( tempdoc ) {
         Inkscape::XML::Node *root = sp_document_repr_root(tempdoc);
@@ -405,10 +454,11 @@ bool ClipboardManagerImpl::pastePathEffect()
             if ( effect ) {
                 _pasteDefs(tempdoc);
                 // make sure all selected items are converted to paths first (i.e. rectangles)
-                sp_selected_path_to_curves(false);
+                sp_selected_path_to_curves(desktop, false);
                 for (GSList *item = const_cast<GSList *>(selection->itemList()) ; item ; item = item->next) {
                     _applyPathEffect(reinterpret_cast<SPItem*>(item->data), effect);
                 }
+
                 return true;
             }
         }
@@ -481,11 +531,11 @@ void ClipboardManagerImpl::_copySelection(Inkscape::Selection *selection)
     for (GSList *i = const_cast<GSList *>(items) ; i != NULL ; i = i->next) {
         _copyUsedDefs(SP_ITEM (i->data));
     }
-    
+
     // copy the representation of the items
     GSList *sorted_items = g_slist_copy(const_cast<GSList *>(items));
     sorted_items = g_slist_sort(sorted_items, (GCompareFunc) sp_object_compare_position);
-    
+
     for (GSList *i = sorted_items ; i ; i = i->next) {
         if (!SP_IS_ITEM(i->data)) continue;
         Inkscape::XML::Node *obj = SP_OBJECT_REPR(i->data);
@@ -503,7 +553,7 @@ void ClipboardManagerImpl::_copySelection(Inkscape::Selection *selection)
         obj_copy->setAttribute("transform", transform_str);
         g_free(transform_str);
     }
-    
+
     // copy style for Paste Style action
     if (sorted_items) {
         if(SP_IS_ITEM(sorted_items->data)) {
@@ -511,7 +561,7 @@ void ClipboardManagerImpl::_copySelection(Inkscape::Selection *selection)
             sp_repr_css_set(_clipnode, style, "style");
             sp_repr_css_attr_unref(style);
         }
-        
+
         // copy path effect from the first path
         if (SP_IS_OBJECT(sorted_items->data)) {
             gchar const *effect = SP_OBJECT_REPR(sorted_items->data)->attribute("inkscape:path-effect");
@@ -520,13 +570,13 @@ void ClipboardManagerImpl::_copySelection(Inkscape::Selection *selection)
             }
         }
     }
-    
-    NR::Maybe<NR::Rect> size = selection->bounds();
+
+    Geom::OptRect size = selection->bounds();
     if (size) {
-        sp_repr_set_point(_clipnode, "min", size->min().to_2geom());
-        sp_repr_set_point(_clipnode, "max", size->max().to_2geom());
+        sp_repr_set_point(_clipnode, "min", size->min());
+        sp_repr_set_point(_clipnode, "max", size->max());
     }
-    
+
     g_slist_free(sorted_items);
 }
 
@@ -538,7 +588,7 @@ void ClipboardManagerImpl::_copyUsedDefs(SPItem *item)
 {
     // copy fill and stroke styles (patterns and gradients)
     SPStyle *style = SP_OBJECT_STYLE(item);
-    
+
     if (style && (style->fill.isPaintserver())) {
         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
         if (SP_IS_LINEARGRADIENT(server) || SP_IS_RADIALGRADIENT(server))
@@ -553,7 +603,7 @@ void ClipboardManagerImpl::_copyUsedDefs(SPItem *item)
         if (SP_IS_PATTERN(server))
             _copyPattern(SP_PATTERN(server));
     }
-    
+
     // For shapes, copy all of the shape's markers
     if (SP_IS_SHAPE(item)) {
         SPShape *shape = SP_SHAPE (item);
@@ -563,11 +613,16 @@ void ClipboardManagerImpl::_copyUsedDefs(SPItem *item)
             }
         }
     }
-    // For lpe items, copy liveeffect if applicable
+    // For lpe items, copy lpe stack if applicable
     if (SP_IS_LPE_ITEM(item)) {
         SPLPEItem *lpeitem = SP_LPE_ITEM (item);
         if (sp_lpe_item_has_path_effect(lpeitem)) {
-            _copyNode(SP_OBJECT_REPR(SP_OBJECT(sp_lpe_item_get_livepatheffectobject(lpeitem))), _doc, _defs);
+            for (PathEffectList::iterator it = lpeitem->path_effect_list->begin(); it != lpeitem->path_effect_list->end(); ++it)
+            {
+                LivePathEffectObject *lpeobj = (*it)->lpeobject;
+                if (lpeobj)
+                    _copyNode(SP_OBJECT_REPR(SP_OBJECT(lpeobj)), _doc, _defs);
+            }
         }
     }
     // For 3D boxes, copy perspectives
@@ -648,7 +703,7 @@ void ClipboardManagerImpl::_copyTextPath(SPTextPath *tp)
     SPItem *path = sp_textpath_get_path_item(tp);
     if(!path) return;
     Inkscape::XML::Node *path_node = SP_OBJECT_REPR(path);
-    
+
     // Do not copy the text path to defs if it's already copied
     if(sp_repr_lookup_child(_root, "id", path_node->attribute("id"))) return;
     _copyNode(path_node, _doc, _defs);
@@ -685,10 +740,10 @@ void ClipboardManagerImpl::_pasteDocument(SPDocument *clipdoc, bool in_place)
         *root = sp_document_repr_root(clipdoc),
         *target_parent = SP_OBJECT_REPR(desktop->currentLayer());
     Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
-    
+
     // copy definitions
     _pasteDefs(clipdoc);
-    
+
     // copy objects
     GSList *pasted_objects = NULL;
     for (Inkscape::XML::Node *obj = root->firstChild() ; obj ; obj = obj->next()) {
@@ -701,35 +756,59 @@ void ClipboardManagerImpl::_pasteDocument(SPDocument *clipdoc, bool in_place)
         pasted_objects = g_slist_prepend(pasted_objects, (gpointer) obj_copy);
     }
     
-    Inkscape::Selection *selection = sp_desktop_selection(desktop);
-    selection->setReprList(pasted_objects);
+    /* The pasted objects are at the origin of the document coordinates (i.e. the upper left corner
+     * of the bounding box of the pasted selection is aligned to the upper left page corner).
+     * Now we will move the pasted objects to where we want them to be, which is either at the
+     * original position ("in place") or at the location of the mouse pointer (optionaly with snapping
+     * to the grid)
+     */ 
+
+    Geom::Point rel_pos_original, rel_pos_mouse;
     
-    // move the selection to the right position
-    if(in_place)
-    {
-        Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
-        if (clipnode) {
-            Geom::Point min, max;
-            sp_repr_get_point(clipnode, "min", &min);
-            sp_repr_get_point(clipnode, "max", &max);
-            
-            // this formula was discovered empyrically
-            min[Geom::Y] += ((max[Geom::Y] - min[Geom::Y]) - sp_document_height(target_document));
-            sp_selection_move_relative(selection, NR::Point(min));
-        }
+    // Calculate the relative location of the original objects
+    Inkscape::XML::Node *clipnode = sp_repr_lookup_name(root, "inkscape:clipboard", 1);
+    if (clipnode) {
+        Geom::Point min, max;
+        // Get two bounding box corners of the data in the clipboard (still in it's original position)
+        sp_repr_get_point(clipnode, "min", &min); //In desktop coordinates
+        sp_repr_get_point(clipnode, "max", &max);        
+        // Calculate the upper-left page corner in desktop coordinates (where the pasted objects are located)
+        Geom::Point ul_page_corner = desktop->doc2dt(Geom::Point(0,0)); 
+        // Calculate the upper-left bbox corner of the original objects
+        Geom::Point ul_sel_corner = Geom::Point(min[Geom::X], max[Geom::Y]);
+        // Now calculate how far we would have to move the pasted objects to get them
+        // at the location of the original
+        rel_pos_original = ul_sel_corner - ul_page_corner; // in desktop coordinates
     }
-    // copied from former sp_selection_paste in selection-chemistry.cpp
-    else {
-        sp_document_ensure_up_to_date(target_document);
-        NR::Maybe<NR::Rect> sel_size = selection->bounds();
-
-        NR::Point m( desktop->point() );
-        if (sel_size) {
-            m -= sel_size->midpoint();
-        }
-        sp_selection_move_relative(selection, m);
+    
+    // Calculate the relative location of the mouse pointer
+    Inkscape::Selection *selection = sp_desktop_selection(desktop);
+    selection->setReprList(pasted_objects);         // Change the selection to the freshly pasted objects
+    sp_document_ensure_up_to_date(target_document); // Update (among other things) all curves in paths, for bounds() to work
+    
+    Geom::OptRect sel_bbox = selection->bounds(); //In desktop coordinates
+    // PS: We could also have used the min/max corners calculated above, instead of selection->bounds() because 
+    // we know that after pasting the upper left corner of the selection will be aligend to the corresponding 
+    // page corner. Using the boundingbox of the selection is more foolproof though
+    if (sel_bbox) {
+        Geom::Point pos_mouse = desktop->point(); //Location of mouse pointer in desktop coordinates
+        // Now calculate how far we would have to move the pasted objects to get their
+        // midpoint at the location of the mouse pointer
+        rel_pos_mouse = pos_mouse - to_2geom(sel_bbox->midpoint());
+    }
+    
+    // Determine which offset we need to apply to the pasted objects
+    Geom::Point offset;
+    if (in_place) { // Align the pasted objects with their originals
+        offset = rel_pos_original;        
+    } else { // Stick to the grid if snapping is enabled, otherwise paste at mouse position;
+        SnapManager &m = desktop->namedview->snap_manager;
+        m.setup(desktop, false); //Don't display the snapindicator
+        offset = rel_pos_original + m.multipleOfGridPitch(rel_pos_mouse - rel_pos_original); 
     }
     
+    // Apply the offset to the pasted objects
+    sp_selection_move_relative(selection, offset);
     g_slist_free(pasted_objects);
 }
 
@@ -749,30 +828,10 @@ void ClipboardManagerImpl::_pasteDefs(SPDocument *clipdoc)
         *defs = sp_repr_lookup_name(root, "svg:defs", 1),
         *target_defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(target_document));
     Inkscape::XML::Document *target_xmldoc = sp_document_repr_doc(target_document);
-        
+
+    prevent_id_clashes(clipdoc, target_document);
+    
     for (Inkscape::XML::Node *def = defs->firstChild() ; def ; def = def->next()) {
-        /// @todo TODO: implement def id collision resolution in ClipboardManagerImpl::_pasteDefs()
-        
-        /*
-        // simplistic solution: when a collision occurs, add "a" to id until it's unique
-        Glib::ustring pasted_id = def->attribute("id");
-        if ( pasted_id.empty() ) continue; // defs without id are useless
-        Glib::ustring pasted_id_original = pasted_id;
-        
-        while(sp_repr_lookup_child(target_defs, "id", pasted_id.data())) {
-            pasted_id.append("a");
-        }
-        
-        if ( pasted_id != pasted_id_original ) {
-            def->setAttribute("id", pasted_id.data());
-            // Update the id in the rest of the document so there are no dangling references
-            // How to do that?
-            _changeIdReferences(clipdoc, pasted_id_original, pasted_id);
-        }
-        */
-        if (sp_repr_lookup_child(target_defs, "id", def->attribute("id")))
-            continue; // skip duplicate defs - temporary non-solution
-        
         _copyNode(def, target_xmldoc, target_defs);
     }
 }
@@ -785,7 +844,7 @@ bool ClipboardManagerImpl::_pasteImage()
 {
     SPDocument *doc = SP_ACTIVE_DOCUMENT;
     if ( doc == NULL ) return false;
-    
+
     // retrieve image data
     Glib::RefPtr<Gdk::Pixbuf> img = _clipboard->wait_for_image();
     if (!img) return false;
@@ -799,13 +858,14 @@ bool ClipboardManagerImpl::_pasteImage()
     // in 1 second.
     time_t rawtime;
     char image_filename[128];
-    gchar const *save_folder;
 
     time(&rawtime);
     strftime(image_filename, 128, "inkscape_pasted_image_%Y%m%d_%H%M%S.png", localtime( &rawtime ));
-    save_folder = (gchar const *) prefs_get_string_attribute("dialogs.save_as", "path");
-    
-    gchar *image_path = g_build_filename(save_folder, image_filename, NULL);
+    /// @todo Check whether the encoding is correct here
+    Inkscape::Preferences *prefs = Inkscape::Preferences::get();
+    std::string save_folder = Glib::filename_from_utf8(prefs->getString("/dialogs/save_as/path"));
+
+    gchar *image_path = g_build_filename(save_folder.data(), image_filename, NULL);
     img->save(image_path, "png");
     file_import(doc, image_path, NULL);
     g_free(image_path);
@@ -820,18 +880,18 @@ bool ClipboardManagerImpl::_pasteText()
 {
     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
     if ( desktop == NULL ) return false;
-    
+
     // if the text editing tool is active, paste the text into the active text object
     if (tools_isactive(desktop, TOOLS_TEXT))
         return sp_text_paste_inline(desktop->event_context);
-    
+
     // try to parse the text as a color and, if successful, apply it as the current style
     SPCSSAttr *css = _parseColor(_clipboard->wait_for_text());
     if (css) {
         sp_desktop_set_style(desktop, css);
         return true;
     }
-    
+
     return false;
 }
 
@@ -843,11 +903,12 @@ bool ClipboardManagerImpl::_pasteText()
  */
 SPCSSAttr *ClipboardManagerImpl::_parseColor(const Glib::ustring &text)
 {
+// TODO reuse existing code instead of replicating here.
     Glib::ustring::size_type len = text.bytes();
     char *str = const_cast<char *>(text.data());
     bool attempt_alpha = false;
     if ( !str || ( *str == '\0' ) ) return NULL; // this is OK due to boolean short-circuit
-    
+
     // those conditionals guard against parsing e.g. the string "fab" as "fab000"
     // (incomplete color) and "45fab71" as "45fab710" (incomplete alpha)
     if ( *str == '#' ) {
@@ -857,12 +918,12 @@ SPCSSAttr *ClipboardManagerImpl::_parseColor(const Glib::ustring &text)
         if ( len < 6 ) return NULL;
         if ( len >= 8 ) attempt_alpha = true;
     }
-    
+
     unsigned int color = 0, alpha = 0xff;
-    
+
     // skip a leading #, if present
     if ( *str == '#' ) ++str;
-    
+
     // try to parse first 6 digits
     int res = sscanf(str, "%6x", &color);
     if ( res && ( res != EOF ) ) {
@@ -872,12 +933,12 @@ SPCSSAttr *ClipboardManagerImpl::_parseColor(const Glib::ustring &text)
         }
 
         SPCSSAttr *color_css = sp_repr_css_attr_new();
-        
+
         // print and set properties
         gchar color_str[16];
         g_snprintf(color_str, 16, "#%06x", color);
         sp_repr_css_set_property(color_css, "fill", color_str);
-        
+
         float opacity = static_cast<float>(alpha)/static_cast<float>(0xff);
         if (opacity > 1.0) opacity = 1.0; // safeguard
         Inkscape::CSSOStringStream opcss;
@@ -896,7 +957,7 @@ void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effect)
 {
     if ( item == NULL ) return;
     if ( SP_IS_RECT(item) ) return;
-    
+
     if (SP_IS_LPE_ITEM(item))
     {
         SPLPEItem *lpeitem = SP_LPE_ITEM(item);
@@ -904,7 +965,7 @@ void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effect)
         if (!obj) return;
         // if the effect is not used by anyone, we might as well take it
         LivePathEffectObject *lpeobj = LIVEPATHEFFECT(obj)->fork_private_if_necessary(1);
-        sp_lpe_item_set_path_effect(lpeitem, lpeobj);
+        sp_lpe_item_add_path_effect(lpeitem, lpeobj);
     }
 }
 
@@ -916,38 +977,77 @@ void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effect)
 SPDocument *ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_target)
 {
     Glib::ustring best_target;
-    if ( required_target == "" ) best_target = _getBestTarget();
-    else best_target = required_target;
+    if ( required_target == "" )
+        best_target = _getBestTarget();
+    else
+        best_target = required_target;
 
     if ( best_target == "" ) {
         return NULL;
     }
-    
-    // doing this synchronously makes better sense
-    Gtk::SelectionData sel = _clipboard->wait_for_contents(best_target);
-    
-    Glib::ustring target = sel.get_target();
-    
+
+    // FIXME: Temporary hack until we add memory input.
+    // Save the clipboard contents to some file, then read it
+    gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-import", NULL );
+
+    bool file_saved = false;
+    Glib::ustring target = best_target;
+
+#ifdef WIN32
+    if (best_target == CLIPBOARD_WIN32_EMF_TARGET)
+    {   // Try to save clipboard data as en emf file (using win32 api)
+        if (OpenClipboard(NULL)) {
+            HGLOBAL hglb = GetClipboardData(CF_ENHMETAFILE);
+            if (hglb) {
+                HENHMETAFILE hemf = CopyEnhMetaFile((HENHMETAFILE) hglb, filename);
+                if (hemf) {
+                    file_saved = true;
+                    target = CLIPBOARD_WIN32_EMF_MIME;
+                    DeleteEnhMetaFile(hemf);
+                }
+            }
+            CloseClipboard();
+        }
+    }
+#endif
+
+    if (!file_saved) {
+        if ( !_clipboard->wait_is_target_available(best_target) ) {
+            return NULL;
+        }
+
+        // doing this synchronously makes better sense
+        // TODO: use another method because this one is badly broken imo.
+        // from documentation: "Returns: A SelectionData object, which will be invalid if retrieving the given target failed."
+        // I don't know how to check whether an object is 'valid' or not, unusable if that's not possible...
+        Gtk::SelectionData sel = _clipboard->wait_for_contents(best_target);
+        target = sel.get_target();  // this can crash if the result was invalid of last function. No way to check for this :(
+
+        // FIXME: Temporary hack until we add memory input.
+        // Save the clipboard contents to some file, then read it
+        g_file_set_contents(filename, (const gchar *) sel.get_data(), sel.get_length(), NULL);
+    }
+
     // there is no specific plain SVG input extension, so if we can paste the Inkscape SVG format,
     // we use the image/svg+xml mimetype to look up the input extension
     if(target == "image/x-inkscape-svg")
         target = "image/svg+xml";
-    
+
     Inkscape::Extension::DB::InputList inlist;
     Inkscape::Extension::db.get_input_list(inlist);
     Inkscape::Extension::DB::InputList::const_iterator in = inlist.begin();
     for (; in != inlist.end() && target != (*in)->get_mimetype() ; ++in);
-    if ( in == inlist.end() ) return NULL; // this shouldn't happen unless _getBestTarget returns something bogus
-    
-    // FIXME: Temporary hack until we add memory input.
-    // Save the clipboard contents to some file, then read it
-    gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-import", NULL );
-    g_file_set_contents(filename, (const gchar *) sel.get_data(), sel.get_length(), NULL);
-    
-    SPDocument *tempdoc = (*in)->open(filename);
+    if ( in == inlist.end() )
+        return NULL; // this shouldn't happen unless _getBestTarget returns something bogus
+
+    SPDocument *tempdoc = NULL;
+    try {
+        tempdoc = (*in)->open(filename);
+    } catch (...) {
+    }
     g_unlink(filename);
     g_free(filename);
-    
+
     return tempdoc;
 }
 
@@ -958,30 +1058,65 @@ SPDocument *ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_targ
  * Finds a suitable output extension to save the internal clipboard document,
  * then saves it to memory and sets the clipboard contents.
  */
-void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint info)
+void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint /*info*/)
 {
     g_assert( _clipboardSPDoc != NULL );
-    
-    const Glib::ustring target = sel.get_target();
+
+    Glib::ustring target = sel.get_target();
     if(target == "") return; // this shouldn't happen
-    
+
+    if (target == CLIPBOARD_TEXT_TARGET) {
+        target = "image/x-inkscape-svg";
+    }
+
     Inkscape::Extension::DB::OutputList outlist;
     Inkscape::Extension::db.get_output_list(outlist);
     Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
     for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out);
-    if ( out == outlist.end() ) return; // this also shouldn't happen
-    
+    if ( out == outlist.end() && target != "image/png") return; // this also shouldn't happen
+
     // FIXME: Temporary hack until we add support for memory output.
     // Save to a temporary file, read it back and then set the clipboard contents
     gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export", NULL );
     gsize len; gchar *data;
-    
-    (*out)->save(_clipboardSPDoc, filename);
-    g_file_get_contents(filename, &data, &len, NULL);
+
+    try {
+        if (out == outlist.end() && target == "image/png")
+        {
+            gdouble dpi = PX_PER_IN;
+            guint32 bgcolor = 0x00000000;
+
+            Geom::Point origin (SP_ROOT(_clipboardSPDoc->root)->x.computed, SP_ROOT(_clipboardSPDoc->root)->y.computed);
+            Geom::Rect area = Geom::Rect(origin, origin + sp_document_dimensions(_clipboardSPDoc));
+
+            unsigned long int width = (unsigned long int) (area.width() * dpi / PX_PER_IN + 0.5);
+            unsigned long int height = (unsigned long int) (area.height() * dpi / PX_PER_IN + 0.5);
+
+            // read from namedview
+            Inkscape::XML::Node *nv = sp_repr_lookup_name (_clipboardSPDoc->rroot, "sodipodi:namedview");
+            if (nv && nv->attribute("pagecolor"))
+                bgcolor = sp_svg_read_color(nv->attribute("pagecolor"), 0xffffff00);
+            if (nv && nv->attribute("inkscape:pageopacity"))
+                bgcolor |= SP_COLOR_F_TO_U(sp_repr_get_double_attribute (nv, "inkscape:pageopacity", 1.0));
+
+            sp_export_png_file(_clipboardSPDoc, filename, area, width, height, dpi, dpi, bgcolor, NULL, NULL, true, NULL);
+        }
+        else
+        {
+            if (!(*out)->loaded()) {
+                // Need to load the extension.
+                (*out)->set_state(Inkscape::Extension::Extension::STATE_LOADED);
+            }
+            (*out)->save(_clipboardSPDoc, filename);
+        }
+        g_file_get_contents(filename, &data, &len, NULL);
+
+        sel.set(8, (guint8 const *) data, len);
+    } catch (...) {
+    }
+
     g_unlink(filename); // delete the temporary file
     g_free(filename);
-    
-    sel.set(8, (guint8 const *) data, len);
 }
 
 
@@ -1009,7 +1144,7 @@ void ClipboardManagerImpl::_createInternalClipboard()
         _defs = SP_OBJECT_REPR(SP_DOCUMENT_DEFS(_clipboardSPDoc));
         _doc = sp_document_repr_doc(_clipboardSPDoc);
         _root = sp_document_repr_root(_clipboardSPDoc);
-        
+
         _clipnode = _doc->createElement("inkscape:clipboard");
         _root->appendChild(_clipnode);
         Inkscape::GC::release(_clipnode);
@@ -1036,17 +1171,17 @@ void ClipboardManagerImpl::_discardInternalClipboard()
 /**
  * @brief Get the scale to resize an item, based on the command and desktop state
  */
-NR::scale ClipboardManagerImpl::_getScale(Geom::Point &min, Geom::Point &max, NR::Rect &obj_rect, bool apply_x, bool apply_y)
+Geom::Scale ClipboardManagerImpl::_getScale(Geom::Point const &min, Geom::Point const &max, Geom::Rect const &obj_rect, bool apply_x, bool apply_y)
 {
     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
     double scale_x = 1.0;
     double scale_y = 1.0;
-    
+
     if (apply_x) {
-        scale_x = (max[Geom::X] - min[Geom::X]) / obj_rect.extent(NR::X);
+        scale_x = (max[Geom::X] - min[Geom::X]) / obj_rect[Geom::X].extent();
     }
     if (apply_y) {
-        scale_y = (max[Geom::Y] - min[Geom::Y]) / obj_rect.extent(NR::Y);
+        scale_y = (max[Geom::Y] - min[Geom::Y]) / obj_rect[Geom::Y].extent();
     }
     // If the "lock aspect ratio" button is pressed and we paste only a single coordinate,
     // resize the second one by the same ratio too
@@ -1054,8 +1189,8 @@ NR::scale ClipboardManagerImpl::_getScale(Geom::Point &min, Geom::Point &max, NR
         if (apply_x && !apply_y) scale_y = scale_x;
         if (apply_y && !apply_x) scale_x = scale_y;
     }
-    
-    return NR::scale(scale_x, scale_y);
+
+    return Geom::Scale(scale_x, scale_y);
 }
 
 
@@ -1065,7 +1200,7 @@ NR::scale ClipboardManagerImpl::_getScale(Geom::Point &min, Geom::Point &max, NR
 Glib::ustring ClipboardManagerImpl::_getBestTarget()
 {
     std::list<Glib::ustring> targets = _clipboard->wait_for_targets();
-    
+
     // clipboard target debugging snippet
     /*
     g_debug("Begin clipboard targets");
@@ -1073,18 +1208,38 @@ Glib::ustring ClipboardManagerImpl::_getBestTarget()
         g_debug("Clipboard target: %s", (*x).data());
     g_debug("End clipboard targets\n");
     //*/
-    
+
     for(std::list<Glib::ustring>::iterator i = _preferred_targets.begin() ;
         i != _preferred_targets.end() ; ++i)
     {
         if ( std::find(targets.begin(), targets.end(), *i) != targets.end() )
             return *i;
     }
+#ifdef WIN32
+    if (OpenClipboard(NULL))
+    {   // If both bitmap and metafile are present, pick the one that was exported first.
+        UINT format = EnumClipboardFormats(0);
+        while (format) {
+            if (format == CF_ENHMETAFILE || format == CF_DIB || format == CF_BITMAP)
+                break;
+            format = EnumClipboardFormats(format);
+        }
+        CloseClipboard();
+        
+        if (format == CF_ENHMETAFILE)
+            return CLIPBOARD_WIN32_EMF_TARGET;
+        if (format == CF_DIB || format == CF_BITMAP)
+            return CLIPBOARD_GDK_PIXBUF_TARGET;
+    }
+    
+    if (IsClipboardFormatAvailable(CF_ENHMETAFILE))
+        return CLIPBOARD_WIN32_EMF_TARGET;
+#endif
     if (_clipboard->wait_is_image_available())
         return CLIPBOARD_GDK_PIXBUF_TARGET;
     if (_clipboard->wait_is_text_available())
         return CLIPBOARD_TEXT_TARGET;
-    
+
     return "";
 }
 
@@ -1093,17 +1248,73 @@ Glib::ustring ClipboardManagerImpl::_getBestTarget()
  * @brief Set the clipboard targets to reflect the mimetypes Inkscape can output
  */
 void ClipboardManagerImpl::_setClipboardTargets()
-{   
+{
     Inkscape::Extension::DB::OutputList outlist;
     Inkscape::Extension::db.get_output_list(outlist);
     std::list<Gtk::TargetEntry> target_list;
+    bool plaintextSet = false;
     for (Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin() ; out != outlist.end() ; ++out) {
-        target_list.push_back(Gtk::TargetEntry( (*out)->get_mimetype() ));
+        if ( !(*out)->deactivated() ) {
+            Glib::ustring mime = (*out)->get_mimetype();
+            if (mime != CLIPBOARD_TEXT_TARGET) {
+                if ( !plaintextSet && (mime.find("svg") == Glib::ustring::npos) ) {
+                    target_list.push_back(Gtk::TargetEntry(CLIPBOARD_TEXT_TARGET));
+                    plaintextSet = true;
+                }
+                target_list.push_back(Gtk::TargetEntry(mime));
+            }
+        }
     }
-    
+
+    // Add PNG export explicitly since there is no extension for this...
+    // On Windows, GTK will also present this as a CF_DIB/CF_BITMAP
+    target_list.push_back(Gtk::TargetEntry( "image/png" ));
+
     _clipboard->set(target_list,
         sigc::mem_fun(*this, &ClipboardManagerImpl::_onGet),
         sigc::mem_fun(*this, &ClipboardManagerImpl::_onClear));
+
+#ifdef WIN32
+    // If the "image/x-emf" target handled by the emf extension would be
+    // presented as a CF_ENHMETAFILE automatically (just like an "image/bmp"
+    // is presented as a CF_BITMAP) this code would not be needed.. ???
+    // Or maybe there is some other way to achieve the same?
+
+    // Note: Metafile is the only format that is rendered and stored in clipboard
+    // on Copy, all other formats are rendered only when needed by a Paste command.
+
+    // FIXME: This should at least be rewritten to use "delayed rendering".
+    //        If possible make it delayed rendering by using GTK API only.
+
+    if (OpenClipboard(NULL)) {
+        if ( _clipboardSPDoc != NULL ) {
+            const Glib::ustring target = CLIPBOARD_WIN32_EMF_MIME;
+
+            Inkscape::Extension::DB::OutputList outlist;
+            Inkscape::Extension::db.get_output_list(outlist);
+            Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin();
+            for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out);
+            if ( out != outlist.end() ) {
+                // FIXME: Temporary hack until we add support for memory output.
+                // Save to a temporary file, read it back and then set the clipboard contents
+                gchar *filename = g_build_filename( g_get_tmp_dir(), "inkscape-clipboard-export.emf", NULL );
+
+                try {
+                    (*out)->save(_clipboardSPDoc, filename);
+                    HENHMETAFILE hemf = GetEnhMetaFileA(filename);
+                    if (hemf) {
+                        SetClipboardData(CF_ENHMETAFILE, hemf);
+                        DeleteEnhMetaFile(hemf);
+                    }
+                } catch (...) {
+                }
+                g_unlink(filename); // delete the temporary file
+                g_free(filename);
+            }
+        }
+        CloseClipboard();
+    }
+#endif
 }