Code

add method to select objects picked by a vector of points
[inkscape.git] / src / selection-chemistry.cpp
index 33f14e0506cf291d240f0f989fd1a314608b6206..f8548cdc4eda0fb199276a687c923b59de6597b8 100644 (file)
 #include "helper/units.h"
 #include "sp-item.h"
 #include "unit-constants.h"
+#include "xml/simple-document.h"
+
 using NR::X;
 using NR::Y;
 
 #include "selection-chemistry.h"
 
 /* fixme: find a better place */
+Inkscape::XML::Document *clipboard_document = NULL;
 GSList *clipboard = NULL;
 GSList *defs_clipboard = NULL;
 SPCSSAttr *style_clipboard = NULL;
-NR::Rect size_clipboard(NR::Point(0,0), NR::Point(0,0));
+NR::Maybe<NR::Rect> size_clipboard;
 
-static void sp_copy_stuff_used_by_item(GSList **defs_clip, SPItem *item, const GSList *items);
+static void sp_copy_stuff_used_by_item(GSList **defs_clip, SPItem *item, const GSList *items, Inkscape::XML::Document* xml_doc);
 
 /**
  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
  * then prepends the copy to 'clip'.
  */
-void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip)
+void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
 {
-    Inkscape::XML::Node *copy = repr->duplicate();
+    Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
 
     // copy complete inherited style
     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
@@ -108,13 +111,13 @@ void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList
     *clip = g_slist_prepend(*clip, copy);
 }
 
-void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip)
+void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip, Inkscape::XML::Document* xml_doc)
 {
 
     // Copy stuff referenced by all items to defs_clip:
     if (defs_clip) {
         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
-            sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items);
+            sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items, xml_doc);
         }
         *defs_clip = g_slist_reverse(*defs_clip);
     }
@@ -132,7 +135,7 @@ void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_c
 
         // Copy item reprs:
         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
-            sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip);
+            sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip, xml_doc);
         }
 
         *clip = g_slist_reverse(*clip);
@@ -156,22 +159,24 @@ paste_defs (GSList **defs_clip, SPDocument *doc)
         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
         gchar const *id = repr->attribute("id");
         if (!id || !doc->getObjectById(id)) {
-            Inkscape::XML::Node *copy = repr->duplicate();
+            Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
+            Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
             Inkscape::GC::release(copy);
         }
     }
 }
 
