Code

1) Fix moving by an integer multiple of the grid spacing (<alt>-dragging in the selec...
[inkscape.git] / src / ui / clipboard.cpp
index 17dabed82f2b256dbae1675acb5ba78074e608a0..f213160f4e2598bab6939b5f39fd40f112dbf948 100644 (file)
@@ -44,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 "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 "libnr/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"
@@ -138,12 +142,14 @@ private:
     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);
     void _userWarn(SPDesktop *, char const *);
 
+    void _inkscape_wait_for_targets(std::list<Glib::ustring> &);
+
     // private properites
     SPDocument *_clipboardSPDoc; ///< Document that stores the clipboard until someone requests it
     Inkscape::XML::Node *_defs; ///< Reference to the clipboard document's defs node
@@ -151,6 +157,10 @@ private:
     Inkscape::XML::Node *_clipnode; ///< The node that holds extra information
     Inkscape::XML::Document *_doc; ///< Reference to the clipboard's Inkscape::XML::Document
 
+    // we need a way to copy plain text AND remember its style;
+    // the standard _clipnode is only available in an SVG tree, hence this special storage
+    SPCSSAttr *_text_style; ///< Style copied along with plain text fragment
+
     Glib::RefPtr<Gtk::Clipboard> _clipboard; ///< Handle to the system wide clipboard - for convenience
     std::list<Glib::ustring> _preferred_targets; ///< List of supported clipboard targets
 };
@@ -162,6 +172,7 @@ ClipboardManagerImpl::ClipboardManagerImpl()
       _root(NULL),
       _clipnode(NULL),
       _doc(NULL),
+      _text_style(NULL),
       _clipboard( Gtk::Clipboard::get() )
 {
     // push supported clipboard targets, in order of preference
@@ -192,7 +203,28 @@ void ClipboardManagerImpl::copy()
     if (desktop->event_context->get_drag()) {
         GrDrag *drag = desktop->event_context->get_drag();
         if (drag->hasSelection()) {
-            _setClipboardColor(drag->getColor());
+            guint32 col = drag->getColor();
+
+            // set the color as clipboard content (text in RRGGBBAA format)
+            _setClipboardColor(col);
+
+            // create a style with this color on fill and opacity in master opacity, so it can be
+            // pasted on other stops or objects
+            if (_text_style) {
+                sp_repr_css_attr_unref(_text_style);
+                _text_style = NULL;
+            }
+            _text_style = sp_repr_css_attr_new();
+            // print and set properties
+            gchar color_str[16];
+            g_snprintf(color_str, 16, "#%06x", col >> 8);
+            sp_repr_css_set_property(_text_style, "fill", color_str);
+            float opacity = SP_RGBA32_A_F(col);
+            if (opacity > 1.0) opacity = 1.0; // safeguard
+            Inkscape::CSSOStringStream opcss;
+            opcss << opacity;
+            sp_repr_css_set_property(_text_style, "opacity", opcss.str().data());
+
             _discardInternalClipboard();
             return;
         }
@@ -206,14 +238,19 @@ void ClipboardManagerImpl::copy()
     }
 
     // Special case for when the text tool is active - if some text is selected, copy plain text,
-    // not the object that holds it
+    // not the object that holds it; also copy the style at cursor into
     if (tools_isactive(desktop, TOOLS_TEXT)) {
+        _discardInternalClipboard();
         Glib::ustring selected_text = sp_text_get_selected_text(desktop->event_context);
         if (!selected_text.empty()) {
             _clipboard->set_text(selected_text);
-            _discardInternalClipboard();
-            return;
         }
+        if (_text_style) {
+            sp_repr_css_attr_unref(_text_style);
+            _text_style = NULL;
+        }
+        _text_style = sp_text_get_style_at_cursor(desktop->event_context);
+        return;
     }
 
     if (selection->isEmpty()) {  // check whether something is selected
@@ -266,7 +303,7 @@ bool ClipboardManagerImpl::paste(bool in_place)
 
     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
 
@@ -305,7 +342,7 @@ const gchar *ClipboardManagerImpl::getFirstObjectID()
         return NULL;
 
     Inkscape::XML::Node *ch = sp_repr_children(root);
-    while (ch != NULL && 
+    while (ch != NULL &&
            strcmp(ch->name(), "svg:g") &&
            strcmp(ch->name(), "svg:path") &&
            strcmp(ch->name(), "svg:use") &&
@@ -340,8 +377,14 @@ bool ClipboardManagerImpl::pasteStyle()
 
     SPDocument *tempdoc = _retrieveClipboard("image/x-inkscape-svg");
     if ( tempdoc == NULL ) {
-        _userWarn(desktop, _("No style on the clipboard."));
-        return false;
+        // no document, but we can try _text_style
+        if (_text_style) {
+            sp_desktop_set_style(desktop, _text_style);
+            return true;
+        } else {
+            _userWarn(desktop, _("No style on the clipboard."));
+            return false;
+        }
     }
 
     Inkscape::XML::Node
@@ -403,15 +446,15 @@ bool ClipboardManagerImpl::pasteSize(bool separately, bool apply_x, bool apply_y
         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));
             }
@@ -450,7 +493,7 @@ 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);
                 }