-GSList *sp_selection_paste_impl (SPDocument *document, SPObject *parent, GSList **clip, GSList **defs_clip)
+GSList *sp_selection_paste_impl (SPDocument *doc, SPObject *parent, GSList **clip, GSList **defs_clip)
 {
-    paste_defs (defs_clip, document);
+    Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
+    paste_defs (defs_clip, doc);
 
     GSList *copied = NULL;
     // add objects to document
     for (GSList *l = *clip; l != NULL; l = l->next) {
         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
-        Inkscape::XML::Node *copy = repr->duplicate();
+        Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
 
         // premultiply the item transform by the accumulated parent transform in the paste layer
         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
@@ -253,6 +258,7 @@ void sp_selection_duplicate()
     if (desktop == NULL)
         return;
 
+    Inkscape::XML::Document* xml_doc = sp_document_repr_doc(desktop->doc());
     Inkscape::Selection *selection = sp_desktop_selection(desktop);
 
     // check if something is selected
@@ -272,7 +278,7 @@ void sp_selection_duplicate()
 
     while (reprs) {
         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
-        Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate();
+        Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate(xml_doc);
 
         parent->appendChild(copy);
 
@@ -424,8 +430,8 @@ void sp_selection_group()
     if (desktop == NULL)
         return;
 
-    SPDocument *document = sp_desktop_document (desktop);
-    Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
+    SPDocument *doc = sp_desktop_document (desktop);
+    Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
 
     Inkscape::Selection *selection = sp_desktop_selection(desktop);
 
@@ -453,7 +459,7 @@ void sp_selection_group()
         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
 
         if (current->parent() == topmost_parent) {
-            Inkscape::XML::Node *spnew = current->duplicate();
+            Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
             sp_repr_unparent(current);
             group->appendChild(spnew);
             Inkscape::GC::release(spnew);
@@ -467,7 +473,7 @@ void sp_selection_group()
                 NR::Matrix item_t (NR::identity());
                 if (t_str)
                     sp_svg_transform_read(t_str, &item_t);
-                item_t *= sp_item_i2doc_affine(SP_ITEM(document->getObjectByRepr(current->parent())));
+                item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
                 //FIXME: when moving both clone and original from a transformed group (either by
                 //grouping into another parent, or by cut/paste) the transform from the original's
                 //parent becomes embedded into original itself, and this affects its clones. Fix
@@ -475,17 +481,17 @@ void sp_selection_group()
                 //then, if this is clone, looking up its original in that array and pre-multiplying
                 //it by the inverse of that original's transform diff.
 
-                sp_selection_copy_one (current, item_t, &temp_clip);
+                sp_selection_copy_one (current, item_t, &temp_clip, xml_doc);
                 sp_repr_unparent(current);
 
                 // paste into topmost_parent (temporarily)
-                GSList *copied = sp_selection_paste_impl (document, document->getObjectByRepr(topmost_parent), &temp_clip, NULL);
+                GSList *copied = sp_selection_paste_impl (doc, doc->getObjectByRepr(topmost_parent), &temp_clip, NULL);
                 if (temp_clip) g_slist_free (temp_clip);
                 if (copied) { // if success,
                     // take pasted object (now in topmost_parent)
                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
                     // make a copy
-                    Inkscape::XML::Node *spnew = in_topmost->duplicate();
+                    Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
                     // remove pasted
                     sp_repr_unparent(in_topmost);
                     // put its copy into group
@@ -576,7 +582,7 @@ sp_item_list_common_parent_group(const GSList *items)
         return NULL;
     }
     SPObject *parent = SP_OBJECT_PARENT(items->data);
-    /* Strictly speaking this CAN happen, if user selects <svg> from XML editor */
+    /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
     if (!SP_IS_GROUP(parent)) {
         return NULL;
     }
@@ -591,17 +597,15 @@ sp_item_list_common_parent_group(const GSList *items)
 
 /** Finds out the minimum common bbox of the selected items
  */
-NR::Rect
+static NR::Maybe<NR::Rect>
 enclose_items(const GSList *items)
 {
     g_assert(items != NULL);
 
-    NR::Rect r = sp_item_bbox_desktop((SPItem *) items->data);
-
-    for (GSList *i = items->next; i; i = i->next) {
-        r = NR::Rect::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
+    NR::Maybe<NR::Rect> r = NR::Nothing();
+    for (GSList const *i = items; i; i = i->next) {
+        r = NR::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
     }
-
     return r;
 }
 
@@ -647,24 +651,31 @@ sp_selection_raise()
     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
 
     // find out the common bbox of the selected items
-    NR::Rect selected = enclose_items(items);
+    NR::Maybe<NR::Rect> selected = enclose_items(items);
 
     // for all objects in the selection (starting from top)
-    while (rev) {
-        SPObject *child = SP_OBJECT(rev->data);
-        // for each selected object, find the next sibling
-        for (SPObject *newref = child->next; newref; newref = newref->next) {
-            // if the sibling is an item AND overlaps our selection,
-            if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
-                // AND if it's not one of our selected objects,
-                if (!g_slist_find((GSList *) items, newref)) {
-                    // move the selected object after that sibling
-                    grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
+    if (selected) {
+        while (rev) {
+            SPObject *child = SP_OBJECT(rev->data);
+            // for each selected object, find the next sibling
+            for (SPObject *newref = child->next; newref; newref = newref->next) {
+                // if the sibling is an item AND overlaps our selection,
+                if (SP_IS_ITEM(newref)) {
+                    NR::Maybe<NR::Rect> newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
+                    if ( newref_bbox && selected->intersects(*newref_bbox) ) {
+                        // AND if it's not one of our selected objects,
+                        if (!g_slist_find((GSList *) items, newref)) {
+                            // move the selected object after that sibling
+                            grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
+                        }
+                        break;
+                    }
                 }
-                break;
             }
+            rev = g_slist_remove(rev, child);
         }
-        rev = g_slist_remove(rev, child);
+    } else {
+        g_slist_free(rev);
     }
 
     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
@@ -731,7 +742,7 @@ sp_selection_lower()
     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
 
     // find out the common bbox of the selected items
-    NR::Rect selected = enclose_items(items);
+    NR::Maybe<NR::Rect> selected = enclose_items(items);
 
     /* construct direct-ordered list of selected children */
     GSList *rev = g_slist_copy((GSList *) items);
@@ -739,30 +750,36 @@ sp_selection_lower()
     rev = g_slist_reverse(rev);
 
     // for all objects in the selection (starting from top)
-    while (rev) {
-        SPObject *child = SP_OBJECT(rev->data);
-        // for each selected object, find the prev sibling
-        for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
-            // if the sibling is an item AND overlaps our selection,
-            if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
-                // AND if it's not one of our selected objects,
-                if (!g_slist_find((GSList *) items, newref)) {
-                    // move the selected object before that sibling
-                    SPObject *put_after = prev_sibling(newref);
-                    if (put_after)
-                        grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
-                    else
-                        SP_OBJECT_REPR(child)->setPosition(0);
+    if (selected) {
+        while (rev) {
+            SPObject *child = SP_OBJECT(rev->data);
+            // for each selected object, find the prev sibling
+            for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
+                // if the sibling is an item AND overlaps our selection,
+                if (SP_IS_ITEM(newref)) {
+                    NR::Maybe<NR::Rect> ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
+                    if ( ref_bbox && selected->intersects(*ref_bbox) ) {
+                        // AND if it's not one of our selected objects,
+                        if (!g_slist_find((GSList *) items, newref)) {
+                            // move the selected object before that sibling
+                            SPObject *put_after = prev_sibling(newref);
+                            if (put_after)
+                                grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
+                            else
+                                SP_OBJECT_REPR(child)->setPosition(0);
+                        }
+                        break;
+                    }
                 }
-                break;
             }
+            rev = g_slist_remove(rev, child);
         }
-        rev = g_slist_remove(rev, child);
+    } else {
+        g_slist_free(rev);
     }
 
     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER, 
                      _("Lower"));
-
 }
 
 void sp_selection_lower_to_bottom()
@@ -833,78 +850,78 @@ void sp_selection_cut()
     sp_selection_delete();
 }
 
-void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient)
+void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient, Inkscape::XML::Document* xml_doc)
 {
     SPGradient *ref = gradient;
 
     while (ref) {
         // climb up the refs, copying each one in the chain
-        Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate();
+        Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate(xml_doc);
         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
 
         ref = ref->ref->getObject();
     }
 }
 
-void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern)
+void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern, Inkscape::XML::Document* xml_doc)
 {
     SPPattern *ref = pattern;
 
     while (ref) {
         // climb up the refs, copying each one in the chain
-        Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate();
+        Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate(xml_doc);
         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
 
         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
             if (!SP_IS_ITEM (child))
                 continue;
-            sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL);
+            sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL, xml_doc);
         }
 
         ref = ref->ref->getObject();
     }
 }
 