@@ -545,7 +588,7 @@ void ClipboardManagerImpl::_copySelection(Inkscape::Selection *selection)
         // write the complete accumulated transform passed to us
         // (we're dealing with unattached representations, so we write to their attributes
         // instead of using sp_item_set_transform)
-        gchar *transform_str = sp_svg_transform_write(from_2geom(sp_item_i2doc_affine(SP_ITEM(i->data))));
+        gchar *transform_str = sp_svg_transform_write(sp_item_i2doc_affine(SP_ITEM(i->data)));
         obj_copy->setAttribute("transform", transform_str);
         g_free(transform_str);
     }
@@ -567,10 +610,10 @@ 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);
@@ -752,33 +795,42 @@ void ClipboardManagerImpl::_pasteDocument(SPDocument *clipdoc, bool in_place)
         pasted_objects = g_slist_prepend(pasted_objects, (gpointer) obj_copy);
     }
 
+    // Change the selection to the freshly pasted objects
     Inkscape::Selection *selection = sp_desktop_selection(desktop);
     selection->setReprList(pasted_objects);
 
-    // move the selection to the right position
-    if(in_place)
-    {
+    // invers apply parent transform
+    Geom::Matrix doc2parent = sp_item_i2doc_affine(SP_ITEM(desktop->currentLayer())).inverse();
+    sp_selection_apply_affine(selection, desktop->dt2doc() * doc2parent * desktop->doc2dt(), true, false);
+
+    // Update (among other things) all curves in paths, for bounds() to work
+    sp_document_ensure_up_to_date(target_document);
+
+    // move selection either to original position (in_place) or to mouse pointer
+    Geom::OptRect sel_bbox = selection->bounds();
+    if (sel_bbox) {
+        // get offset of selection to original position of copied elements
+        Geom::Point pos_original;
         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));
+            pos_original = Geom::Point(min[Geom::X], max[Geom::Y]);
         }
-    }
-    // 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();
+        Geom::Point offset = pos_original - sel_bbox->corner(3);
 
-        NR::Point m( desktop->point() );
-        if (sel_size) {
-            m -= sel_size->midpoint();
+        if (!in_place) {
+            SnapManager &m = desktop->namedview->snap_manager;
+            m.setup(desktop);
+            sp_event_context_discard_delayed_snap_event(desktop->event_context);
+
+            // get offset from mouse pointer to bbox center, snap to grid if enabled
+            Geom::Point mouse_offset = desktop->point() - sel_bbox->midpoint();
+            offset = m.multipleOfGridPitch(mouse_offset - offset, sel_bbox->midpoint() + offset) + offset;
         }
-        sp_selection_move_relative(selection, m);
+
+        sp_selection_move_relative(selection, offset);
     }
 
     g_slist_free(pasted_objects);
@@ -802,7 +854,7 @@ void ClipboardManagerImpl::_pasteDefs(SPDocument *clipdoc)
     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()) {
         _copyNode(def, target_xmldoc, target_defs);
     }
@@ -830,13 +882,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");
+    /// @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, image_filename, NULL);
+    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);
@@ -874,6 +927,7 @@ 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;
@@ -1006,7 +1060,7 @@ SPDocument *ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_targ
     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);
+    for (; in != inlist.end() && target != (*in)->get_mimetype() ; ++in){};
     if ( in == inlist.end() )
         return NULL; // this shouldn't happen unless _getBestTarget returns something bogus
 