-void sp_copy_single (GSList **defs_clip, SPObject *thing)
+void sp_copy_single (GSList **defs_clip, SPObject *thing, Inkscape::XML::Document* xml_doc)
 {
-    Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate();
+    Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate(xml_doc);
     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
 }
 
 
-void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items)
+void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items, Inkscape::XML::Document* xml_doc)
 {
     SPItem *path = sp_textpath_get_path_item (tp);
     if (!path)
         return;
     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
         return;
-    Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate();
+    Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate(xml_doc);
     *defs_clip = g_slist_prepend (*defs_clip, repr);
 }
 
 /**
  * Copies things like patterns, markers, gradients, etc.
  */
-void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items)
+void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items, Inkscape::XML::Document* xml_doc)
 {
     SPStyle *style = SP_OBJECT_STYLE (item);
 
     if (style && (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)) {
         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
-            sp_copy_gradient (defs_clip, SP_GRADIENT(server));
+            sp_copy_gradient (defs_clip, SP_GRADIENT(server), xml_doc);
         if (SP_IS_PATTERN (server))
-            sp_copy_pattern (defs_clip, SP_PATTERN(server));
+            sp_copy_pattern (defs_clip, SP_PATTERN(server), xml_doc);
     }
 
     if (style && (style->stroke.type == SP_PAINT_TYPE_PAINTSERVER)) {
         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
-            sp_copy_gradient (defs_clip, SP_GRADIENT(server));
+            sp_copy_gradient (defs_clip, SP_GRADIENT(server), xml_doc);
         if (SP_IS_PATTERN (server))
-            sp_copy_pattern (defs_clip, SP_PATTERN(server));
+            sp_copy_pattern (defs_clip, SP_PATTERN(server), xml_doc);
     }
 
     // For shapes, copy all of the shape's markers into defs_clip
@@ -912,40 +929,40 @@ void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList
         SPShape *shape = SP_SHAPE (item);
         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
             if (shape->marker[i]) {
-                sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]));
+                sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]), xml_doc);
             }
         }
     }
 
     if (SP_IS_TEXT_TEXTPATH (item)) {
-        sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items);
+        sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items, xml_doc);
     }
 
     if (item->clip_ref->getObject()) {
-        sp_copy_single (defs_clip, item->clip_ref->getObject());
+        sp_copy_single (defs_clip, item->clip_ref->getObject(), xml_doc);
     }
 
     if (item->mask_ref->getObject()) {
         SPObject *mask = item->mask_ref->getObject();
-        sp_copy_single (defs_clip, mask);
+        sp_copy_single (defs_clip, mask, xml_doc);
         // recurse into the mask for its gradients etc.
         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
             if (SP_IS_ITEM(o))
-                sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
+                sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items, xml_doc);
         }
     }
 
     if (style->filter.filter) {
         SPObject *filter = style->filter.filter;
         if (SP_IS_FILTER(filter)) {
-            sp_copy_single (defs_clip, filter);
+            sp_copy_single (defs_clip, filter, xml_doc);
         }
     }
 
     // recurse
     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
         if (SP_IS_ITEM(o))
-            sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
+            sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items, xml_doc);
     }
 }
 
@@ -996,6 +1013,10 @@ void sp_selection_copy()
     if (desktop == NULL)
         return;
 
+    if (!clipboard_document) {
+        clipboard_document = new Inkscape::XML::SimpleDocument();
+    }
+
     Inkscape::Selection *selection = sp_desktop_selection(desktop);
 
     if (tools_isactive (desktop, TOOLS_DROPPER)) {
@@ -1012,7 +1033,7 @@ void sp_selection_copy()
     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
 
     // 0. Copy text to system clipboard
-    // FIXME: for non-texts, put serialized XML as text to the clipboard;
+    // FIXME: for non-texts, put serialized Inkscape::XML as text to the clipboard;
     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
     Glib::ustring text;
     if (tools_isactive (desktop, TOOLS_TEXT)) {
@@ -1058,7 +1079,7 @@ void sp_selection_copy()
         clipboard = g_slist_remove(clipboard, clipboard->data);
     }
 
-    sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard);
+    sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard, clipboard_document);
 
     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
         SPStyle *const query = sp_style_new();
@@ -1117,7 +1138,11 @@ void sp_selection_paste(bool in_place)
     if (!in_place) {
         sp_document_ensure_up_to_date(document);
 
-        NR::Point m( desktop->point() - selection->bounds().midpoint() );
+        NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
+        NR::Point m( desktop->point() );
+        if (sel_bbox) {
+            m -= sel_bbox->midpoint();
+        }
 
         /* Snap the offset of the new item(s) to the grid */
         /* FIXME: this gridsnap fiddling is a hack. */
@@ -1168,7 +1193,7 @@ void sp_selection_paste_size (bool apply_x, bool apply_y)
     Inkscape::Selection *selection = sp_desktop_selection(desktop);
 
     // check if something is in the clipboard
-    if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
+    if (!size_clipboard) {
         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
         return;
     }
@@ -1179,15 +1204,15 @@ void sp_selection_paste_size (bool apply_x, bool apply_y)
         return;
     }
 
-    NR::Rect current = selection->bounds();
-    if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
+    NR::Maybe<NR::Rect> current = selection->bounds();
+    if ( !current || current->isEmpty() ) {
         return;
     }
 
-    double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
-    double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
+    double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
+    double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
 