@@ -1032,13 +1086,17 @@ 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);
+    for ( ; out != outlist.end() && target != (*out)->get_mimetype() ; ++out){};
     if ( out == outlist.end() && target != "image/png") return; // this also shouldn't happen
 
     // FIXME: Temporary hack until we add support for memory output.
@@ -1049,17 +1107,14 @@ void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint /*info*/)
     try {
         if (out == outlist.end() && target == "image/png")
         {
-            NRRect area;
             gdouble dpi = PX_PER_IN;
             guint32 bgcolor = 0x00000000;
 
-            area.x0 = SP_ROOT(_clipboardSPDoc->root)->x.computed;
-            area.y0 = SP_ROOT(_clipboardSPDoc->root)->y.computed;
-            area.x1 = area.x0 + sp_document_width (_clipboardSPDoc);
-            area.y1 = area.y0 + sp_document_height (_clipboardSPDoc);
+            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.x1 - area.x0) * dpi / PX_PER_IN + 0.5);
-            unsigned long int height = (unsigned long int) ((area.y1 - area.y0) * dpi / PX_PER_IN + 0.5);
+            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");
@@ -1068,10 +1123,14 @@ void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint /*info*/)
             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.x0, area.y0, area.x1, area.y1, width, height, dpi, dpi, bgcolor, NULL, NULL, true, NULL);
+            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);
@@ -1113,6 +1172,12 @@ void ClipboardManagerImpl::_createInternalClipboard()
         _clipnode = _doc->createElement("inkscape:clipboard");
         _root->appendChild(_clipnode);
         Inkscape::GC::release(_clipnode);
+
+        // once we create a SVG document, style will be stored in it, so flush _text_style
+        if (_text_style) {
+            sp_repr_css_attr_unref(_text_style);
+            _text_style = NULL;
+        }
     }
 }
 
@@ -1136,17 +1201,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
@@ -1155,7 +1220,7 @@ NR::scale ClipboardManagerImpl::_getScale(Geom::Point &min, Geom::Point &max, NR
         if (apply_y && !apply_x) scale_x = scale_y;
     }
 
-    return NR::scale(scale_x, scale_y);
+    return Geom::Scale(scale_x, scale_y);
 }
 
 
@@ -1164,7 +1229,9 @@ NR::scale ClipboardManagerImpl::_getScale(Geom::Point &min, Geom::Point &max, NR
  */
 Glib::ustring ClipboardManagerImpl::_getBestTarget()
 {
-    std::list<Glib::ustring> targets = _clipboard->wait_for_targets();
+    // GTKmm's wait_for_targets() is broken, see the comment in _inkscape_wait_for_targets()
+    std::list<Glib::ustring> targets; // = _clipboard->wait_for_targets();
+    _inkscape_wait_for_targets(targets);
 
     // clipboard target debugging snippet
     /*
@@ -1190,13 +1257,13 @@ Glib::ustring ClipboardManagerImpl::_getBestTarget()
             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
@@ -1217,8 +1284,18 @@ 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...
@@ -1293,6 +1370,35 @@ void ClipboardManagerImpl::_userWarn(SPDesktop *desktop, char const *msg)
 }
 
 
+// GTKMM's clipboard::wait_for_targets is buggy and might return bogus, see
+//
+// https://bugs.launchpad.net/inkscape/+bug/296778
+// http://mail.gnome.org/archives/gtk-devel-list/2009-June/msg00062.html
+//
+// for details. Until this has been fixed upstream we will use our own implementation
+// of this method, as copied from /gtkmm-2.16.0/gtk/gtkmm/clipboard.cc.
+void ClipboardManagerImpl::_inkscape_wait_for_targets(std::list<Glib::ustring> &listTargets)
+{
+    //Get a newly-allocated array of atoms:
+    GdkAtom* targets = 0;
+    gint n_targets = 0;
+    gboolean test = gtk_clipboard_wait_for_targets( gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), &targets, &n_targets );
+    if(!test)
+        n_targets = 0; //otherwise it will be -1.
+
+    //Add the targets to the C++ container:
+    for(int i = 0; i < n_targets; i++)
+    {
+        //Convert the atom to a string:
+        gchar* const atom_name = gdk_atom_name(targets[i]);
+
+        Glib::ustring target;
+        if(atom_name)
+            target = Glib::ScopedPtr<char>(atom_name).get(); //This frees the gchar*.
+
+        listTargets.push_back(target);
+    }
+}
 
 /* #######################################
           ClipboardManager class