-    sp_selection_scale_relative (selection, current.midpoint(), 
+    sp_selection_scale_relative (selection, current->midpoint(),
                                  NR::scale(
                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
@@ -1204,7 +1229,7 @@ void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
     Inkscape::Selection *selection = sp_desktop_selection(desktop);
 
     // check if something is in the clipboard
-    if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
+    if ( !size_clipboard ) {
         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
         return;
     }
@@ -1218,13 +1243,13 @@ void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
         SPItem *item = SP_ITEM(l->data);
 
-        NR::Rect current = sp_item_bbox_desktop(item);
-        if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
+        NR::Maybe<NR::Rect> current = sp_item_bbox_desktop(item);
+        if ( !current || current->isEmpty() ) {
             continue;
         }
 
-        double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
-        double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
+        double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
+        double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
 
         sp_item_scale_rel (item,
                                  NR::scale(
@@ -1255,7 +1280,7 @@ void sp_selection_to_next_layer ()
     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
     if (next) {
         GSList *temp_clip = NULL;
-        sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
+        sp_selection_copy_impl (items, &temp_clip, NULL, NULL, sp_document_repr_doc(dt->doc())); // we're in the same doc, so no need to copy defs
         sp_selection_delete_impl (items);
         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
         GSList *copied;
@@ -1300,7 +1325,7 @@ void sp_selection_to_prev_layer ()
     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
     if (next) {
         GSList *temp_clip = NULL;
-        sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
+        sp_selection_copy_impl (items, &temp_clip, NULL, NULL, sp_document_repr_doc(dt->doc())); // we're in the same doc, so no need to copy defs
         sp_selection_delete_impl (items);
         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
         GSList *copied;
@@ -1511,16 +1536,16 @@ sp_selection_scale_absolute(Inkscape::Selection *selection,
     if (selection->isEmpty())
         return;
 
-    NR::Rect const bbox(selection->bounds());
-    if (bbox.isEmpty()) {
+    NR::Maybe<NR::Rect> const bbox(selection->bounds());
+    if ( !bbox || bbox->isEmpty() ) {
         return;
     }
 
-    NR::translate const p2o(-bbox.min());
+    NR::translate const p2o(-bbox->min());
 
     NR::scale const newSize(x1 - x0,
                             y1 - y0);
-    NR::scale const scale( newSize / NR::scale(bbox.dimensions()) );
+    NR::scale const scale( newSize / NR::scale(bbox->dimensions()) );
     NR::translate const o2n(x0, y0);
     NR::Matrix const final( p2o * scale * o2n );
 
@@ -1533,15 +1558,15 @@ void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const
     if (selection->isEmpty())
         return;
 
-    NR::Rect const bbox(selection->bounds());
+    NR::Maybe<NR::Rect> const bbox(selection->bounds());
 
-    if (bbox.isEmpty()) {
+    if ( !bbox || bbox->isEmpty() ) {
         return;
     }
 
     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
-    if ( bbox.extent(NR::X) * scale[NR::X] > 1e6  ||
-         bbox.extent(NR::Y) * scale[NR::Y] > 1e6 )
+    if ( bbox->extent(NR::X) * scale[NR::X] > 1e6  ||
+         bbox->extent(NR::Y) * scale[NR::Y] > 1e6 )
     {
         return;
     }
@@ -1646,9 +1671,12 @@ sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
     if (selection->isEmpty())
         return;
 
-    NR::Point center = selection->center();
+    NR::Maybe<NR::Point> center = selection->center();
+    if (!center) {
+        return;
+    }
 
-    sp_selection_rotate_relative(selection, center, angle_degrees);
+    sp_selection_rotate_relative(selection, *center, angle_degrees);
 
     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
                            ( ( angle_degrees > 0 )
@@ -1667,17 +1695,20 @@ sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
     if (selection->isEmpty())
         return;
 
-    NR::Rect const bbox(selection->bounds());
+    NR::Maybe<NR::Rect> const bbox(selection->bounds());
+    NR::Maybe<NR::Point> center = selection->center();
 
-    NR::Point center = selection->center();
+    if ( !bbox || !center ) {
+        return;
+    }
 
     gdouble const zoom = selection->desktop()->current_zoom();
     gdouble const zmove = angle / zoom;
-    gdouble const r = NR::L2(bbox.max() - center);
+    gdouble const r = NR::L2(bbox->max() - *center);
 
     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
 
-    sp_selection_rotate_relative(selection, center, zangle);
+    sp_selection_rotate_relative(selection, *center, zangle);
 
     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
                            ( (angle > 0)
@@ -1693,11 +1724,15 @@ sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
     if (selection->isEmpty())
         return;
 
-    NR::Rect const bbox(selection->bounds());
-    NR::Point const center(bbox.midpoint());
-    double const max_len = bbox.maxExtent();
+    NR::Maybe<NR::Rect> const bbox(selection->bounds());
+    if (!bbox) {
+        return;
+    }
+
+    NR::Point const center(bbox->midpoint());
 
     // you can't scale "do nizhe pola" (below zero)
+    double const max_len = bbox->maxExtent();
     if ( max_len + grow <= 1e-3 ) {
         return;
     }
@@ -1726,7 +1761,13 @@ sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
     if (selection->isEmpty())
         return;
 
-    NR::Point const center(selection->bounds().midpoint());
+    NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
+
+    if (!sel_bbox) {
+        return;
+    }
+
+    NR::Point const center(sel_bbox->midpoint());
     sp_selection_scale_relative(selection, center, NR::scale(times, times));
     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT, 
                      _("Scale by whole factor"));
@@ -1980,10 +2021,10 @@ SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
 {
     NR::Rect dbox = desktop->get_display_area();
-    NR::Rect sbox = sp_item_bbox_desktop(item);
+    NR::Maybe<NR::Rect> sbox = sp_item_bbox_desktop(item);
 
-    if (dbox.contains(sbox) == false) {
-        NR::Point const s_dt = sbox.midpoint();
+    if ( sbox && dbox.contains(*sbox) == false ) {
+        NR::Point const s_dt = sbox->midpoint();
         NR::Point const s_w = desktop->d2w(s_dt);
         NR::Point const d_dt = dbox.midpoint();
         NR::Point const d_w = desktop->d2w(d_dt);
@@ -2042,7 +2083,7 @@ sp_selection_clone()
     }
     
     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE, 
-                     _("Clone"));
+                     Q_("action|Clone"));
 
     selection->setReprList(newsel);
  
@@ -2158,8 +2199,8 @@ sp_selection_tile(bool apply)
     if (desktop == NULL)
         return;
 
-    SPDocument *document = sp_desktop_document(desktop);
-    Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
+    SPDocument *doc = sp_desktop_document(desktop);
+    Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
 
     Inkscape::Selection *selection = sp_desktop_selection(desktop);
 
@@ -2169,14 +2210,14 @@ sp_selection_tile(bool apply)
         return;
     }
 
-    sp_document_ensure_up_to_date(document);
-    NR::Rect r = selection->bounds();
-    if (r.isEmpty()) {
+    sp_document_ensure_up_to_date(doc);
+    NR::Maybe<NR::Rect> r = selection->bounds();
+    if ( !r || r->isEmpty() ) {
         return;
     }
 
     // calculate the transform to be applied to objects to move them to 0,0
-    NR::Point move_p = NR::Point(0, sp_document_height(document)) - (r.min() + NR::Point (0, r.extent(NR::Y)));
+    NR::Point move_p = NR::Point(0, sp_document_height(doc)) - (r->min() + NR::Point (0, r->extent(NR::Y)));
     move_p[NR::Y] = -move_p[NR::Y];
     NR::Matrix move = NR::Matrix (NR::translate (move_p));
 
@@ -2195,11 +2236,11 @@ sp_selection_tile(bool apply)
     // create a list of duplicates
     GSList *repr_copies = NULL;
     for (GSList *i = items; i != NULL; i = i->next) {
-        Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
+        Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
         repr_copies = g_slist_prepend (repr_copies, dup);
     }
 
-    NR::Rect bounds(desktop->dt2doc(r.min()), desktop->dt2doc(r.max()));
+    NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
 
     if (apply) {
         // delete objects so that their clones don't get alerted; this object will be restored shortly
@@ -2215,8 +2256,8 @@ sp_selection_tile(bool apply)
     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
 
-    const gchar *pat_id = pattern_tile (repr_copies, bounds, document,
-                                        NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r.min()[NR::X], r.max()[NR::Y])))) * parent_transform.inverse(), parent_transform * move);
+    const gchar *pat_id = pattern_tile (repr_copies, bounds, doc,
+                                        NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X], r->max()[NR::Y])))) * parent_transform.inverse(), parent_transform * move);
 
     // restore compensation setting
     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
@@ -2246,7 +2287,7 @@ sp_selection_tile(bool apply)
 
     g_slist_free (items);
 
-    sp_document_done (document, SP_VERB_EDIT_TILE, 
+    sp_document_done (doc, SP_VERB_EDIT_TILE, 
                       _("Objects to pattern"));
 }
 
@@ -2257,7 +2298,8 @@ sp_selection_untile()
     if (desktop == NULL)
         return;
 
-    SPDocument *document = sp_desktop_document(desktop);
+    SPDocument *doc = sp_desktop_document(desktop);
+    Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
 
     Inkscape::Selection *selection = sp_desktop_selection(desktop);
 
@@ -2295,14 +2337,14 @@ sp_selection_untile()
         pat_transform *= item->transform;
 
         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
-            Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
+            Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
 
            // FIXME: relink clones to the new canvas objects
            // use SPObject::setid when mental finishes it to steal ids of
 
             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
-            sp_document_ensure_up_to_date (document);
+            sp_document_ensure_up_to_date (doc);
 
             NR::Matrix transform( i->transform * pat_transform );
             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
@@ -2504,11 +2546,14 @@ sp_selection_create_bitmap_copy ()
     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
     NR::Matrix t;
+
+    double shift_x = bbox.x0;
+    double shift_y = bbox.y1; 
     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
-        t = NR::scale (1, -1) * NR::translate ((unsigned) (bbox.x0 + 0.5), (unsigned) (bbox.y1 + 0.5)) * eek.inverse();
-    } else {
-        t = NR::scale (1, -1) * NR::translate (bbox.x0, bbox.y1) * eek.inverse();
+        shift_x = round (shift_x);
+        shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
     }
+    t = NR::scale(1, -1) * NR::translate (shift_x, shift_y) * eek.inverse();
 
     // Do the export
     sp_export_png_file(document, filepath,
@@ -2588,7 +2633,8 @@ sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
     if (desktop == NULL)
         return;
 
-    SPDocument *document = sp_desktop_document(desktop);
+    SPDocument *doc = sp_desktop_document(desktop);
+    Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
     
     Inkscape::Selection *selection = sp_desktop_selection(desktop);
 
@@ -2610,7 +2656,7 @@ sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
     }
     // /END FIXME
     
-    sp_document_ensure_up_to_date(document);
+    sp_document_ensure_up_to_date(doc);
 
     GSList *items = g_slist_copy((GSList *) selection->itemList());
     
@@ -2628,7 +2674,7 @@ sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
 
         for (GSList *i = items; i != NULL; i = i->next) {
-            Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
+            Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
             mask_items = g_slist_prepend (mask_items, dup);
 
             if (remove_original) {
@@ -2639,7 +2685,7 @@ sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
     } else if (!topmost) {
         // topmost item is used as a mask, which is applied to other items in a selection
         GSList *i = items;
-        Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
+        Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
         mask_items = g_slist_prepend (mask_items, dup);
 
         if (remove_original) {
@@ -2656,7 +2702,7 @@ sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
             apply_to_items = g_slist_prepend (apply_to_items, i->data);
         }
 
-        Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
+        Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
         mask_items = g_slist_prepend (mask_items, dup);
 
         if (remove_original) {
@@ -2677,15 +2723,15 @@ sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
 
         GSList *mask_items_dup = NULL;
         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
-            Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate();
+            Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
         }
 
         const gchar *mask_id = NULL;
         if (apply_clip_path) {
-            mask_id = sp_clippath_create(mask_items_dup, document, &maskTransform);
+            mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
         } else {
-            mask_id = sp_mask_create(mask_items_dup, document, &maskTransform);
+            mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
         }
 
         g_slist_free (mask_items_dup);
@@ -2704,9 +2750,9 @@ sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
     g_slist_free (items_to_delete);
 
     if (apply_clip_path) 
-        sp_document_done (document, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
+        sp_document_done (doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
     else 
-        sp_document_done (document, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
+        sp_document_done (doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
 }
 
 void sp_selection_unset_mask(bool apply_clip_path) {
@@ -2714,7 +2760,8 @@ void sp_selection_unset_mask(bool apply_clip_path) {
     if (desktop == NULL)
         return;
     
-    SPDocument *document = sp_desktop_document(desktop);    
+    SPDocument *doc = sp_desktop_document(desktop);    
+    Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
     Inkscape::Selection *selection = sp_desktop_selection(desktop);
 
     // check if something is selected
@@ -2724,7 +2771,7 @@ void sp_selection_unset_mask(bool apply_clip_path) {
     }
     
     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
-    sp_document_ensure_up_to_date(document);
+    sp_document_ensure_up_to_date(doc);
 
     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
     std::map<SPObject*,SPItem*> referenced_objects;
@@ -2754,7 +2801,7 @@ void sp_selection_unset_mask(bool apply_clip_path) {
         SPObject *obj = (*it).first;
         GSList *items_to_move = NULL;
         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
-            Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
+            Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
             items_to_move = g_slist_prepend (items_to_move, copy);
         }
 
@@ -2787,9 +2834,9 @@ void sp_selection_unset_mask(bool apply_clip_path) {
     }
 
     if (apply_clip_path) 
-        sp_document_done (document, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
+        sp_document_done (doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
     else 
-        sp_document_done (document, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
+        sp_document_done (doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
 }
 
 void fit_canvas_to_selection(SPDesktop *desktop) {
@@ -2799,22 +2846,22 @@ void fit_canvas_to_selection(SPDesktop *desktop) {
     g_return_if_fail(doc != NULL);
     g_return_if_fail(desktop->selection != NULL);
     g_return_if_fail(!desktop->selection->isEmpty());
-    NRRect bbox = {0,0,0,0};
+    NRRect bbox(0, 0, 0, 0);
 
     desktop->selection->bounds(&bbox);
-    if (!empty(bbox)) {
+    if (!nr_rect_d_test_empty(&bbox)) {
         doc->fitToRect(bbox);
     }
 };
 
 void fit_canvas_to_drawing(SPDocument *doc) {
     g_return_if_fail(doc != NULL);
-    NRRect bbox = {0,0,0,0};
+    NRRect bbox(0, 0, 0, 0);
 
     sp_document_ensure_up_to_date (doc);
     sp_item_invoke_bbox(SP_ITEM(doc->root), &bbox, sp_item_i2r_affine(SP_ITEM(doc->root)), TRUE);
 
-    if (!empty(bbox)) {
+    if (!nr_rect_d_test_empty(&bbox)) {
         doc->fitToRect(bbox);
     }
 };
@@ -2836,6 +2883,60 @@ void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
                      _("Fit page to selection"));
 };
 
+static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
+    // don't operate on layers
+    if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
+        f(SP_ITEM(root), desktop);
+    }
+    for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
+        //don't recurse into locked layers
+        if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
+            itemtree_map(f, iter, desktop);
+        }
+    }
+}
+
+static void unlock(SPItem *item, SPDesktop *desktop) {
+    if (item->isLocked()) {
+        item->setLocked(FALSE);
+    }
+}
+
+static void unhide(SPItem *item, SPDesktop *desktop) {
+    if (desktop->itemIsHidden(item)) {
+        item->setExplicitlyHidden(FALSE);
+    }
+}
+
+static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
+    if (!dt) return;
+        
+    SPObject *root;
+    if (layer_only) {
+        root = dt->currentLayer();
+    } else {
+        root = dt->currentRoot();
+    }
+    
+    itemtree_map(f, root, dt);
+}
+
+void unlock_all(SPDesktop *dt) {
+    process_all(&unlock, dt, true);
+}
+
+void unlock_all_in_all_layers(SPDesktop *dt) {
+    process_all(&unlock, dt, false);
+}
+
+void unhide_all(SPDesktop *dt) {
+    process_all(&unhide, dt, true);
+}
+
+void unhide_all_in_all_layers(SPDesktop *dt) {
+    process_all(&unhide, dt, false);
+}
+
 /*
   Local Variables:
   mode:c++