diff options
| author | Martin Owens <doctormo@gmail.com> | 2014-03-27 01:33:44 +0000 |
|---|---|---|
| committer | Martin Owens <doctormo@gmail.com> | 2014-03-27 01:33:44 +0000 |
| commit | 5a4fb2325f60d292b47330f540b26a3279341c90 (patch) | |
| tree | d2aa7967be25450b83e625025366c618101ae49f /src/ui | |
| parent | The Polar Arrange Tab of the Arrange Dialog now hides the parametric (diff) | |
| parent | Remove Snap menu item and improve grid menu item text (diff) | |
| download | inkscape-5a4fb2325f60d292b47330f540b26a3279341c90.tar.gz inkscape-5a4fb2325f60d292b47330f540b26a3279341c90.zip | |
Commit a merge to trunk, with probabal errors
(bzr r11073.1.36)
Diffstat (limited to 'src/ui')
268 files changed, 41779 insertions, 6841 deletions
diff --git a/src/ui/CMakeLists.txt b/src/ui/CMakeLists.txt index 2e419bbc3..7d80f1e36 100644 --- a/src/ui/CMakeLists.txt +++ b/src/ui/CMakeLists.txt @@ -14,13 +14,38 @@ set(ui_SRC tool/manipulator.cpp tool/modifier-tracker.cpp tool/multi-path-manipulator.cpp - tool/node-tool.cpp tool/node.cpp tool/path-manipulator.cpp tool/selectable-control-point.cpp tool/selector.cpp tool/transform-handle-set.cpp + tools/arc-tool.cpp + tools/box3d-tool.cpp + tools/calligraphic-tool.cpp + tools/connector-tool.cpp + tools/dropper-tool.cpp + tools/dynamic-base.cpp + tools/eraser-tool.cpp + tools/flood-tool.cpp + tools/freehand-base.cpp + tools/gradient-tool.cpp + tools/lpe-tool.cpp + tools/measure-tool.cpp + tools/mesh-tool.cpp + tools/node-tool.cpp + tools/pencil-tool.cpp + tools/pen-tool.cpp + tools/rect-tool.cpp + tools/select-tool.cpp + tools/spiral-tool.cpp + tools/spray-tool.cpp + tools/star-tool.cpp + tools/text-tool.cpp + tools/tool-base.cpp + tools/tweak-tool.cpp + tools/zoom-tool.cpp + dialog/aboutbox.cpp dialog/align-and-distribute.cpp dialog/calligraphic-profile-rename.cpp @@ -42,6 +67,7 @@ set(ui_SRC dialog/filter-effects-dialog.cpp dialog/find.cpp dialog/floating-behavior.cpp + dialog/font-substitution.cpp dialog/glyphs.cpp dialog/grid-arrange-tab.cpp dialog/guides.cpp @@ -54,21 +80,25 @@ set(ui_SRC dialog/livepatheffect-editor.cpp dialog/memory.cpp dialog/messages.cpp + dialog/new-from-template.cpp dialog/object-attributes.cpp dialog/object-properties.cpp dialog/ocaldialogs.cpp dialog/polar-arrange-tab.cpp dialog/print-colors-preview-dialog.cpp dialog/print.cpp - dialog/scriptdialog.cpp + dialog/symbols.cpp dialog/xml-tree.cpp # dialog/session-player.cpp dialog/spellcheck.cpp dialog/svg-fonts-dialog.cpp dialog/swatches.cpp + dialog/template-load-tab.cpp + dialog/template-widget.cpp dialog/text-edit.cpp dialog/tile.cpp dialog/tracedialog.cpp + dialog/pixelartdialog.cpp dialog/transformation.cpp dialog/undo-history.cpp # dialog/whiteboard-connect.cpp @@ -83,10 +113,10 @@ set(ui_SRC widget/dock.cpp widget/entity-entry.cpp widget/entry.cpp - widget/frame.cpp widget/filter-effect-chooser.cpp - widget/handlebox.cpp - widget/icon-widget.cpp + widget/frame.cpp + widget/gimpcolorwheel.c + widget/gimpspinscale.c widget/imageicon.cpp widget/imagetoggler.cpp widget/labelled.cpp @@ -103,20 +133,18 @@ set(ui_SRC widget/registry.cpp widget/rendering-options.cpp widget/rotateable.cpp - widget/ruler.cpp widget/scalar-unit.cpp widget/scalar.cpp widget/selected-style.cpp + widget/spin-scale.cpp widget/spin-slider.cpp widget/spinbutton.cpp widget/style-subject.cpp widget/style-swatch.cpp - widget/svg-canvas.cpp widget/text.cpp widget/tolerance-slider.cpp - widget/toolbox.cpp widget/unit-menu.cpp - widget/zoom-status.cpp + widget/unit-tracker.cpp view/view.cpp view/view-widget.cpp @@ -126,6 +154,7 @@ set(ui_SRC # Headers clipboard.h control-manager.h + control-types.h icon-names.h previewable.h previewfillable.h @@ -158,6 +187,7 @@ set(ui_SRC dialog/filter-effects-dialog.h dialog/find.h dialog/floating-behavior.h + dialog/font-substitution.h dialog/glyphs.h dialog/guides.h dialog/grid-arrange-tab.h @@ -170,17 +200,22 @@ set(ui_SRC dialog/livepatheffect-editor.h dialog/memory.h dialog/messages.h + dialog/new-from-template.h dialog/object-attributes.h dialog/object-properties.h dialog/ocaldialogs.h dialog/panel-dialog.h dialog/polar-arrange-tab.h + dialog/pixelartdialog.h dialog/print-colors-preview-dialog.h dialog/print.h - dialog/scriptdialog.h + dialog/spellcheck.h dialog/svg-fonts-dialog.h dialog/swatches.h + dialog/symbols.h + dialog/template-load-tab.h + dialog/template-widget.h dialog/text-edit.h dialog/tile.h dialog/tracedialog.h @@ -196,7 +231,6 @@ set(ui_SRC tool/manipulator.h tool/modifier-tracker.h tool/multi-path-manipulator.h - tool/node-tool.h tool/node-types.h tool/node.h tool/path-manipulator.h @@ -205,9 +239,31 @@ set(ui_SRC tool/shape-record.h tool/transform-handle-set.h - view/edit-widget-interface.h - view/view-widget.h - view/view.h + tools/arc-tool.h + tools/box3d-tool.h + tools/calligraphic-tool.h + tools/connector-tool.h + tools/dropper-tool.h + tools/dynamic-base.h + tools/eraser-tool.h + tools/flood-tool.h + tools/freehand-base.h + tools/gradient-tool.h + tools/lpe-tool.h + tools/measure-tool.h + tools/mesh-tool.h + tools/node-tool.h + tools/pencil-tool.h + tools/pen-tool.h + tools/rect-tool.h + tools/select-tool.h + tools/spiral-tool.h + tools/spray-tool.h + tools/star-tool.h + tools/text-tool.h + tools/tool-base.h + tools/tweak-tool.h + tools/zoom-tool.h widget/anchor-selector.h widget/attr-widget.h @@ -219,10 +275,10 @@ set(ui_SRC widget/dock.h widget/entity-entry.h widget/entry.h - widget/frame.h widget/filter-effect-chooser.h - widget/handlebox.h - widget/icon-widget.h + widget/frame.h + widget/gimpspinscale.h + widget/gimpcolorwheel.h widget/imageicon.h widget/imagetoggler.h widget/labelled.h @@ -240,20 +296,22 @@ set(ui_SRC widget/registry.h widget/rendering-options.h widget/rotateable.h - widget/ruler.h widget/scalar-unit.h widget/scalar.h widget/selected-style.h + widget/spin-scale.h widget/spin-slider.h widget/spinbutton.h widget/style-subject.h widget/style-swatch.h - widget/svg-canvas.h widget/text.h widget/tolerance-slider.h - widget/toolbox.h widget/unit-menu.h - widget/zoom-status.h + widget/unit-tracker.h + + view/edit-widget-interface.h + view/view-widget.h + view/view.h ) if(WIN32) diff --git a/src/ui/Makefile_insert b/src/ui/Makefile_insert index 59b290dc4..4081f86f8 100644 --- a/src/ui/Makefile_insert +++ b/src/ui/Makefile_insert @@ -5,6 +5,7 @@ ink_common_sources += \ ui/clipboard.h \ ui/control-manager.cpp \ ui/control-manager.h \ + ui/control-types.h \ ui/icon-names.h \ ui/previewable.h \ ui/previewfillable.h \ diff --git a/src/ui/cache/svg_preview_cache.cpp b/src/ui/cache/svg_preview_cache.cpp index f8a806a13..f1d6304cb 100644 --- a/src/ui/cache/svg_preview_cache.cpp +++ b/src/ui/cache/svg_preview_cache.cpp @@ -19,7 +19,6 @@ # include "config.h" #endif -#include <glib.h> #include <gtk/gtk.h> #include <2geom/transforms.h> #include "sp-namedview.h" @@ -34,7 +33,7 @@ #include "ui/cache/svg_preview_cache.h" -GdkPixbuf* render_pixbuf(Inkscape::Drawing &drawing, double scale_factor, const Geom::Rect& dbox, unsigned psize) +GdkPixbuf* render_pixbuf(Inkscape::Drawing &drawing, double scale_factor, Geom::Rect const &dbox, unsigned psize) { Geom::Affine t(Geom::Scale(scale_factor, scale_factor)); drawing.root()->setTransform(Geom::Scale(scale_factor)); @@ -57,18 +56,12 @@ GdkPixbuf* render_pixbuf(Inkscape::Drawing &drawing, double scale_factor, const /* Render */ cairo_surface_t *s = cairo_image_surface_create( CAIRO_FORMAT_ARGB32, psize, psize); - Inkscape::DrawingContext ct(s, area.min()); + Inkscape::DrawingContext dc(s, area.min()); - drawing.render(ct, area, Inkscape::DrawingItem::RENDER_BYPASS_CACHE); + drawing.render(dc, area, Inkscape::DrawingItem::RENDER_BYPASS_CACHE); cairo_surface_flush(s); - GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(cairo_image_surface_get_data(s), - GDK_COLORSPACE_RGB, - TRUE, - 8, psize, psize, cairo_image_surface_get_stride(s), - ink_cairo_pixbuf_cleanup, s); - convert_pixbuf_argb32_to_normal(pixbuf); - + GdkPixbuf* pixbuf = ink_pixbuf_create_from_cairo_surface(s); return pixbuf; } @@ -82,6 +75,12 @@ SvgPreview::SvgPreview() SvgPreview::~SvgPreview() { + for (std::map<Glib::ustring, GdkPixbuf *>::iterator i = _pixmap_cache.begin(); + i != _pixmap_cache.end(); ++i) + { + g_object_unref(i->second); + i->second = NULL; + } } Glib::ustring SvgPreview::cache_key(gchar const *uri, gchar const *name, unsigned psize) const { @@ -103,6 +102,7 @@ GdkPixbuf* SvgPreview::get_preview_from_cache(const Glib::ustring& key) { } void SvgPreview::set_preview_in_cache(const Glib::ustring& key, GdkPixbuf* px) { + g_object_ref(px); _pixmap_cache[key] = px; } @@ -121,6 +121,16 @@ GdkPixbuf* SvgPreview::get_preview(const gchar* uri, const gchar* id, Inkscape:: return px; } +void SvgPreview::remove_preview_from_cache(const Glib::ustring& key) { + std::map<Glib::ustring, GdkPixbuf *>::iterator found = _pixmap_cache.find(key); + if ( found != _pixmap_cache.end() ) { + g_object_unref(found->second); + found->second = NULL; + _pixmap_cache.erase(key); + } +} + + } } } diff --git a/src/ui/cache/svg_preview_cache.h b/src/ui/cache/svg_preview_cache.h index 11d26fe22..b04a82350 100644 --- a/src/ui/cache/svg_preview_cache.h +++ b/src/ui/cache/svg_preview_cache.h @@ -40,6 +40,7 @@ class SvgPreview { GdkPixbuf* get_preview_from_cache(const Glib::ustring& key); void set_preview_in_cache(const Glib::ustring& key, GdkPixbuf* px); GdkPixbuf* get_preview(const gchar* uri, const gchar* id, Inkscape::DrawingItem *root, double scale_factor, unsigned int psize); + void remove_preview_from_cache(const Glib::ustring& key); }; }; // namespace Cache diff --git a/src/ui/clipboard.cpp b/src/ui/clipboard.cpp index 8f0652a78..8e2502545 100644 --- a/src/ui/clipboard.cpp +++ b/src/ui/clipboard.cpp @@ -7,9 +7,11 @@ * Jon A. Cruz <jon@joncruz.org> * Incorporates some code from selection-chemistry.cpp, see that file for more credits. * Abhishek Sharma + * Tavmjong Bah * * Copyright (C) 2008 authors * Copyright (C) 2010 Jon A. Cruz + * Copyright (C) 2012 Tavmjong Bah (Symbol additions) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -19,6 +21,7 @@ * See the file COPYING for details. */ +#include <gtkmm/clipboard.h> #include "ui/clipboard.h" // TODO: reduce header bloat if possible @@ -26,7 +29,6 @@ #include "file.h" // for file_import, used in _pasteImage #include <list> #include <algorithm> -#include <gtkmm/clipboard.h> #include <glibmm/ustring.h> #include <glibmm/i18n.h> #include <glib/gstdio.h> // for g_file_set_contents etc., used in _onGet and paste @@ -42,7 +44,7 @@ #include "selection.h" #include "message-stack.h" #include "context-fns.h" -#include "dropper-context.h" // used in copy() +#include "ui/tools/dropper-tool.h" // used in copy() #include "style.h" #include "extension/db.h" // extension database #include "extension/input.h" @@ -59,23 +61,24 @@ #include "sp-shape.h" #include "sp-gradient.h" #include "sp-gradient-reference.h" -#include "sp-gradient-fns.h" -#include "sp-linear-gradient-fns.h" -#include "sp-radial-gradient-fns.h" +#include "sp-linear-gradient.h" +#include "sp-radial-gradient.h" #include "sp-clippath.h" #include "sp-mask.h" #include "sp-textpath.h" #include "sp-rect.h" +#include "sp-use.h" +#include "sp-symbol.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 copy -#include "text-context.h" +#include "ui/tools/text-tool.h" #include "text-editing.h" #include "tools-switch.h" #include "path-chemistry.h" -#include "unit-constants.h" +#include "util/units.h" #include "helper/png-write.h" #include "svg/svg-color.h" #include "sp-namedview.h" @@ -90,12 +93,6 @@ #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 { @@ -109,6 +106,7 @@ class ClipboardManagerImpl : public ClipboardManager { public: virtual void copy(SPDesktop *desktop); virtual void copyPathParameter(Inkscape::LivePathEffect::PathParam *); + virtual void copySymbol(Inkscape::XML::Node* symbol, gchar const* style); virtual bool paste(SPDesktop *desktop, bool in_place); virtual bool pasteStyle(SPDesktop *desktop); virtual bool pasteSize(SPDesktop *desktop, bool separately, bool apply_x, bool apply_y); @@ -174,13 +172,18 @@ ClipboardManagerImpl::ClipboardManagerImpl() _text_style(NULL), _clipboard( Gtk::Clipboard::get() ) { + // 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 ? + // push supported clipboard targets, in order of preference _preferred_targets.push_back("image/x-inkscape-svg"); _preferred_targets.push_back("image/svg+xml"); _preferred_targets.push_back("image/svg+xml-compressed"); -#ifdef WIN32 - _preferred_targets.push_back(CLIPBOARD_WIN32_EMF_MIME); -#endif + _preferred_targets.push_back("image/x-emf"); + _preferred_targets.push_back("CF_ENHMETAFILE"); + _preferred_targets.push_back("WCF_ENHMETAFILE"); // seen on Wine _preferred_targets.push_back("application/pdf"); _preferred_targets.push_back("image/x-adobe-illustrator"); } @@ -234,7 +237,8 @@ void ClipboardManagerImpl::copy(SPDesktop *desktop) // 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)); + //_setClipboardColor(sp_dropper_context_get_color(desktop->event_context)); + _setClipboardColor(SP_DROPPER_CONTEXT(desktop->event_context)->get_color()); _discardInternalClipboard(); return; } @@ -243,13 +247,13 @@ void ClipboardManagerImpl::copy(SPDesktop *desktop) // 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); + Glib::ustring selected_text = Inkscape::UI::Tools::sp_text_get_selected_text(desktop->event_context); _clipboard->set_text(selected_text); if (_text_style) { sp_repr_css_attr_unref(_text_style); _text_style = NULL; } - _text_style = sp_text_get_style_at_cursor(desktop->event_context); + _text_style = Inkscape::UI::Tools::sp_text_get_style_at_cursor(desktop->event_context); return; } @@ -295,6 +299,47 @@ void ClipboardManagerImpl::copyPathParameter(Inkscape::LivePathEffect::PathParam } /** + * Copy a symbol from the symbol dialog. + * @param symbol The Inkscape::XML::Node for the symbol. + */ +void ClipboardManagerImpl::copySymbol(Inkscape::XML::Node* symbol, gchar const* style) +{ + //std::cout << "ClipboardManagerImpl::copySymbol" << std::endl; + if ( symbol == NULL ) { + return; + } + + _discardInternalClipboard(); + _createInternalClipboard(); + + // We add "_duplicate" to have a well defined symbol name that + // bypasses the "prevent_id_classes" routine. We'll get rid of it + // when we paste. + Inkscape::XML::Node *repr = symbol->duplicate(_doc); + Glib::ustring symbol_name = repr->attribute("id"); + + symbol_name += "_inkscape_duplicate"; + repr->setAttribute("id", symbol_name.c_str()); + _defs->appendChild(repr); + + Glib::ustring id("#"); + id += symbol->attribute("id"); + + Inkscape::XML::Node *use = _doc->createElement("svg:use"); + use->setAttribute("xlink:href", id.c_str() ); + // Set a default style in <use> rather than <symbol> so it can be changed. + use->setAttribute("style", style ); + _root->appendChild(use); + + // This min and max sets offsets, we don't have any so set to zero. + sp_repr_set_point(_clipnode, "min", Geom::Point(0,0)); + sp_repr_set_point(_clipnode, "max", Geom::Point(0,0)); + + fit_canvas_to_drawing(_clipboardSPDoc); + _setClipboardTargets(); +} + +/** * Paste from the system clipboard into the active desktop. * @param in_place Whether to put the contents where they were when copied. */ @@ -679,7 +724,7 @@ void ClipboardManagerImpl::_copyUsedDefs(SPItem *item) // 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)) { + if (lpeitem->hasPathEffect()) { for (PathEffectList::iterator it = lpeitem->path_effect_list->begin(); it != lpeitem->path_effect_list->end(); ++it) { LivePathEffectObject *lpeobj = (*it)->lpeobject; @@ -863,7 +908,7 @@ bool ClipboardManagerImpl::_pasteText(SPDesktop *desktop) // 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); + return Inkscape::UI::Tools::sp_text_paste_inline(desktop->event_context); } // try to parse the text as a color and, if successful, apply it as the current style @@ -893,7 +938,7 @@ void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effectsta { SPLPEItem *lpeitem = SP_LPE_ITEM(item); // for each effect in the stack, check if we need to fork it before adding it to the item - sp_lpe_item_fork_path_effects_if_necessary(lpeitem, 1); + lpeitem->forkPathEffectsIfNecessary(1); std::istringstream iss(effectstack); std::string href; @@ -904,7 +949,7 @@ void ClipboardManagerImpl::_applyPathEffect(SPItem *item, gchar const *effectsta return; } LivePathEffectObject *lpeobj = LIVEPATHEFFECT(obj); - sp_lpe_item_add_path_effect(lpeitem, lpeobj); + lpeitem->addPathEffect(lpeobj); } } } @@ -935,7 +980,7 @@ SPDocument *ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_targ Glib::ustring target = best_target; #ifdef WIN32 - if (best_target == CLIPBOARD_WIN32_EMF_TARGET) + if (best_target == "CF_ENHMETAFILE" || best_target == "WCF_ENHMETAFILE") { // Try to save clipboard data as en emf file (using win32 api) if (OpenClipboard(NULL)) { HGLOBAL hglb = GetClipboardData(CF_ENHMETAFILE); @@ -943,7 +988,7 @@ SPDocument *ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_targ HENHMETAFILE hemf = CopyEnhMetaFile((HENHMETAFILE) hglb, filename); if (hemf) { file_saved = true; - target = CLIPBOARD_WIN32_EMF_MIME; + target = "image/x-emf"; DeleteEnhMetaFile(hemf); } } @@ -974,6 +1019,10 @@ SPDocument *ClipboardManagerImpl::_retrieveClipboard(Glib::ustring required_targ if (target == "image/x-inkscape-svg") { target = "image/svg+xml"; } + // Use the EMF extension to import metafiles + if (target == "CF_ENHMETAFILE" || target == "WCF_ENHMETAFILE") { + target = "image/x-emf"; + } Inkscape::Extension::DB::InputList inlist; Inkscape::Extension::db.get_input_list(inlist); @@ -1032,14 +1081,14 @@ void ClipboardManagerImpl::_onGet(Gtk::SelectionData &sel, guint /*info*/) try { if (out == outlist.end() && target == "image/png") { - gdouble dpi = PX_PER_IN; + gdouble dpi = Inkscape::Util::Quantity::convert(1, "in", "px"); guint32 bgcolor = 0x00000000; Geom::Point origin (_clipboardSPDoc->getRoot()->x.computed, _clipboardSPDoc->getRoot()->y.computed); Geom::Rect area = Geom::Rect(origin, origin + _clipboardSPDoc->getDimensions()); - 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); + unsigned long int width = (unsigned long int) (Inkscape::Util::Quantity::convert(area.width(), "px", "in") * dpi + 0.5); + unsigned long int height = (unsigned long int) (Inkscape::Util::Quantity::convert(area.height(), "in", "px") * dpi + 0.5); // read from namedview Inkscape::XML::Node *nv = sp_repr_lookup_name (_clipboardSPDoc->rroot, "sodipodi:namedview"); @@ -1167,10 +1216,10 @@ Glib::ustring ClipboardManagerImpl::_getBestTarget() // clipboard target debugging snippet /* - g_debug("Begin clipboard targets"); + g_message("Begin clipboard targets"); for ( std::list<Glib::ustring>::iterator x = targets.begin() ; x != targets.end(); ++x ) - g_debug("Clipboard target: %s", (*x).data()); - g_debug("End clipboard targets\n"); + g_message("Clipboard target: %s", (*x).data()); + g_message("End clipboard targets\n"); //*/ for (std::list<Glib::ustring>::iterator i = _preferred_targets.begin() ; @@ -1193,7 +1242,7 @@ Glib::ustring ClipboardManagerImpl::_getBestTarget() CloseClipboard(); if (format == CF_ENHMETAFILE) { - return CLIPBOARD_WIN32_EMF_TARGET; + return "CF_ENHMETAFILE"; } if (format == CF_DIB || format == CF_BITMAP) { return CLIPBOARD_GDK_PIXBUF_TARGET; @@ -1201,7 +1250,7 @@ Glib::ustring ClipboardManagerImpl::_getBestTarget() } if (IsClipboardFormatAvailable(CF_ENHMETAFILE)) { - return CLIPBOARD_WIN32_EMF_TARGET; + return "CF_ENHMETAFILE"; } #endif if (_clipboard->wait_is_image_available()) { @@ -1222,7 +1271,13 @@ void ClipboardManagerImpl::_setClipboardTargets() { Inkscape::Extension::DB::OutputList outlist; Inkscape::Extension::db.get_output_list(outlist); + +#if WITH_GTKMM_3_0 + std::vector<Gtk::TargetEntry> target_list; +#else std::list<Gtk::TargetEntry> target_list; +#endif + bool plaintextSet = false; for (Inkscape::Extension::DB::OutputList::const_iterator out = outlist.begin() ; out != outlist.end() ; ++out) { if ( !(*out)->deactivated() ) { @@ -1259,7 +1314,7 @@ void ClipboardManagerImpl::_setClipboardTargets() if (OpenClipboard(NULL)) { if ( _clipboardSPDoc != NULL ) { - const Glib::ustring target = CLIPBOARD_WIN32_EMF_MIME; + const Glib::ustring target = "image/x-emf"; Inkscape::Extension::DB::OutputList outlist; Inkscape::Extension::db.get_output_list(outlist); diff --git a/src/ui/clipboard.h b/src/ui/clipboard.h index fb28bfc14..b565740c3 100644 --- a/src/ui/clipboard.h +++ b/src/ui/clipboard.h @@ -25,6 +25,7 @@ class SPDesktop; namespace Inkscape { class Selection; +namespace XML { class Node; } namespace LivePathEffect { class PathParam; } namespace UI { @@ -43,6 +44,7 @@ class ClipboardManager { public: virtual void copy(SPDesktop *desktop) = 0; virtual void copyPathParameter(Inkscape::LivePathEffect::PathParam *) = 0; + virtual void copySymbol(Inkscape::XML::Node* symbol, gchar const* style) = 0; virtual bool paste(SPDesktop *desktop, bool in_place = false) = 0; virtual bool pasteStyle(SPDesktop *desktop) = 0; virtual bool pasteSize(SPDesktop *desktop, bool separately, bool apply_x, bool apply_y) = 0; diff --git a/src/ui/control-manager.cpp b/src/ui/control-manager.cpp index ea9cf175d..5a3c5a496 100644 --- a/src/ui/control-manager.cpp +++ b/src/ui/control-manager.cpp @@ -12,31 +12,68 @@ #include "control-manager.h" #include <algorithm> -#include <glib.h> +#include <set> + #include <glib-object.h> #include "display/sodipodi-ctrl.h" // for SP_TYPE_CTRL +#include "display/sp-canvas-item.h" +#include "display/sp-ctrlline.h" +#include "display/sp-ctrlcurve.h" #include "display/sp-ctrlpoint.h" #include "preferences.h" +using Inkscape::ControlFlags; + namespace { std::map<Inkscape::ControlType, std::vector<int> > sizeTable; +// Note: The following operator overloads are local to this file at the moment to discourage flag manipulation elsewhere. +/* +ControlFlags operator |(ControlFlags lhs, ControlFlags rhs) +{ + return static_cast<ControlFlags>(static_cast<int>(lhs) | static_cast<int>(rhs)); +} +*/ + +ControlFlags operator &(ControlFlags lhs, ControlFlags rhs) +{ + return static_cast<ControlFlags>(static_cast<int>(lhs) & static_cast<int>(rhs)); +} + +ControlFlags operator ^(ControlFlags lhs, ControlFlags rhs) +{ + return static_cast<ControlFlags>(static_cast<int>(lhs) ^ static_cast<int>(rhs)); +} + +ControlFlags& operator ^=(ControlFlags &lhs, ControlFlags rhs) +{ + lhs = lhs ^ rhs; + return lhs; +} + } // namespace #define FILL_COLOR_NORMAL 0xffffff7f #define FILL_COLOR_MOUSEOVER 0xff0000ff +// Default color for line: +#define LINE_COLOR_PRIMARY 0x0000ff7f +#define LINE_COLOR_SECONDARY 0xff00007f +#define LINE_COLOR_TERTIARY 0xffff007f + namespace Inkscape { class ControlManagerImpl { public: - ControlManagerImpl(); + ControlManagerImpl(ControlManager &manager); ~ControlManagerImpl() {} + SPCanvasItem *createControl(SPCanvasGroup *parent, ControlType type); + void setControlSize(int size, bool force = false); void track(SPCanvasItem *anchor); @@ -45,6 +82,10 @@ public: void updateItem(SPCanvasItem *item); + bool setControlType(SPCanvasItem *item, ControlType type); + + void setSelected(SPCanvasItem *item, bool selected); + private: static void thingFinalized(gpointer data, GObject *wasObj); @@ -64,14 +105,20 @@ private: ControlManagerImpl &_mgr; }; + + ControlManager &_manager; sigc::signal<void> _sizeChangedSignal; PrefListener _prefHook; int _size; std::vector<SPCanvasItem *> _itemList; std::map<Inkscape::ControlType, std::vector<int> > _sizeTable; + std::map<Inkscape::ControlType, GType> _typeTable; + std::map<Inkscape::ControlType, SPCtrlShapeType> _ctrlToShape; + std::set<Inkscape::ControlType> _sizeChangers; }; -ControlManagerImpl::ControlManagerImpl() : +ControlManagerImpl::ControlManagerImpl(ControlManager &manager) : + _manager(manager), _sizeChangedSignal(), _prefHook(*this), _size(3), @@ -83,6 +130,39 @@ ControlManagerImpl::ControlManagerImpl() : _size = prefs->getIntLimited("/options/grabsize/value", 3, 1, 7); + _typeTable[CTRL_TYPE_UNKNOWN] = SP_TYPE_CTRL; + _typeTable[CTRL_TYPE_ADJ_HANDLE] = SP_TYPE_CTRL; + _typeTable[CTRL_TYPE_ANCHOR] = SP_TYPE_CTRL; + _typeTable[CTRL_TYPE_INVISIPOINT] = SP_TYPE_CTRL; + _typeTable[CTRL_TYPE_NODE_AUTO] = SP_TYPE_CTRL; + _typeTable[CTRL_TYPE_NODE_CUSP] = SP_TYPE_CTRL; + _typeTable[CTRL_TYPE_NODE_SMOOTH] = SP_TYPE_CTRL; + _typeTable[CTRL_TYPE_NODE_SYMETRICAL] = SP_TYPE_CTRL; + + _typeTable[CTRL_TYPE_ORIGIN] = SP_TYPE_CTRLPOINT; + + _typeTable[CTRL_TYPE_LINE] = SP_TYPE_CTRLLINE; + + + // ------- + _ctrlToShape[CTRL_TYPE_UNKNOWN] = SP_CTRL_SHAPE_DIAMOND; + _ctrlToShape[CTRL_TYPE_NODE_CUSP] = SP_CTRL_SHAPE_DIAMOND; + _ctrlToShape[CTRL_TYPE_NODE_SMOOTH] = SP_CTRL_SHAPE_SQUARE; + _ctrlToShape[CTRL_TYPE_NODE_AUTO] = SP_CTRL_SHAPE_CIRCLE; + _ctrlToShape[CTRL_TYPE_NODE_SYMETRICAL] = SP_CTRL_SHAPE_SQUARE; + + _ctrlToShape[CTRL_TYPE_ADJ_HANDLE] = SP_CTRL_SHAPE_CIRCLE; + _ctrlToShape[CTRL_TYPE_INVISIPOINT] = SP_CTRL_SHAPE_SQUARE; + + // ------- + + _sizeChangers.insert(CTRL_TYPE_NODE_AUTO); + _sizeChangers.insert(CTRL_TYPE_NODE_CUSP); + _sizeChangers.insert(CTRL_TYPE_NODE_SMOOTH); + _sizeChangers.insert(CTRL_TYPE_NODE_SYMETRICAL); + + // ------- + { int sizes[] = {8, 8, 8, 8, 8, 8, 8}; _sizeTable[CTRL_TYPE_UNKNOWN] = std::vector<int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); @@ -92,7 +172,7 @@ ControlManagerImpl::ControlManagerImpl() : _sizeTable[CTRL_TYPE_ANCHOR] = std::vector<int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); } { - int sizes[] = {2, 3, 4, 7, 8, 9, 10}; + int sizes[] = {2, 4, 7, 8, 9, 10, 12}; _sizeTable[CTRL_TYPE_ADJ_HANDLE] = std::vector<int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); } { @@ -106,6 +186,20 @@ ControlManagerImpl::ControlManagerImpl() : int sizes[] = {2, 3, 4, 7, 8, 9, 10}; _sizeTable[CTRL_TYPE_ORIGIN] = std::vector<int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); } + { + int sizes[] = {5, 7, 9, 10, 11, 12, 13}; + _sizeTable[CTRL_TYPE_NODE_AUTO] = std::vector<int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); + _sizeTable[CTRL_TYPE_NODE_CUSP] = std::vector<int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); + } + { + int sizes[] = {3, 5, 7, 8, 9, 10, 11}; + _sizeTable[CTRL_TYPE_NODE_SMOOTH] = std::vector<int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); + _sizeTable[CTRL_TYPE_NODE_SYMETRICAL] = std::vector<int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); + } + { + int sizes[] = {1, 1, 1, 1, 1, 1, 1}; + _sizeTable[CTRL_TYPE_INVISIPOINT] = std::vector<int>(sizes, sizes + (sizeof(sizes) / sizeof(sizes[0]))); + } } @@ -127,6 +221,63 @@ void ControlManagerImpl::setControlSize(int size, bool force) } } +SPCanvasItem *ControlManagerImpl::createControl(SPCanvasGroup *parent, ControlType type) +{ + SPCanvasItem *item = 0; + double targetSize = _sizeTable[type][_size - 1]; + switch (type) + { + case CTRL_TYPE_ADJ_HANDLE: + item = sp_canvas_item_new(parent, SP_TYPE_CTRL, + "shape", SP_CTRL_SHAPE_CIRCLE, + "size", targetSize, + "filled", 0, + "fill_color", 0xff00007f, + "stroked", 1, + "stroke_color", 0x0000ff7f, + NULL); + break; + case CTRL_TYPE_ANCHOR: + item = sp_canvas_item_new(parent, SP_TYPE_CTRL, + "size", targetSize, + "filled", 1, + "fill_color", FILL_COLOR_NORMAL, + "stroked", 1, + "stroke_color", 0x000000ff, + NULL); + break; + case CTRL_TYPE_NODE_AUTO: + case CTRL_TYPE_NODE_CUSP: + case CTRL_TYPE_NODE_SMOOTH: + case CTRL_TYPE_NODE_SYMETRICAL: + { + SPCtrlShapeType shape = _ctrlToShape[_ctrlToShape.count(type) ? type : CTRL_TYPE_UNKNOWN]; + item = sp_canvas_item_new(parent, SP_TYPE_CTRL, + "shape", shape, + "size", targetSize, + NULL); + break; + } + case CTRL_TYPE_ORIGIN: + item = sp_canvas_item_new(parent, SP_TYPE_CTRLPOINT, + NULL); + break; + case CTRL_TYPE_INVISIPOINT: + item = sp_canvas_item_new(parent, SP_TYPE_CTRL, + "shape", SP_CTRL_SHAPE_SQUARE, + "size", targetSize, + NULL); + break; + case CTRL_TYPE_UNKNOWN: + default: + item = sp_canvas_item_new(parent, SP_TYPE_CTRL, NULL); + } + if (item) { + item->ctrlType = type; + } + return item; +} + void ControlManagerImpl::track(SPCanvasItem *item) { g_object_weak_ref( G_OBJECT(item), ControlManagerImpl::thingFinalized, this ); @@ -145,15 +296,56 @@ void ControlManagerImpl::updateItem(SPCanvasItem *item) { if (item) { double target = _sizeTable[item->ctrlType][_size - 1]; + if ((item->ctrlType == CTRL_TYPE_ORIGIN) && SP_IS_CTRLPOINT(item)) { sp_ctrlpoint_set_radius(SP_CTRLPOINT(item), target / 2.0); } else { - sp_canvas_item_set(item, "size", target, NULL); + if (_sizeChangers.count(item->ctrlType) && _manager.isSelected(item)) { + target += 2; + } + g_object_set(item, "size", target, NULL); } sp_canvas_item_request_update(item); } } +bool ControlManagerImpl::setControlType(SPCanvasItem *item, ControlType type) +{ + bool accepted = false; + if (item && (item->ctrlType == type)) { + // nothing to do + accepted = true; + } else if (item) { + if (_ctrlToShape.count(type) && (_typeTable[type] == _typeTable[item->ctrlType])) { // compatible? + double targetSize = _sizeTable[type][_size - 1]; + if (_manager.isSelected(item) && _sizeChangers.count(item->ctrlType)) { + targetSize += 2.0; + } + SPCtrlShapeType targetShape = _ctrlToShape[type]; + g_object_set(item, "shape", targetShape, "size", targetSize, NULL); + item->ctrlType = type; + accepted = true; + } + } + + return accepted; +} + + +void ControlManagerImpl::setSelected(SPCanvasItem *item, bool selected) +{ + if (_manager.isSelected(item) != selected) { + item->ctrlFlags ^= CTRL_FLAG_SELECTED; // toggle, since we know it is different + + // TODO refresh colors + double targetSize = _sizeTable[item->ctrlType][_size - 1]; + if (selected && _sizeChangers.count(item->ctrlType)) { + targetSize += 2.0; + } + g_object_set(item, "size", targetSize, NULL); + } +} + void ControlManagerImpl::thingFinalized(gpointer data, GObject *wasObj) { if (data) { @@ -178,7 +370,7 @@ void ControlManagerImpl::thingFinalized(GObject *wasObj) // ---------------------------------------------------- ControlManager::ControlManager() : - _impl(new ControlManagerImpl()) + _impl(new ControlManagerImpl(*this)) { } @@ -196,39 +388,41 @@ ControlManager &ControlManager::getManager() SPCanvasItem *ControlManager::createControl(SPCanvasGroup *parent, ControlType type) { - SPCanvasItem *item = 0; - switch (type) - { - case CTRL_TYPE_ADJ_HANDLE: - item = sp_canvas_item_new(parent, SP_TYPE_CTRL, - "shape", SP_CTRL_SHAPE_CIRCLE, - "size", 4.0, - "filled", 0, - "fill_color", 0xff00007f, - "stroked", 1, - "stroke_color", 0x0000ff7f, - NULL); - break; - case CTRL_TYPE_ANCHOR: - item = sp_canvas_item_new(parent, SP_TYPE_CTRL, - "size", 6.0, - "filled", 1, - "fill_color", FILL_COLOR_NORMAL, - "stroked", 1, - "stroke_color", 0x000000ff, - NULL); - break; - case CTRL_TYPE_ORIGIN: - item = sp_canvas_item_new(parent, SP_TYPE_CTRLPOINT, NULL); - break; - case CTRL_TYPE_UNKNOWN: - default: - item = sp_canvas_item_new(parent, SP_TYPE_CTRL, NULL); + return _impl->createControl(parent, type); +} + +SPCtrlLine *ControlManager::createControlLine(SPCanvasGroup *parent, CtrlLineType type) +{ + SPCtrlLine *line = SP_CTRLLINE(sp_canvas_item_new(parent, SP_TYPE_CTRLLINE, NULL)); + if (line) { + line->ctrlType = CTRL_TYPE_LINE; + + line->setRgba32((type == CTLINE_PRIMARY) ? LINE_COLOR_PRIMARY : + (type == CTLINE_SECONDARY) ? LINE_COLOR_SECONDARY : LINE_COLOR_TERTIARY); } - if (item) { - item->ctrlType = type; + return line; +} + +SPCtrlLine *ControlManager::createControlLine(SPCanvasGroup *parent, Geom::Point const &p1, Geom::Point const &p2, CtrlLineType type) +{ + SPCtrlLine *line = createControlLine(parent, type); + if (line) { + line->setCoords(p1, p2); } - return item; + return line; +} + +SPCtrlCurve *ControlManager::createControlCurve(SPCanvasGroup *parent, Geom::Point const &p0, Geom::Point const &p1, Geom::Point const &p2, Geom::Point const &p3, CtrlLineType type) +{ + SPCtrlCurve *line = SP_CTRLCURVE(sp_canvas_item_new(parent, SP_TYPE_CTRLCURVE, NULL)); + if (line) { + line->ctrlType = CTRL_TYPE_LINE; + + line->setRgba32((type == CTLINE_PRIMARY) ? LINE_COLOR_PRIMARY : + (type == CTLINE_SECONDARY) ? LINE_COLOR_SECONDARY : LINE_COLOR_TERTIARY); + line->setCoords(p0, p1, p2, p3); + } + return line; } void ControlManager::track(SPCanvasItem *item) @@ -246,6 +440,47 @@ void ControlManager::updateItem(SPCanvasItem *item) return _impl->updateItem(item); } +bool ControlManager::setControlType(SPCanvasItem *item, ControlType type) +{ + return _impl->setControlType(item, type); +} + +bool ControlManager::isActive(SPCanvasItem *item) const +{ + return (item->ctrlFlags & CTRL_FLAG_ACTIVE) != 0; +} + +void ControlManager::setActive(SPCanvasItem *item, bool active) +{ + if (isActive(item) != active) { + item->ctrlFlags ^= CTRL_FLAG_ACTIVE; // toggle, since we know it is different + // TODO refresh size/colors + } +} + +bool ControlManager::isPrelight(SPCanvasItem *item) const +{ + return (item->ctrlFlags & CTRL_FLAG_PRELIGHT) != 0; +} + +void ControlManager::setPrelight(SPCanvasItem *item, bool prelight) +{ + if (isPrelight(item) != prelight) { + item->ctrlFlags ^= CTRL_FLAG_PRELIGHT; // toggle, since we know it is different + // TODO refresh size/colors + } +} + +bool ControlManager::isSelected(SPCanvasItem *item) const +{ + return (item->ctrlFlags & CTRL_FLAG_SELECTED) != 0; +} + +void ControlManager::setSelected(SPCanvasItem *item, bool selected) +{ + _impl->setSelected(item, selected); +} + } // namespace Inkscape /* diff --git a/src/ui/control-manager.h b/src/ui/control-manager.h index 1d3e474b3..05a53f6a0 100644 --- a/src/ui/control-manager.h +++ b/src/ui/control-manager.h @@ -14,18 +14,35 @@ #include <memory> #include <sigc++/sigc++.h> -#include "display/sp-canvas-item.h" +#include "ui/control-types.h" -struct SPCanvasItem; struct SPCanvasGroup; +struct SPCanvasItem; +struct SPCtrlLine; +struct SPCtrlCurve; + +namespace Geom +{ + +class Point; + +} // namespace Geom namespace Inkscape { +enum CtrlLineType { + CTLINE_PRIMARY, + CTLINE_SECONDARY, + CTLINE_TERTIARY, +}; + + class ControlManagerImpl; class ControlManager { public: + static ControlManager &getManager(); ~ControlManager(); @@ -34,10 +51,27 @@ public: SPCanvasItem *createControl(SPCanvasGroup *parent, ControlType type); + SPCtrlLine *createControlLine(SPCanvasGroup *parent, CtrlLineType type = CTLINE_PRIMARY); + + SPCtrlLine *createControlLine(SPCanvasGroup *parent, Geom::Point const &p1, Geom::Point const &p2, CtrlLineType type = CTLINE_PRIMARY); + + SPCtrlCurve *createControlCurve(SPCanvasGroup *parent, Geom::Point const &p0, Geom::Point const &p1, Geom::Point const &p2, Geom::Point const &p3, CtrlLineType type = CTLINE_PRIMARY); + void track(SPCanvasItem *item); void updateItem(SPCanvasItem *item); + bool setControlType(SPCanvasItem *item, ControlType type); + + bool isActive(SPCanvasItem *item) const; + void setActive(SPCanvasItem *item, bool active); + + bool isPrelight(SPCanvasItem *item) const; + void setPrelight(SPCanvasItem *item, bool prelight); + + bool isSelected(SPCanvasItem *item) const; + void setSelected(SPCanvasItem *item, bool selected); + private: ControlManager(); diff --git a/src/ui/control-types.h b/src/ui/control-types.h new file mode 100644 index 000000000..0bbf31144 --- /dev/null +++ b/src/ui/control-types.h @@ -0,0 +1,61 @@ +#ifndef SEEN_UI_CONTROL_TYPES_H +#define SEEN_UI_CONTROL_TYPES_H + +/* + * Authors: + * Jon A. Cruz <jon@joncruz.org> + * + * Copyright (C) 2012 authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +namespace Inkscape +{ + +// Rough initial set. Most likely needs refinement. +enum ControlType { + CTRL_TYPE_UNKNOWN, + CTRL_TYPE_ADJ_HANDLE, + CTRL_TYPE_ANCHOR, + CTRL_TYPE_POINT, + CTRL_TYPE_ROTATE, + CTRL_TYPE_SIZER, + CTRL_TYPE_SHAPER, + CTRL_TYPE_ORIGIN, + CTRL_TYPE_LINE, + CTRL_TYPE_NODE_AUTO, + CTRL_TYPE_NODE_CUSP, + CTRL_TYPE_NODE_SMOOTH, + CTRL_TYPE_NODE_SYMETRICAL, + CTRL_TYPE_INVISIPOINT +}; + +/** + * Flags for internal representation/tracking. + */ +enum ControlFlags { + CTRL_FLAG_NORMAL = 0, + CTRL_FLAG_ACTIVE = 1 << 0, + CTRL_FLAG_PRELIGHT = 1 << 1, + CTRL_FLAG_SELECTED = 1 << 2, +}; + +} // namespace Inkscape + +#endif // SEEN_UI_CONTROL_TYPES_H + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/dialog/Makefile_insert b/src/ui/dialog/Makefile_insert index 5a367248e..daa8aea22 100644 --- a/src/ui/dialog/Makefile_insert +++ b/src/ui/dialog/Makefile_insert @@ -45,6 +45,8 @@ ink_common_sources += \ ui/dialog/filter-effects-dialog.h \ ui/dialog/find.cpp \ ui/dialog/find.h \ + ui/dialog/font-substitution.cpp \ + ui/dialog/font-substitution.h \ ui/dialog/floating-behavior.cpp \ ui/dialog/floating-behavior.h \ ui/dialog/glyphs.cpp \ @@ -71,6 +73,8 @@ ink_common_sources += \ ui/dialog/memory.h \ ui/dialog/messages.cpp \ ui/dialog/messages.h \ + ui/dialog/new-from-template.cpp \ + ui/dialog/new-from-template.h \ ui/dialog/ocaldialogs.cpp \ ui/dialog/ocaldialogs.h \ ui/dialog/object-attributes.cpp \ @@ -84,20 +88,26 @@ ink_common_sources += \ ui/dialog/print.h \ ui/dialog/print-colors-preview-dialog.cpp \ ui/dialog/print-colors-preview-dialog.h \ - ui/dialog/scriptdialog.cpp \ - ui/dialog/scriptdialog.h \ ui/dialog/spellcheck.cpp \ ui/dialog/spellcheck.h \ ui/dialog/svg-fonts-dialog.cpp \ ui/dialog/svg-fonts-dialog.h \ ui/dialog/swatches.cpp \ ui/dialog/swatches.h \ + ui/dialog/symbols.cpp \ + ui/dialog/symbols.h \ + ui/dialog/template-load-tab.cpp \ + ui/dialog/template-load-tab.h \ + ui/dialog/template-widget.cpp \ + ui/dialog/template-widget.h \ ui/dialog/text-edit.cpp \ ui/dialog/text-edit.h \ ui/dialog/tile.cpp \ ui/dialog/tile.h \ ui/dialog/tracedialog.cpp \ ui/dialog/tracedialog.h \ + ui/dialog/pixelartdialog.cpp \ + ui/dialog/pixelartdialog.h \ ui/dialog/transformation.cpp \ ui/dialog/transformation.h \ ui/dialog/undo-history.cpp \ diff --git a/src/ui/dialog/aboutbox.cpp b/src/ui/dialog/aboutbox.cpp index 885846685..121773b6d 100644 --- a/src/ui/dialog/aboutbox.cpp +++ b/src/ui/dialog/aboutbox.cpp @@ -34,6 +34,7 @@ #include "svg-view-widget.h" #include "sp-text.h" #include "text-editing.h" +#include "util/units.h" #include "inkscape-version.h" @@ -97,7 +98,12 @@ AboutBox::AboutBox() : Gtk::Dialog(_("About Inkscape")) { tabs->append_page(*manage( make_scrolled_text(license_text)), _("_License"), true); +#if WITH_GTKMM_3_0 + get_content_area()->pack_end(*manage(tabs), true, true); +#else get_vbox()->pack_end(*manage(tabs), true, true); +#endif + tabs->show_all(); add_button(Gtk::Stock::CLOSE, Gtk::RESPONSE_CLOSE); @@ -108,17 +114,17 @@ AboutBox::AboutBox() : Gtk::Dialog(_("About Inkscape")) { g_strdup_printf("<small>Inkscape %s</small>", Inkscape::version_string); label->set_markup(label_text); -#if WITH_GTKMM_2_22 label->set_alignment(Gtk::ALIGN_END, Gtk::ALIGN_CENTER); -#else - label->set_alignment(Gtk::ALIGN_RIGHT, Gtk::ALIGN_CENTER); -#endif label->set_padding(5,0); g_free(label_text); label->set_selectable(true); label->show(); +#if WITH_GTKMM_3_0 + get_content_area()->pack_start(*manage(label), false, false); +#else get_vbox()->pack_start(*manage(label), false, false); +#endif Gtk::Requisition requisition; #if GTK_CHECK_VERSION(3,0,0) @@ -170,8 +176,8 @@ Gtk::Widget *build_splash_widget() { GtkWidget *v=sp_svg_view_widget_new(doc); - double width=doc->getWidth(); - double height=doc->getHeight(); + double width=doc->getWidth().value("px"); + double height=doc->getHeight().value("px"); doc->doUnref(); @@ -247,6 +253,7 @@ void AboutBox::initStrings() { "Arpad Biro\n" "Nicholas Bishop\n" "Joshua L. Blocher\n" +"Hanno Böck\n" "Henrik Bohre\n" "Boldewyn\n" "Daniel Borgmann\n" @@ -353,7 +360,7 @@ void AboutBox::initStrings() { "Nick\n" "Andreas Nilsson\n" "Mitsuru Oka\n" -"Marten Owens\n" +"Martin Owens\n" "Alvin Penner\n" "Jon Phillips\n" "Zdenko Podobny\n" @@ -390,6 +397,7 @@ void AboutBox::initStrings() { "Alex Valavanis\n" "Joakim Verona\n" "Lucas Vieites\n" +"Daniel Wagenaar\n" "Michael Wybrow\n" "Gellule Xg\n" "Daniel Yacob\n" @@ -440,7 +448,7 @@ void AboutBox::initStrings() { "Aleksandar Urošević <urke@users.sourceforge.net>, 2004-2006.\n" "Alessio Frusciante <algol@firenze.linux.it>, 2002, 2003.\n" "Alexander Shopov <ash@contact.bg>, 2006.\n" -"Alexandre Prokoudine <alexandre.prokoudine@gmail.com>, 2005, 2010-2011.\n" +"Alexandre Prokoudine <alexandre.prokoudine@gmail.com>, 2005, 2010-2013.\n" "Alexey Remizov <alexey@remizov.pp.ru>, 2004.\n" "Ali Ghanavatian <ghanvatian.ali@gmail.com>, 2010.\n" "Álvaro Lopes <alvieboy@alvie.com>, 2001, 2002.\n" @@ -461,14 +469,14 @@ void AboutBox::initStrings() { "Christian Meyer <chrisime@gnome.org>, 2000-2002.\n" "Christian Neumair <chris@gnome-de.org>, 2002, 2003.\n" "Christian Rose <menthos@menthos.com>, 2000-2003.\n" -"Cristian Secară <cristi@secarica.ro>, 2010.\n" +"Cristian Secară <cristi@secarica.ro>, 2010-2013.\n" "Christophe Merlet (RedFox) <redfox@redfoxcenter.org>, 2000-2002.\n" "Clytie Siddall <clytie@riverland.net.au>, 2004-2008.\n" "Colin Marquardt <colin@marquardt-home.de>, 2004-2006.\n" "Cédric Gemy <radar.map35@free.fr>, 2006.\n" "Daniel Díaz <yosoy@danieldiaz.org>, 2004.\n" "Didier Conchaudron <conchaudron@free.fr>, 2003.\n" -"Dimitris Spingos <dmtrs32@gmail.com>, 2011.\n" +"Dimitris Spingos <dmtrs32@gmail.com>, 2011-2013.\n" "Dorji Tashi <dorjee_doss@hotmail.com>, 2006.\n" "Duarte Loreto <happyguy_pt@hotmail.com> 2002, 2003 (Maintainer).\n" "Elias Norberg <elno0959 at student.su.se>, 2009.\n" @@ -486,6 +494,7 @@ void AboutBox::initStrings() { "Ilia Penev <lichopicho@gmail.com>, 2006.\n" "Ivan Masár <helix84@centrum.sk>, 2006-2010. \n" "Iñaki Larrañaga <dooteo@euskalgnu.org>, 2006.\n" +"Jānis Eisaks <jancs@dv.lv>, 2012, 2013.\n" "Jeffrey Steve Borbón Sanabria <jeff_kerokid@yahoo.com>, 2005.\n" "Jesper Öqvist <jesper@llbit.se>, 2010, 2011.\n" "Joaquim Perez i Noguer <noguer@gmail.com>, 2008-2009.\n" @@ -507,16 +516,16 @@ void AboutBox::initStrings() { "Kingsley Turner <kingsley@maddogsbreakfast.com.au>, 2006.\n" "Kitae <bluetux@gmail.com>, 2006.\n" "Kjartan Maraas <kmaraas@gnome.org>, 2000-2002.\n" -"Kris De Gussem <kris.DeGussem@gmail.com>, 2008-2011.\n" +"Kris De Gussem <Kris.DeGussem@gmail.com>, 2008-2013.\n" "Lauris Kaplinski <lauris@ariman.ee>, 2000.\n" "Leandro Regueiro <leandro.regueiro@gmail.com>, 2006-2008, 2010.\n" "Liu Xiaoqin <liuxqsmile@gmail.com>, 2008.\n" "Luca Bruno <luca.br@uno.it>, 2005.\n" -"Lucas Vieites Fariña<lucas@codexion.com>, 2003-2010.\n" +"Lucas Vieites Fariña<lucas@codexion.com>, 2003-2013.\n" "Mahesh subedi <submanesh@hotmail.com>, 2006.\n" "Martin Srebotnjak, <miles@filmsi.net>, 2005, 2010.\n" "Masatake YAMATO <jet@gyve.org>, 2002.\n" -"Masato Hashimoto <cabezon.hashimoto@gmail.com>, 2009-2011.\n" +"Masato Hashimoto <cabezon.hashimoto@gmail.com>, 2009-2012.\n" "Matiphas <matiphas _a_ free _point_ fr>, 2004-2006.\n" "Mattias Hultgren <mattias_hultgren@tele2.se>, 2005, 2006.\n" "Maxim Dziumanenko <mvd@mylinux.com.ua>, 2004.\n" @@ -527,7 +536,7 @@ void AboutBox::initStrings() { "Muhammad Bashir Al-Noimi <mhdbnoimi@gmail.com>, 2008.\n" "Myckel Habets <myckel@sdf.lonestar.org>, 2008.\n" "Nguyen Dinh Trung <nguyendinhtrung141@gmail.com>, 2007, 2008.\n" -"Nicolas Dufour <nicoduf@yahoo.fr>, 2008-2011.\n" +"Nicolas Dufour <nicoduf@yahoo.fr>, 2008-2013.\n" "Pawan Chitrakar <pchitrakar@gmail.com>, 2006.\n" "Przemysław Loesch <p_loesch@poczta.onet.pl>, 2005.\n" "Quico Llach <quico@softcatala.org>, 2000. Traducció sodipodi.\n" @@ -548,7 +557,7 @@ void AboutBox::initStrings() { "Thiago Pimentel <thiago.merces@gmail.com>, 2006.\n" "Toshifumi Sato <sato@centrosystem.com>, 2005.\n" "Jon South <striker@lunar-linux.org>, 2006. \n" -"Uwe Schöler <oss@oss-marketplace.com>, 2006-2011.\n" +"Uwe Schöler <oss@oss-marketplace.com>, 2006-2013.\n" "Valek Filippov <frob@df.ru>, 2000, 2003.\n" "Victor Dachev <vdachev@gmail.com>, 2006.\n" "Vincent van Adrighem <V.vanAdrighem@dirck.mine.nu>, 2003.\n" @@ -563,7 +572,7 @@ void AboutBox::initStrings() { "Yaron Shahrabani <sh.yaron@gmail.com>, 2009.\n" "Yukihiro Nakai <nakai@gnome.gr.jp>, 2000, 2003.\n" "Yuri Beznos <zhiz0id@gmail.com>, 2006.\n" -"Yuri Chornoivan <yurchor@ukr.net>, 2007-2011.\n" +"Yuri Chornoivan <yurchor@ukr.net>, 2007-2013.\n" "Yuri Syrota <rasta@renome.rovno.ua>, 2000.\n" "Yves Guillou <yvesguillou@users.sourceforge.net>, 2004.\n" "Zdenko Podobný <zdpo@mailbox.sk>, 2003, 2004." diff --git a/src/ui/dialog/aboutbox.h b/src/ui/dialog/aboutbox.h index 622b1324f..7b3308672 100644 --- a/src/ui/dialog/aboutbox.h +++ b/src/ui/dialog/aboutbox.h @@ -15,6 +15,14 @@ #ifndef INKSCAPE_UI_DIALOG_ABOUTBOX_H #define INKSCAPE_UI_DIALOG_ABOUTBOX_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/dialog.h> namespace Inkscape { diff --git a/src/ui/dialog/align-and-distribute.cpp b/src/ui/dialog/align-and-distribute.cpp index f8d63aade..6b4aeebb9 100644 --- a/src/ui/dialog/align-and-distribute.cpp +++ b/src/ui/dialog/align-and-distribute.cpp @@ -40,13 +40,14 @@ #include "text-editing.h" #include "tools-switch.h" #include "ui/icon-names.h" -#include "ui/tool/node-tool.h" +#include "ui/tools/node-tool.h" #include "ui/tool/multi-path-manipulator.h" #include "util/glib-list-iterators.h" #include "verbs.h" #include "widgets/icon.h" #include "sp-root.h" #include "document-undo.h" +#include "desktop.h" #include <glibmm/i18n.h> @@ -57,227 +58,150 @@ namespace Dialog { /////////helper classes////////////////////////////////// -class Action { -public : - Action(const Glib::ustring &id, - const Glib::ustring &tiptext, - guint row, guint column, +Action::Action(const Glib::ustring &id, + const Glib::ustring &tiptext, + guint row, guint column, #if WITH_GTKMM_3_0 - Gtk::Grid &parent, + Gtk::Grid &parent, #else - Gtk::Table &parent, + Gtk::Table &parent, #endif - AlignAndDistribute &dialog): - _dialog(dialog), - _id(id), - _parent(parent) - { - Gtk::Widget* pIcon = Gtk::manage( sp_icon_get_icon( _id, Inkscape::ICON_SIZE_LARGE_TOOLBAR) ); - Gtk::Button * pButton = Gtk::manage(new Gtk::Button()); - pButton->set_relief(Gtk::RELIEF_NONE); - pIcon->show(); - pButton->add(*pIcon); - pButton->show(); - - pButton->signal_clicked() - .connect(sigc::mem_fun(*this, &Action::on_button_click)); - pButton->set_tooltip_text(tiptext); + AlignAndDistribute &dialog): + _dialog(dialog), + _id(id), + _parent(parent) +{ + Gtk::Widget* pIcon = Gtk::manage( sp_icon_get_icon( _id, Inkscape::ICON_SIZE_LARGE_TOOLBAR) ); + Gtk::Button * pButton = Gtk::manage(new Gtk::Button()); + pButton->set_relief(Gtk::RELIEF_NONE); + pIcon->show(); + pButton->add(*pIcon); + pButton->show(); + + pButton->signal_clicked() + .connect(sigc::mem_fun(*this, &Action::on_button_click)); + pButton->set_tooltip_text(tiptext); #if WITH_GTKMM_3_0 - parent.attach(*pButton, column, row, 1, 1); + parent.attach(*pButton, column, row, 1, 1); #else - parent.attach(*pButton, column, column+1, row, row+1, Gtk::FILL, Gtk::FILL); + parent.attach(*pButton, column, column+1, row, row+1, Gtk::FILL, Gtk::FILL); #endif - } - virtual ~Action(){} +} - AlignAndDistribute &_dialog; -private : - virtual void on_button_click(){} +void ActionAlign::do_action(SPDesktop *desktop, int index) +{ + Inkscape::Selection *selection = sp_desktop_selection(desktop); + if (!selection) return; - Glib::ustring _id; + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + bool sel_as_group = prefs->getBool("/dialogs/align/sel-as-groups"); -#if WITH_GTKMM_3_0 - Gtk::Grid &_parent; -#else - Gtk::Table &_parent; -#endif -}; + using Inkscape::Util::GSListConstIterator; + std::list<SPItem *> selected; + selected.insert<GSListConstIterator<SPItem *> >(selected.end(), selection->itemList(), NULL); + if (selected.empty()) return; + const Coeffs &a = _allCoeffs[index]; + SPItem *focus = NULL; + Geom::OptRect b = Geom::OptRect(); + Selection::CompareSize horiz = (a.mx0 != 0.0) || (a.mx1 != 0.0) + ? Selection::HORIZONTAL : Selection::VERTICAL; -class ActionAlign : public Action { -public : - struct Coeffs { - double mx0, mx1, my0, my1; - double sx0, sx1, sy0, sy1; + switch (AlignTarget(prefs->getInt("/dialogs/align/align-to", 6))) + { + case LAST: + focus = SP_ITEM(*selected.begin()); + break; + case FIRST: + focus = SP_ITEM(*--(selected.end())); + break; + case BIGGEST: + focus = selection->largestItem(horiz); + break; + case SMALLEST: + focus = selection->smallestItem(horiz); + break; + case PAGE: + b = sp_desktop_document(desktop)->preferredBounds(); + break; + case DRAWING: + b = sp_desktop_document(desktop)->getRoot()->desktopPreferredBounds(); + break; + case SELECTION: + b = selection->preferredBounds(); + break; + default: + g_assert_not_reached (); + break; }; - ActionAlign(const Glib::ustring &id, - const Glib::ustring &tiptext, - guint row, guint column, - AlignAndDistribute &dialog, - guint coeffIndex): - Action(id, tiptext, row, column, - dialog.align_table(), dialog), - _index(coeffIndex), - _dialog(dialog) - {} -private : + if(focus) + b = focus->desktopPreferredBounds(); + g_return_if_fail(b); - virtual void on_button_click() { - //Retreive selected objects - SPDesktop *desktop = _dialog.getDesktop(); - if (!desktop) return; + // Generate the move point from the selected bounding box + Geom::Point mp = Geom::Point(a.mx0 * b->min()[Geom::X] + a.mx1 * b->max()[Geom::X], + a.my0 * b->min()[Geom::Y] + a.my1 * b->max()[Geom::Y]); - Inkscape::Selection *selection = sp_desktop_selection(desktop); - if (!selection) return; + bool changed = false; + if (sel_as_group) + b = selection->preferredBounds(); - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - bool sel_as_group = prefs->getBool("/dialogs/align/sel-as-groups"); - int prefs_bbox = prefs->getBool("/tools/bounding_box"); - - using Inkscape::Util::GSListConstIterator; - std::list<SPItem *> selected; - selected.insert<GSListConstIterator<SPItem *> >(selected.end(), selection->itemList(), NULL); - if (selected.empty()) return; - - Geom::Point mp; //Anchor point - AlignAndDistribute::AlignTarget target = _dialog.getAlignTarget(); - const Coeffs &a= _allCoeffs[_index]; - switch (target) - { - case AlignAndDistribute::LAST: - case AlignAndDistribute::FIRST: - case AlignAndDistribute::BIGGEST: - case AlignAndDistribute::SMALLEST: - { - //Check 2 or more selected objects - std::list<SPItem *>::iterator second(selected.begin()); - ++second; - if (second == selected.end()) - return; - //Find the master (anchor on which the other objects are aligned) - std::list<SPItem *>::iterator master( - _dialog.find_master ( - selected, - (a.mx0 != 0.0) || - (a.mx1 != 0.0) ) - ); - //remove the master from the selection - SPItem * thing = *master; - // TODO: either uncomment or remove the following commented lines, depending on which - // behaviour of moving objects makes most sense; also cf. discussion at - // https://bugs.launchpad.net/inkscape/+bug/255933 - /*if (!sel_as_group) { */ - selected.erase(master); - /*}*/ - //Compute the anchor point - Geom::OptRect b = !prefs_bbox ? thing->desktopVisualBounds() : thing->desktopGeometricBounds(); - if (b) { - mp = Geom::Point(a.mx0 * b->min()[Geom::X] + a.mx1 * b->max()[Geom::X], - a.my0 * b->min()[Geom::Y] + a.my1 * b->max()[Geom::Y]); - } else { - return; + //Move each item in the selected list separately + for (std::list<SPItem *>::iterator it(selected.begin()); + it != selected.end(); ++it) + { + sp_desktop_document (desktop)->ensureUpToDate(); + if (!sel_as_group) + b = (*it)->desktopPreferredBounds(); + if (b && (!focus || (*it) != focus)) { + Geom::Point const sp(a.sx0 * b->min()[Geom::X] + a.sx1 * b->max()[Geom::X], + a.sy0 * b->min()[Geom::Y] + a.sy1 * b->max()[Geom::Y]); + Geom::Point const mp_rel( mp - sp ); + if (LInfty(mp_rel) > 1e-9) { + sp_item_move_rel(*it, Geom::Translate(mp_rel)); + changed = true; } - break; } + } - case AlignAndDistribute::PAGE: - mp = Geom::Point(a.mx1 * sp_desktop_document(desktop)->getWidth(), - a.my1 * sp_desktop_document(desktop)->getHeight()); - break; + if (changed) { + DocumentUndo::done( sp_desktop_document(desktop) , SP_VERB_DIALOG_ALIGN_DISTRIBUTE, + _("Align")); + } +} - case AlignAndDistribute::DRAWING: - { - Geom::OptRect b = !prefs_bbox ? sp_desktop_document(desktop)->getRoot()->desktopVisualBounds() - : sp_desktop_document(desktop)->getRoot()->desktopGeometricBounds(); - if (b) { - mp = Geom::Point(a.mx0 * b->min()[Geom::X] + a.mx1 * b->max()[Geom::X], - a.my0 * b->min()[Geom::Y] + a.my1 * b->max()[Geom::Y]); - } else { - return; - } - break; - } - case AlignAndDistribute::SELECTION: - { - Geom::OptRect b = !prefs_bbox ? selection->visualBounds() : selection->geometricBounds(); - if (b) { - mp = Geom::Point(a.mx0 * b->min()[Geom::X] + a.mx1 * b->max()[Geom::X], - a.my0 * b->min()[Geom::Y] + a.my1 * b->max()[Geom::Y]); - } else { - return; - } - break; - } +ActionAlign::Coeffs const ActionAlign::_allCoeffs[11] = { + {1., 0., 0., 0., 0., 1., 0., 0., SP_VERB_ALIGN_HORIZONTAL_RIGHT_TO_ANCHOR}, + {1., 0., 0., 0., 1., 0., 0., 0., SP_VERB_ALIGN_HORIZONTAL_LEFT}, + {.5, .5, 0., 0., .5, .5, 0., 0., SP_VERB_ALIGN_HORIZONTAL_CENTER}, + {0., 1., 0., 0., 0., 1., 0., 0., SP_VERB_ALIGN_HORIZONTAL_RIGHT}, + {0., 1., 0., 0., 1., 0., 0., 0., SP_VERB_ALIGN_HORIZONTAL_LEFT_TO_ANCHOR}, + {0., 0., 0., 1., 0., 0., 1., 0., SP_VERB_ALIGN_VERTICAL_BOTTOM_TO_ANCHOR}, + {0., 0., 0., 1., 0., 0., 0., 1., SP_VERB_ALIGN_VERTICAL_TOP}, + {0., 0., .5, .5, 0., 0., .5, .5, SP_VERB_ALIGN_VERTICAL_CENTER}, + {0., 0., 1., 0., 0., 0., 1., 0., SP_VERB_ALIGN_VERTICAL_BOTTOM}, + {0., 0., 1., 0., 0., 0., 0., 1., SP_VERB_ALIGN_VERTICAL_TOP_TO_ANCHOR}, + {.5, .5, .5, .5, .5, .5, .5, .5, SP_VERB_ALIGN_VERTICAL_HORIZONTAL_CENTER} +}; - default: - g_assert_not_reached (); - break; - }; // end of switch - - // Top hack: temporarily set clone compensation to unmoved, so that we can align/distribute - // clones with their original (and the move of the original does not disturb the - // clones). The only problem with this is that if there are outside-of-selection clones of - // a selected original, they will be unmoved too, possibly contrary to user's - // expecation. However this is a minor point compared to making align/distribute always - // work as expected, and "unmoved" is the default option anyway. - int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED); - prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED); +void ActionAlign::do_verb_action(SPDesktop *desktop, int verb) +{ + do_action(desktop, verb_to_coeff(verb)); +} - bool changed = false; - Geom::OptRect b; - if (sel_as_group) - b = !prefs_bbox ? selection->visualBounds() : selection->geometricBounds(); +int ActionAlign::verb_to_coeff(int verb) { - //Move each item in the selected list separately - for (std::list<SPItem *>::iterator it(selected.begin()); - it != selected.end(); - it++) - { - sp_desktop_document (desktop)->ensureUpToDate(); - if (!sel_as_group) - b = !prefs_bbox ? (*it)->desktopVisualBounds() : (*it)->desktopGeometricBounds(); - if (b) { - Geom::Point const sp(a.sx0 * b->min()[Geom::X] + a.sx1 * b->max()[Geom::X], - a.sy0 * b->min()[Geom::Y] + a.sy1 * b->max()[Geom::Y]); - Geom::Point const mp_rel( mp - sp ); - if (LInfty(mp_rel) > 1e-9) { - sp_item_move_rel(*it, Geom::Translate(mp_rel)); - changed = true; - } - } + for(guint i = 0; i < G_N_ELEMENTS(_allCoeffs); i++) { + if (_allCoeffs[i].verb_id == verb) { + return i; } - - // restore compensation setting - prefs->setInt("/options/clonecompensation/value", saved_compensation); - - if (changed) { - DocumentUndo::done( sp_desktop_document(desktop) , SP_VERB_DIALOG_ALIGN_DISTRIBUTE, - _("Align")); - } - - } - guint _index; - AlignAndDistribute &_dialog; - static const Coeffs _allCoeffs[10]; - -}; -ActionAlign::Coeffs const ActionAlign::_allCoeffs[10] = { - {1., 0., 0., 0., 0., 1., 0., 0.}, - {1., 0., 0., 0., 1., 0., 0., 0.}, - {.5, .5, 0., 0., .5, .5, 0., 0.}, - {0., 1., 0., 0., 0., 1., 0., 0.}, - {0., 1., 0., 0., 1., 0., 0., 0.}, - {0., 0., 0., 1., 0., 0., 1., 0.}, - {0., 0., 0., 1., 0., 0., 0., 1.}, - {0., 0., .5, .5, 0., 0., .5, .5}, - {0., 0., 1., 0., 0., 0., 1., 0.}, - {0., 0., 1., 0., 0., 0., 0., 1.} -}; + return -1; +} BBoxSort::BBoxSort(SPItem *pItem, Geom::Rect const &bounds, Geom::Dim2 orientation, double kBegin, double kEnd) : item(pItem), @@ -373,7 +297,7 @@ private : float pos = sorted.front().bbox.min()[_orientation]; for ( std::vector<BBoxSort> ::iterator it (sorted.begin()); it < sorted.end(); - it ++ ) + ++it ) { if (!Geom::are_near(pos, it->bbox.min()[_orientation], 1e-6)) { Geom::Point t(0.0, 0.0); @@ -444,19 +368,25 @@ public : private : Geom::Dim2 _orientation; bool _distribute; - virtual void on_button_click() - { - if (!_dialog.getDesktop()) return; - SPEventContext *event_context = sp_desktop_event_context(_dialog.getDesktop()); - if (!INK_IS_NODE_TOOL (event_context)) return; - InkNodeTool *nt = INK_NODE_TOOL(event_context); + virtual void on_button_click() { + if (!_dialog.getDesktop()) { + return; + } + + Inkscape::UI::Tools::ToolBase *event_context = _dialog.getDesktop()->getEventContext(); - if (_distribute) + if (!INK_IS_NODE_TOOL(event_context)) { + return; + } + + Inkscape::UI::Tools::NodeTool *nt = INK_NODE_TOOL(event_context); + + if (_distribute) { nt->_multipath->distributeNodes(_orientation); - else + } else { nt->_multipath->alignNodes(_orientation); - + } } }; @@ -781,7 +711,7 @@ struct Baselines {} }; -bool operator< (const Baselines &a, const Baselines &b) +static bool operator< (const Baselines &a, const Baselines &b) { return (a._base[a._orientation] < b._base[b._orientation]); } @@ -899,14 +829,14 @@ private : -void on_tool_changed(Inkscape::Application */*inkscape*/, SPEventContext */*context*/, AlignAndDistribute *daad) +static void on_tool_changed(Inkscape::Application */*inkscape*/, Inkscape::UI::Tools::ToolBase */*context*/, AlignAndDistribute *daad) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if (desktop && sp_desktop_event_context(desktop)) + if (desktop && desktop->getEventContext()) daad->setMode(tools_active(desktop) == TOOLS_NODES); } -void on_selection_changed(Inkscape::Application */*inkscape*/, Inkscape::Selection */*selection*/, AlignAndDistribute *daad) +static void on_selection_changed(Inkscape::Application */*inkscape*/, Inkscape::Selection */*selection*/, AlignAndDistribute *daad) { daad->randomize_bbox = Geom::OptRect(); } @@ -1066,7 +996,6 @@ AlignAndDistribute::AlignAndDistribute() //Rest of the widgetry -#if WITH_GTKMM_2_24 _combo.append(_("Last selected")); _combo.append(_("First selected")); _combo.append(_("Biggest object")); @@ -1074,36 +1003,34 @@ AlignAndDistribute::AlignAndDistribute() _combo.append(_("Page")); _combo.append(_("Drawing")); _combo.append(_("Selection")); -#else - _combo.append_text(_("Last selected")); - _combo.append_text(_("First selected")); - _combo.append_text(_("Biggest object")); - _combo.append_text(_("Smallest object")); - _combo.append_text(_("Page")); - _combo.append_text(_("Drawing")); - _combo.append_text(_("Selection")); -#endif _combo.set_active(prefs->getInt("/dialogs/align/align-to", 6)); _combo.signal_changed().connect(sigc::mem_fun(*this, &AlignAndDistribute::on_ref_change)); - _anchorBox.pack_start(_anchorLabel); - _anchorBox.pack_start(_combo); + _anchorBox.pack_end(_combo, false, false); + _anchorBox.pack_end(_anchorLabel, false, false); _selgrpLabel.set_mnemonic_widget(_selgrp); - _selgrpBox.pack_start(_selgrpLabel); - _selgrpBox.pack_start(_selgrp); + _selgrpBox.pack_end(_selgrp, false, false); + _selgrpBox.pack_end(_selgrpLabel, false, false); _selgrp.set_active(prefs->getBool("/dialogs/align/sel-as-groups")); _selgrp.signal_toggled().connect(sigc::mem_fun(*this, &AlignAndDistribute::on_selgrp_toggled)); + // Right align the buttons + _alignTableBox.pack_end(_alignTable, false, false); + _distributeTableBox.pack_end(_distributeTable, false, false); + _rearrangeTableBox.pack_end(_rearrangeTable, false, false); + _removeOverlapTableBox.pack_end(_removeOverlapTable, false, false); + _nodesTableBox.pack_end(_nodesTable, false, false); + _alignBox.pack_start(_anchorBox); _alignBox.pack_start(_selgrpBox); - _alignBox.pack_start(_alignTable); + _alignBox.pack_start(_alignTableBox); _alignFrame.add(_alignBox); - _distributeFrame.add(_distributeTable); - _rearrangeFrame.add(_rearrangeTable); - _removeOverlapFrame.add(_removeOverlapTable); - _nodesFrame.add(_nodesTable); + _distributeFrame.add(_distributeTableBox); + _rearrangeFrame.add(_rearrangeTableBox); + _removeOverlapFrame.add(_removeOverlapTableBox); + _nodesFrame.add(_nodesTableBox); Gtk::Box *contents = _getContents(); contents->set_spacing(4); @@ -1123,6 +1050,9 @@ AlignAndDistribute::AlignAndDistribute() g_signal_connect (G_OBJECT (INKSCAPE), "change_selection", G_CALLBACK (on_selection_changed), this); randomize_bbox = Geom::OptRect(); + _desktopChangeConn = _deskTrack.connectDesktopChanged( sigc::mem_fun(*this, &AlignAndDistribute::setDesktop) ); + _deskTrack.connect(GTK_WIDGET(gobj())); + show_all_children(); on_tool_changed (NULL, NULL, this); // set current mode @@ -1133,11 +1063,23 @@ AlignAndDistribute::~AlignAndDistribute() sp_signal_disconnect_by_data (G_OBJECT (INKSCAPE), this); for (std::list<Action *>::iterator it = _actionList.begin(); - it != _actionList.end(); - ++it) + it != _actionList.end(); ++it) { delete *it; + } + + _desktopChangeConn.disconnect(); + _deskTrack.disconnect(); } +void AlignAndDistribute::setTargetDesktop(SPDesktop *desktop) +{ + if (_desktop != desktop) { + _desktop = desktop; + on_tool_changed (NULL, NULL, this); + } +} + + void AlignAndDistribute::on_ref_change(){ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setInt("/dialogs/align/align-to", _combo.get_active_row_number()); @@ -1158,21 +1100,12 @@ void AlignAndDistribute::on_selgrp_toggled(){ void AlignAndDistribute::setMode(bool nodeEdit) { //Act on widgets used in node mode -#if WITH_GTKMM_2_24 void ( Gtk::Widget::*mNode) () = nodeEdit ? &Gtk::Widget::show_all : &Gtk::Widget::hide; //Act on widgets used in selection mode void ( Gtk::Widget::*mSel) () = nodeEdit ? &Gtk::Widget::hide : &Gtk::Widget::show_all; -#else - void ( Gtk::Widget::*mNode) () = nodeEdit ? - &Gtk::Widget::show_all : &Gtk::Widget::hide_all; - - //Act on widgets used in selection mode - void ( Gtk::Widget::*mSel) () = nodeEdit ? - &Gtk::Widget::hide_all : &Gtk::Widget::show_all; -#endif ((_alignFrame).*(mSel))(); ((_distributeFrame).*(mSel))(); @@ -1288,70 +1221,6 @@ void AlignAndDistribute::addBaselineButton(const Glib::ustring &id, const Glib:: *this, table, orientation, distribute)); } - - - -std::list<SPItem *>::iterator AlignAndDistribute::find_master( std::list<SPItem *> &list, bool horizontal){ - std::list<SPItem *>::iterator master = list.end(); - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - int prefs_bbox = prefs->getBool("/tools/bounding_box"); - switch (getAlignTarget()) { - case LAST: - return list.begin(); - break; - - case FIRST: - return --(list.end()); - break; - - case BIGGEST: - { - gdouble max = -1e18; - for (std::list<SPItem *>::iterator it = list.begin(); it != list.end(); ++it) { - Geom::OptRect b = !prefs_bbox ? (*it)->desktopVisualBounds() : (*it)->desktopGeometricBounds(); - if (b) { - gdouble dim = (*b)[horizontal ? Geom::X : Geom::Y].extent(); - if (dim > max) { - max = dim; - master = it; - } - } - } - return master; - break; - } - - case SMALLEST: - { - gdouble max = 1e18; - for (std::list<SPItem *>::iterator it = list.begin(); it != list.end(); ++it) { - Geom::OptRect b = !prefs_bbox ? (*it)->desktopVisualBounds() : (*it)->desktopGeometricBounds(); - if (b) { - gdouble dim = (*b)[horizontal ? Geom::X : Geom::Y].extent(); - if (dim < max) { - max = dim; - master = it; - } - } - } - return master; - break; - } - - default: - g_assert_not_reached (); - break; - - } // end of switch statement - return master; -} - -AlignAndDistribute::AlignTarget AlignAndDistribute::getAlignTarget()const { - return AlignTarget(_combo.get_active_row_number()); -} - - - } // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/align-and-distribute.h b/src/ui/dialog/align-and-distribute.h index 59cc0dba4..dfd84535b 100644 --- a/src/ui/dialog/align-and-distribute.h +++ b/src/ui/dialog/align-and-distribute.h @@ -22,6 +22,7 @@ #include <gtkmm/comboboxtext.h> #include <gtkmm/label.h> #include "2geom/rect.h" +#include "ui/dialog/desktop-tracker.h" #if WITH_GTKMM_3_0 #include <gtkmm/checkbutton.h> @@ -46,10 +47,6 @@ public: static AlignAndDistribute &getInstance() { return *new AlignAndDistribute(); } - enum AlignTarget { LAST=0, FIRST, BIGGEST, SMALLEST, PAGE, DRAWING, SELECTION }; - - AlignTarget getAlignTarget() const; - #if WITH_GTKMM_3_0 Gtk::Grid &align_table(){return _alignTable;} Gtk::Grid &distribute_table(){return _distributeTable;} @@ -64,7 +61,6 @@ public: Gtk::Table &nodes_table(){return _nodesTable;} #endif - std::list<SPItem *>::iterator find_master(std::list <SPItem *> &list, bool horizontal); void setMode(bool nodeEdit); Geom::OptRect randomize_bbox; @@ -106,6 +102,7 @@ protected: void addBaselineButton(const Glib::ustring &id, const Glib::ustring tiptext, guint row, guint col, Gtk::Table &table, Geom::Dim2 orientation, bool distribute); #endif + void setTargetDesktop(SPDesktop *desktop); std::list<Action *> _actionList; UI::Widget::Frame _alignFrame, _distributeFrame, _rearrangeFrame, _removeOverlapFrame, _nodesFrame; @@ -117,11 +114,20 @@ protected: Gtk::HBox _anchorBox; Gtk::HBox _selgrpBox; Gtk::VBox _alignBox; + Gtk::HBox _alignTableBox; + Gtk::HBox _distributeTableBox; + Gtk::HBox _rearrangeTableBox; + Gtk::HBox _removeOverlapTableBox; + Gtk::HBox _nodesTableBox; Gtk::Label _anchorLabel; Gtk::Label _selgrpLabel; Gtk::CheckButton _selgrp; Gtk::ComboBoxText _combo; + SPDesktop *_desktop; + DesktopTracker _deskTrack; + sigc::connection _desktopChangeConn; + private: AlignAndDistribute(AlignAndDistribute const &d); AlignAndDistribute& operator=(AlignAndDistribute const &d); @@ -138,6 +144,83 @@ struct BBoxSort }; bool operator< (const BBoxSort &a, const BBoxSort &b); + +class Action { +public : + + Action(const Glib::ustring &id, + const Glib::ustring &tiptext, + guint row, guint column, + #if WITH_GTKMM_3_0 + Gtk::Grid &parent, + #else + Gtk::Table &parent, + #endif + AlignAndDistribute &dialog); + + virtual ~Action(){} + + AlignAndDistribute &_dialog; + +private : + virtual void on_button_click(){} + + Glib::ustring _id; + +#if WITH_GTKMM_3_0 + Gtk::Grid &_parent; +#else + Gtk::Table &_parent; +#endif +}; + + +class ActionAlign : public Action { +public : + struct Coeffs { + double mx0, mx1, my0, my1; + double sx0, sx1, sy0, sy1; + int verb_id; + }; + enum AlignTarget { LAST=0, FIRST, BIGGEST, SMALLEST, PAGE, DRAWING, SELECTION }; + ActionAlign(const Glib::ustring &id, + const Glib::ustring &tiptext, + guint row, guint column, + AlignAndDistribute &dialog, + guint coeffIndex): + Action(id, tiptext, row, column, + dialog.align_table(), dialog), + _index(coeffIndex), + _dialog(dialog) + {} + + /* + * Static function called to align from a keyboard shortcut + */ + static void do_verb_action(SPDesktop *desktop, int verb); + static int verb_to_coeff(int verb); + +private : + + + virtual void on_button_click() { + //Retreive selected objects + SPDesktop *desktop = _dialog.getDesktop(); + if (!desktop) return; + + do_action(desktop, _index); + } + + static void do_action(SPDesktop *desktop, int index); + + guint _index; + AlignAndDistribute &_dialog; + + static const Coeffs _allCoeffs[11]; + +}; + + } // namespace Dialog } // namespace UI } // namespace Inkscape diff --git a/src/ui/dialog/calligraphic-profile-rename.cpp b/src/ui/dialog/calligraphic-profile-rename.cpp index c6633df0b..9ae22db2d 100644 --- a/src/ui/dialog/calligraphic-profile-rename.cpp +++ b/src/ui/dialog/calligraphic-profile-rename.cpp @@ -13,14 +13,16 @@ * Released under GNU GPL. Read the file 'COPYING' for more information */ -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - #include "calligraphic-profile-rename.h" #include <glibmm/i18n.h> #include <gtkmm/stock.h> +#if WITH_GTKMM_3_0 +# include <gtkmm/grid.h> +#else +# include <gtkmm/table.h> +#endif + #include "desktop.h" namespace Inkscape { @@ -28,40 +30,68 @@ namespace UI { namespace Dialog { CalligraphicProfileRename::CalligraphicProfileRename() : +#if WITH_GTKMM_3_0 + _layout_table(Gtk::manage(new Gtk::Grid())), +#else + _layout_table(Gtk::manage(new Gtk::Table(1, 2))), +#endif _applied(false) { + set_title(_("Edit profile")); + +#if WITH_GTKMM_3_0 + Gtk::Box *mainVBox = get_content_area(); + _layout_table->set_column_spacing(4); + _layout_table->set_row_spacing(4); +#else Gtk::Box *mainVBox = get_vbox(); - _layout_table.set_spacings(4); - _layout_table.resize (1, 2); + _layout_table->set_spacings(4); +#endif _profile_name_entry.set_activates_default(true); _profile_name_label.set_label(_("Profile name:")); _profile_name_label.set_alignment(1.0, 0.5); - _layout_table.attach(_profile_name_label, +#if WITH_GTKMM_3_0 + _layout_table->attach(_profile_name_label, 0, 0, 1, 1); + + _profile_name_entry.set_hexpand(); + _layout_table->attach(_profile_name_entry, 1, 0, 1, 1); +#else + _layout_table->attach(_profile_name_label, 0, 1, 0, 1, Gtk::FILL, Gtk::FILL); - _layout_table.attach(_profile_name_entry, + _layout_table->attach(_profile_name_entry, 1, 2, 0, 1, Gtk::FILL | Gtk::EXPAND, Gtk::FILL); - mainVBox->pack_start(_layout_table, false, false, 4); +#endif + + mainVBox->pack_start(*_layout_table, false, false, 4); // Buttons _close_button.set_use_stock(true); _close_button.set_label(Gtk::Stock::CANCEL.id); _close_button.set_can_default(); + _delete_button.set_use_underline(true); + _delete_button.set_label(_("Delete")); + _delete_button.set_can_default(); + _delete_button.set_visible(false); + _apply_button.set_use_underline(true); _apply_button.set_label(_("Save")); _apply_button.set_can_default(); _close_button.signal_clicked() - .connect(sigc::mem_fun(*this, &CalligraphicProfileRename::_close)); + .connect(sigc::mem_fun(*this, &CalligraphicProfileRename::_close)); + _delete_button.signal_clicked() + .connect(sigc::mem_fun(*this, &CalligraphicProfileRename::_delete)); _apply_button.signal_clicked() - .connect(sigc::mem_fun(*this, &CalligraphicProfileRename::_apply)); + .connect(sigc::mem_fun(*this, &CalligraphicProfileRename::_apply)); signal_delete_event().connect( sigc::bind_return( sigc::hide(sigc::mem_fun(*this, &CalligraphicProfileRename::_close)), true ) ); add_action_widget(_close_button, Gtk::RESPONSE_CLOSE); + add_action_widget(_delete_button, Gtk::RESPONSE_DELETE_EVENT); add_action_widget(_apply_button, Gtk::RESPONSE_APPLY); _apply_button.grab_default(); @@ -73,6 +103,15 @@ void CalligraphicProfileRename::_apply() { _profile_name = _profile_name_entry.get_text(); _applied = true; + _deleted = false; + _close(); +} + +void CalligraphicProfileRename::_delete() +{ + _profile_name = _profile_name_entry.get_text(); + _applied = true; + _deleted = true; _close(); } @@ -81,11 +120,25 @@ void CalligraphicProfileRename::_close() this->Gtk::Dialog::hide(); } -void CalligraphicProfileRename::show(SPDesktop *desktop) +void CalligraphicProfileRename::show(SPDesktop *desktop, const Glib::ustring profile_name) { CalligraphicProfileRename &dial = instance(); dial._applied=false; + dial._deleted=false; dial.set_modal(true); + + dial._profile_name = profile_name; + dial._profile_name_entry.set_text(profile_name); + + if (profile_name.empty()) { + dial.set_title(_("Add profile")); + dial._delete_button.set_visible(false); + + } else { + dial.set_title(_("Edit profile")); + dial._delete_button.set_visible(true); + } + desktop->setWindowTransient (dial.gobj()); dial.property_destroy_with_parent() = true; // dial.Gtk::Dialog::show(); diff --git a/src/ui/dialog/calligraphic-profile-rename.h b/src/ui/dialog/calligraphic-profile-rename.h index f0eb0b491..3256338eb 100644 --- a/src/ui/dialog/calligraphic-profile-rename.h +++ b/src/ui/dialog/calligraphic-profile-rename.h @@ -11,10 +11,26 @@ #ifndef INKSCAPE_DIALOG_CALLIGRAPHIC_PROFILE_H #define INKSCAPE_DIALOG_CALLIGRAPHIC_PROFILE_H +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/dialog.h> #include <gtkmm/entry.h> #include <gtkmm/label.h> -#include <gtkmm/table.h> + +namespace Gtk { +#if WITH_GTKMM_3_0 +class Grid; +#else +class Table; +#endif +} + class SPDesktop; namespace Inkscape { @@ -29,10 +45,13 @@ public: return "CalligraphicProfileRename"; } - static void show(SPDesktop *desktop); + static void show(SPDesktop *desktop, const Glib::ustring profile_name); static bool applied() { return instance()._applied; } + static bool deleted() { + return instance()._deleted; + } static Glib::ustring getProfileName() { return instance()._profile_name; } @@ -40,14 +59,23 @@ public: protected: void _close(); void _apply(); + void _delete(); Gtk::Label _profile_name_label; Gtk::Entry _profile_name_entry; - Gtk::Table _layout_table; + +#if WITH_GTKMM_3_0 + Gtk::Grid* _layout_table; +#else + Gtk::Table* _layout_table; +#endif + Gtk::Button _close_button; + Gtk::Button _delete_button; Gtk::Button _apply_button; Glib::ustring _profile_name; bool _applied; + bool _deleted; private: static CalligraphicProfileRename &instance() { static CalligraphicProfileRename instance_; diff --git a/src/ui/dialog/clonetiler.cpp b/src/ui/dialog/clonetiler.cpp index 47ec03b30..fb131d8da 100644 --- a/src/ui/dialog/clonetiler.cpp +++ b/src/ui/dialog/clonetiler.cpp @@ -21,7 +21,6 @@ #include <climits> -#include <glib.h> #include <glibmm/i18n.h> #include <2geom/transforms.h> #include <gtkmm/adjustment.h> @@ -35,8 +34,8 @@ #include "document.h" #include "document-undo.h" #include "filter-chemistry.h" -#include "helper/unit-menu.h" -#include "helper/units.h" +#include "ui/widget/unit-menu.h" +#include "util/units.h" #include "helper/window.h" #include "inkscape.h" #include "interface.h" @@ -59,6 +58,7 @@ #include "sp-root.h" using Inkscape::DocumentUndo; +using Inkscape::Util::unit_table; namespace Inkscape { namespace UI { @@ -815,9 +815,15 @@ CloneTiler::CloneTiler (void) : GtkWidget *frame = gtk_frame_new (_("1. Pick from the drawing:")); gtk_box_pack_start (GTK_BOX (vvb), frame, FALSE, FALSE, 0); +#if GTK_CHECK_VERSION(3,0,0) + GtkWidget *table = gtk_grid_new(); + gtk_grid_set_row_spacing(GTK_GRID(table), 4); + gtk_grid_set_column_spacing(GTK_GRID(table), 6); +#else GtkWidget *table = gtk_table_new (3, 3, FALSE); gtk_table_set_row_spacings (GTK_TABLE (table), 4); gtk_table_set_col_spacings (GTK_TABLE (table), 6); +#endif gtk_container_add(GTK_CONTAINER(frame), table); @@ -893,9 +899,16 @@ CloneTiler::CloneTiler (void) : GtkWidget *frame = gtk_frame_new (_("2. Tweak the picked value:")); gtk_box_pack_start (GTK_BOX (vvb), frame, FALSE, FALSE, VB_MARGIN); +#if GTK_CHECK_VERSION(3,0,0) + GtkWidget *table = gtk_grid_new(); + gtk_grid_set_row_spacing(GTK_GRID(table), 4); + gtk_grid_set_column_spacing(GTK_GRID(table), 6); +#else GtkWidget *table = gtk_table_new (4, 2, FALSE); gtk_table_set_row_spacings (GTK_TABLE (table), 4); gtk_table_set_col_spacings (GTK_TABLE (table), 6); +#endif + gtk_container_add(GTK_CONTAINER(frame), table); { @@ -935,10 +948,15 @@ CloneTiler::CloneTiler (void) : GtkWidget *frame = gtk_frame_new (_("3. Apply the value to the clones':")); gtk_box_pack_start (GTK_BOX (vvb), frame, FALSE, FALSE, 0); - +#if GTK_CHECK_VERSION(3,0,0) + GtkWidget *table = gtk_grid_new(); + gtk_grid_set_row_spacing(GTK_GRID(table), 4); + gtk_grid_set_column_spacing(GTK_GRID(table), 6); +#else GtkWidget *table = gtk_table_new (2, 2, FALSE); gtk_table_set_row_spacings (GTK_TABLE (table), 4); gtk_table_set_col_spacings (GTK_TABLE (table), 6); +#endif gtk_container_add(GTK_CONTAINER(frame), table); { @@ -987,10 +1005,17 @@ CloneTiler::CloneTiler (void) : // Rows/columns, width/height { +#if GTK_CHECK_VERSION(3,0,0) + GtkWidget *table = gtk_grid_new(); + gtk_grid_set_row_spacing(GTK_GRID(table), 4); + gtk_grid_set_column_spacing(GTK_GRID(table), 6); +#else GtkWidget *table = gtk_table_new (2, 2, FALSE); - gtk_container_set_border_width (GTK_CONTAINER (table), VB_MARGIN); gtk_table_set_row_spacings (GTK_TABLE (table), 4); gtk_table_set_col_spacings (GTK_TABLE (table), 6); +#endif + + gtk_container_set_border_width (GTK_CONTAINER (table), VB_MARGIN); gtk_box_pack_start (GTK_BOX (mainbox), table, FALSE, FALSE, 0); { @@ -1068,35 +1093,36 @@ CloneTiler::CloneTiler (void) : g_object_set_data (G_OBJECT(dlg), "widthheight", (gpointer) hb); // unitmenu - GtkWidget *u = sp_unit_selector_new (SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE); - sp_unit_selector_set_unit (SP_UNIT_SELECTOR(u), sp_desktop_namedview(SP_ACTIVE_DESKTOP)->doc_units); + unit_menu = new Inkscape::UI::Widget::UnitMenu(); + unit_menu->setUnitType(Inkscape::Util::UNIT_TYPE_LINEAR); + unit_menu->setUnit(sp_desktop_namedview(SP_ACTIVE_DESKTOP)->doc_units->abbr); + unitChangedConn = unit_menu->signal_changed().connect(sigc::mem_fun(*this, &CloneTiler::clonetiler_unit_changed)); { // Width spinbutton #if WITH_GTKMM_3_0 - Glib::RefPtr<Gtk::Adjustment> a = Gtk::Adjustment::create(0.0, -1e6, 1e6, 1.0, 10.0, 0); + fill_width = Gtk::Adjustment::create(0.0, -1e6, 1e6, 1.0, 10.0, 0); #else - Gtk::Adjustment *a = new Gtk::Adjustment (0.0, -1e6, 1e6, 1.0, 10.0, 0); + fill_width = new Gtk::Adjustment (0.0, -1e6, 1e6, 1.0, 10.0, 0); #endif - sp_unit_selector_add_adjustment (SP_UNIT_SELECTOR (u), GTK_ADJUSTMENT (a->gobj())); double value = prefs->getDouble(prefs_path + "fillwidth", 50.0); - SPUnit const &unit = *sp_unit_selector_get_unit(SP_UNIT_SELECTOR(u)); - gdouble const units = sp_pixels_get_units (value, unit); - a->set_value (units); + Inkscape::Util::Unit const *unit = unit_menu->getUnit(); + gdouble const units = Inkscape::Util::Quantity::convert(value, "px", unit); + fill_width->set_value (units); #if WITH_GTKMM_3_0 - Inkscape::UI::Widget::SpinButton *e = new Inkscape::UI::Widget::SpinButton(a, 1.0, 2); + Inkscape::UI::Widget::SpinButton *e = new Inkscape::UI::Widget::SpinButton(fill_width, 1.0, 2); #else - Inkscape::UI::Widget::SpinButton *e = new Inkscape::UI::Widget::SpinButton (*a, 1.0, 2); + Inkscape::UI::Widget::SpinButton *e = new Inkscape::UI::Widget::SpinButton (*fill_width, 1.0, 2); #endif e->set_tooltip_text (_("Width of the rectangle to be filled")); e->set_width_chars (7); e->set_digits (4); gtk_box_pack_start (GTK_BOX (hb), GTK_WIDGET(e->gobj()), TRUE, TRUE, 0); // TODO: C++ification - g_signal_connect(G_OBJECT(a->gobj()), "value_changed", - G_CALLBACK(clonetiler_fill_width_changed), u); + g_signal_connect(G_OBJECT(fill_width->gobj()), "value_changed", + G_CALLBACK(clonetiler_fill_width_changed), unit_menu); } { GtkWidget *l = gtk_label_new (""); @@ -1108,32 +1134,31 @@ CloneTiler::CloneTiler (void) : { // Height spinbutton #if WITH_GTKMM_3_0 - Glib::RefPtr<Gtk::Adjustment> a = Gtk::Adjustment::create(0.0, -1e6, 1e6, 1.0, 10.0, 0); + fill_height = Gtk::Adjustment::create(0.0, -1e6, 1e6, 1.0, 10.0, 0); #else - Gtk::Adjustment *a = new Gtk::Adjustment (0.0, -1e6, 1e6, 1.0, 10.0, 0); + fill_height = new Gtk::Adjustment (0.0, -1e6, 1e6, 1.0, 10.0, 0); #endif - sp_unit_selector_add_adjustment (SP_UNIT_SELECTOR (u), GTK_ADJUSTMENT (a->gobj())); double value = prefs->getDouble(prefs_path + "fillheight", 50.0); - SPUnit const &unit = *sp_unit_selector_get_unit(SP_UNIT_SELECTOR(u)); - gdouble const units = sp_pixels_get_units (value, unit); - a->set_value (units); + Inkscape::Util::Unit const *unit = unit_menu->getUnit(); + gdouble const units = Inkscape::Util::Quantity::convert(value, "px", unit); + fill_height->set_value (units); #if WITH_GTKMM_3_0 - Inkscape::UI::Widget::SpinButton *e = new Inkscape::UI::Widget::SpinButton(a, 1.0, 2); + Inkscape::UI::Widget::SpinButton *e = new Inkscape::UI::Widget::SpinButton(fill_height, 1.0, 2); #else - Inkscape::UI::Widget::SpinButton *e = new Inkscape::UI::Widget::SpinButton (*a, 1.0, 2); + Inkscape::UI::Widget::SpinButton *e = new Inkscape::UI::Widget::SpinButton (*fill_height, 1.0, 2); #endif e->set_tooltip_text (_("Height of the rectangle to be filled")); e->set_width_chars (7); e->set_digits (4); gtk_box_pack_start (GTK_BOX (hb), GTK_WIDGET(e->gobj()), TRUE, TRUE, 0); // TODO: C++ification - g_signal_connect(G_OBJECT(a->gobj()), "value_changed", - G_CALLBACK(clonetiler_fill_height_changed), u); + g_signal_connect(G_OBJECT(fill_height->gobj()), "value_changed", + G_CALLBACK(clonetiler_fill_height_changed), unit_menu); } - gtk_box_pack_start (GTK_BOX (hb), u, TRUE, TRUE, 0); + gtk_box_pack_start (GTK_BOX (hb), (GtkWidget*) unit_menu->gobj(), TRUE, TRUE, 0); clonetiler_table_attach (table, hb, 0.0, 2, 2); } @@ -1326,8 +1351,8 @@ void CloneTiler::on_picker_color_changed(guint rgba) void CloneTiler::clonetiler_change_selection(Inkscape::Application * /*inkscape*/, Inkscape::Selection *selection, GtkWidget *dlg) { - GtkWidget *buttons = (GtkWidget *) g_object_get_data (G_OBJECT(dlg), "buttons_on_tiles"); - GtkWidget *status = (GtkWidget *) g_object_get_data (G_OBJECT(dlg), "status"); + GtkWidget *buttons = GTK_WIDGET(g_object_get_data (G_OBJECT(dlg), "buttons_on_tiles")); + GtkWidget *status = GTK_WIDGET(g_object_get_data (G_OBJECT(dlg), "status")); if (selection->isEmpty()) { gtk_widget_set_sensitive (buttons, FALSE); @@ -2038,9 +2063,9 @@ guint32 CloneTiler::clonetiler_trace_pick(Geom::Rect box) /* Find visible area */ cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, ibox.width(), ibox.height()); - Inkscape::DrawingContext ct(s, ibox.min()); + Inkscape::DrawingContext dc(s, ibox.min()); /* Render */ - trace_drawing->render(ct, ibox); + trace_drawing->render(dc, ibox); double R = 0, G = 0, B = 0, A = 0; ink_cairo_surface_average_color(s, R, G, B, A); cairo_surface_destroy(s); @@ -2204,7 +2229,7 @@ void CloneTiler::clonetiler_apply(GtkWidget */*widget*/, GtkWidget *dlg) desktop->setWaitingCursor(); // set statusbar text - GtkWidget *status = (GtkWidget *) g_object_get_data (G_OBJECT(dlg), "status"); + GtkWidget *status = GTK_WIDGET(g_object_get_data (G_OBJECT(dlg), "status")); gtk_label_set_markup (GTK_LABEL(status), _("<small>Creating tiled clones...</small>")); gtk_widget_queue_draw(GTK_WIDGET(status)); gdk_window_process_all_updates(); @@ -2807,15 +2832,29 @@ void CloneTiler::clonetiler_table_attach(GtkWidget *table, GtkWidget *widget, fl { GtkWidget *a = gtk_alignment_new (align, 0, 0, 0); gtk_container_add(GTK_CONTAINER(a), widget); - gtk_table_attach ( GTK_TABLE (table), a, col, col + 1, row, row + 1, (GtkAttachOptions)4, (GtkAttachOptions)0, 0, 0 ); + +#if GTK_CHECK_VERSION(3,0,0) + gtk_widget_set_halign(table, GTK_ALIGN_FILL); + gtk_widget_set_valign(table, GTK_ALIGN_CENTER); + gtk_grid_attach(GTK_GRID(table), a, col, row, 1, 1); +#else + gtk_table_attach ( GTK_TABLE (table), a, col, col + 1, row, row + 1, GTK_FILL, (GtkAttachOptions)0, 0, 0 ); +#endif } GtkWidget * CloneTiler::clonetiler_table_x_y_rand(int values) { +#if GTK_CHECK_VERSION(3,0,0) + GtkWidget *table = gtk_grid_new(); + gtk_grid_set_row_spacing(GTK_GRID(table), 6); + gtk_grid_set_column_spacing(GTK_GRID(table), 8); +#else GtkWidget *table = gtk_table_new (values + 2, 5, FALSE); - gtk_container_set_border_width (GTK_CONTAINER (table), VB_MARGIN); gtk_table_set_row_spacings (GTK_TABLE (table), 6); gtk_table_set_col_spacings (GTK_TABLE (table), 8); +#endif + + gtk_container_set_border_width (GTK_CONTAINER (table), VB_MARGIN); { #if GTK_CHECK_VERSION(3,0,0) @@ -2870,10 +2909,10 @@ void CloneTiler::clonetiler_pick_switched(GtkToggleButton */*tb*/, gpointer data } -void CloneTiler::clonetiler_switch_to_create(GtkToggleButton */*tb*/, GtkWidget *dlg) +void CloneTiler::clonetiler_switch_to_create(GtkToggleButton * /*tb*/, GtkWidget *dlg) { - GtkWidget *rowscols = (GtkWidget *) g_object_get_data (G_OBJECT(dlg), "rowscols"); - GtkWidget *widthheight = (GtkWidget *) g_object_get_data (G_OBJECT(dlg), "widthheight"); + GtkWidget *rowscols = GTK_WIDGET(g_object_get_data (G_OBJECT(dlg), "rowscols")); + GtkWidget *widthheight = GTK_WIDGET(g_object_get_data (G_OBJECT(dlg), "widthheight")); if (rowscols) { gtk_widget_set_sensitive (rowscols, TRUE); @@ -2887,10 +2926,10 @@ void CloneTiler::clonetiler_switch_to_create(GtkToggleButton */*tb*/, GtkWidget } -void CloneTiler::clonetiler_switch_to_fill(GtkToggleButton */*tb*/, GtkWidget *dlg) +void CloneTiler::clonetiler_switch_to_fill(GtkToggleButton * /*tb*/, GtkWidget *dlg) { - GtkWidget *rowscols = (GtkWidget *) g_object_get_data (G_OBJECT(dlg), "rowscols"); - GtkWidget *widthheight = (GtkWidget *) g_object_get_data (G_OBJECT(dlg), "widthheight"); + GtkWidget *rowscols = GTK_WIDGET(g_object_get_data (G_OBJECT(dlg), "rowscols")); + GtkWidget *widthheight = GTK_WIDGET(g_object_get_data (G_OBJECT(dlg), "widthheight")); if (rowscols) { gtk_widget_set_sensitive (rowscols, FALSE); @@ -2906,30 +2945,43 @@ void CloneTiler::clonetiler_switch_to_fill(GtkToggleButton */*tb*/, GtkWidget *d -void CloneTiler::clonetiler_fill_width_changed(GtkAdjustment *adj, GtkWidget *u) +void CloneTiler::clonetiler_fill_width_changed(GtkAdjustment *adj, Inkscape::UI::Widget::UnitMenu *u) { gdouble const raw_dist = gtk_adjustment_get_value (adj); - SPUnit const &unit = *sp_unit_selector_get_unit(SP_UNIT_SELECTOR(u)); - gdouble const pixels = sp_units_get_pixels (raw_dist, unit); + Inkscape::Util::Unit const *unit = u->getUnit(); + gdouble const pixels = Inkscape::Util::Quantity::convert(raw_dist, unit, "px"); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble(prefs_path + "fillwidth", pixels); } -void CloneTiler::clonetiler_fill_height_changed(GtkAdjustment *adj, GtkWidget *u) +void CloneTiler::clonetiler_fill_height_changed(GtkAdjustment *adj, Inkscape::UI::Widget::UnitMenu *u) { gdouble const raw_dist = gtk_adjustment_get_value (adj); - SPUnit const &unit = *sp_unit_selector_get_unit(SP_UNIT_SELECTOR(u)); - gdouble const pixels = sp_units_get_pixels (raw_dist, unit); + Inkscape::Util::Unit const *unit = u->getUnit(); + gdouble const pixels = Inkscape::Util::Quantity::convert(raw_dist, unit, "px"); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble(prefs_path + "fillheight", pixels); } +void CloneTiler::clonetiler_unit_changed() +{ + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + gdouble width_pixels = prefs->getDouble(prefs_path + "fillwidth"); + gdouble height_pixels = prefs->getDouble(prefs_path + "fillheight"); + + Inkscape::Util::Unit const *unit = unit_menu->getUnit(); + + gdouble width_value = Inkscape::Util::Quantity::convert(width_pixels, "px", unit); + gdouble height_value = Inkscape::Util::Quantity::convert(height_pixels, "px", unit); + gtk_adjustment_set_value(fill_width->gobj(), width_value); + gtk_adjustment_set_value(fill_height->gobj(), height_value); +} void CloneTiler::clonetiler_do_pick_toggled(GtkToggleButton *tb, GtkWidget *dlg) { - GtkWidget *vvb = (GtkWidget *) g_object_get_data (G_OBJECT(dlg), "dotrace"); + GtkWidget *vvb = GTK_WIDGET(g_object_get_data (G_OBJECT(dlg), "dotrace")); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setBool(prefs_path + "dotrace", gtk_toggle_button_get_active (tb)); @@ -2939,7 +2991,6 @@ void CloneTiler::clonetiler_do_pick_toggled(GtkToggleButton *tb, GtkWidget *dlg) } } - } } } diff --git a/src/ui/dialog/clonetiler.h b/src/ui/dialog/clonetiler.h index 2cad30e9e..e2a0240ee 100644 --- a/src/ui/dialog/clonetiler.h +++ b/src/ui/dialog/clonetiler.h @@ -11,7 +11,6 @@ #define __SP_CLONE_TILER_H__ #include "ui/widget/panel.h" -#include <glib.h> #include <gtk/gtk.h> #include "ui/dialog/desktop-tracker.h" @@ -20,6 +19,11 @@ namespace Inkscape { namespace UI { + +namespace Widget { + class UnitMenu; +} + namespace Dialog { class CloneTiler : public Widget::Panel { @@ -46,8 +50,9 @@ protected: static void clonetiler_do_pick_toggled(GtkToggleButton *tb, GtkWidget *dlg); static void clonetiler_pick_to(GtkToggleButton *tb, gpointer data); static void clonetiler_xy_changed(GtkAdjustment *adj, gpointer data); - static void clonetiler_fill_width_changed(GtkAdjustment *adj, GtkWidget *u); - static void clonetiler_fill_height_changed(GtkAdjustment *adj, GtkWidget *u); + static void clonetiler_fill_width_changed(GtkAdjustment *adj, Inkscape::UI::Widget::UnitMenu *u); + static void clonetiler_fill_height_changed(GtkAdjustment *adj, Inkscape::UI::Widget::UnitMenu *u); + void clonetiler_unit_changed(); static void clonetiler_switch_to_create(GtkToggleButton */*tb*/, GtkWidget *dlg); static void clonetiler_switch_to_fill(GtkToggleButton */*tb*/, GtkWidget *dlg); static void clonetiler_keep_bbox_toggled(GtkToggleButton *tb, gpointer /*data*/); @@ -113,12 +118,22 @@ private: DesktopTracker deskTrack; Inkscape::UI::Widget::ColorPicker *color_picker; GtkSizeGroup* table_row_labels; + Inkscape::UI::Widget::UnitMenu *unit_menu; + +#if WITH_GTKMM_3_0 + Glib::RefPtr<Gtk::Adjustment> fill_width; + Glib::RefPtr<Gtk::Adjustment> fill_height; +#else + Gtk::Adjustment *fill_width; + Gtk::Adjustment *fill_height; +#endif sigc::connection desktopChangeConn; sigc::connection selectChangedConn; sigc::connection subselChangedConn; sigc::connection selectModifiedConn; sigc::connection color_changed_connection; + sigc::connection unitChangedConn; /** * Can be invoked for setting the desktop. Currently not used. diff --git a/src/ui/dialog/color-item.cpp b/src/ui/dialog/color-item.cpp index 25f055f08..7940c28ae 100644 --- a/src/ui/dialog/color-item.cpp +++ b/src/ui/dialog/color-item.cpp @@ -11,9 +11,18 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + #include <errno.h> -#include <glibmm/i18n.h> + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/label.h> +#include <glibmm/i18n.h> #include <cairo.h> #include <gtk/gtk.h> @@ -35,6 +44,7 @@ #include "xml/node.h" #include "xml/repr.h" #include "verbs.h" +#include "widgets/gradient-vector.h" #include "color.h" // for SP_RGBA32_U_COMPOSE @@ -138,12 +148,12 @@ static gboolean handleLeaveNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*ev return FALSE; } -static void dieDieDie( GtkObject *obj, gpointer user_data ) +static void dieDieDie( GObject *obj, gpointer user_data ) { g_message("die die die %p %p", obj, user_data ); } -static bool getBlock( std::string& dst, guchar ch, std::string const str ) +static bool getBlock( std::string& dst, guchar ch, std::string const & str ) { bool good = false; std::string::size_type pos = str.find(ch); @@ -225,11 +235,7 @@ static void colorItemDragBegin( GtkWidget */*widget*/, GdkDragContext* dc, gpoin cairo_pattern_destroy(gradient); cairo_surface_flush(s); - pixbuf = gdk_pixbuf_new_from_data(cairo_image_surface_get_data(s), - GDK_COLORSPACE_RGB, TRUE, 8, - width, height, cairo_image_surface_get_stride(s), - ink_cairo_pixbuf_cleanup, s); - convert_pixbuf_argb32_to_normal(pixbuf); + pixbuf = ink_pixbuf_create_from_cairo_surface(s); } else { Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, width, height ); guint32 fillWith = (0xff000000 & (item->def.getR() << 24)) @@ -355,6 +361,23 @@ void ColorItem::setGradient(SPGradient *grad) _grad = grad; // TODO regen and push to listeners } + + setName( gr_prepare_label(_grad) ); +} + +void ColorItem::setName(const Glib::ustring name) +{ + //def.descr = name; + + for ( std::vector<Gtk::Widget*>::iterator it = _previews.begin(); it != _previews.end(); ++it ) { + Gtk::Widget* widget = *it; + if ( IS_EEK_PREVIEW(widget->gobj()) ) { + gtk_widget_set_tooltip_text(GTK_WIDGET(widget->gobj()), name.c_str()); + } + else if ( GTK_IS_LABEL(widget->gobj()) ) { + gtk_label_set_text(GTK_LABEL(widget->gobj()), name.c_str()); + } + } } void ColorItem::setPattern(cairo_pattern_t *pattern) @@ -366,6 +389,7 @@ void ColorItem::setPattern(cairo_pattern_t *pattern) cairo_pattern_destroy(_pattern); } _pattern = pattern; + _updatePreviews(); } @@ -533,11 +557,7 @@ void ColorItem::_regenPreview(EekPreview * preview) cairo_destroy(ct); cairo_surface_flush(s); - GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data( cairo_image_surface_get_data(s), - GDK_COLORSPACE_RGB, TRUE, 8, - w, h, cairo_image_surface_get_stride(s), - ink_cairo_pixbuf_cleanup, s); - convert_pixbuf_argb32_to_normal(pixbuf); + GdkPixbuf* pixbuf = ink_pixbuf_create_from_cairo_surface(s); eek_preview_set_pixbuf( preview, pixbuf ); } @@ -546,58 +566,29 @@ void ColorItem::_regenPreview(EekPreview * preview) | (_isLive ? PREVIEW_LINK_OTHER:0)) ); } -Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, ::PreviewSize size, guint ratio) +Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, ::PreviewSize size, guint ratio, guint border) { Gtk::Widget* widget = 0; if ( style == PREVIEW_STYLE_BLURB) { Gtk::Label *lbl = new Gtk::Label(def.descr); -#if WITH_GTKMM_2_22 lbl->set_alignment(Gtk::ALIGN_START, Gtk::ALIGN_CENTER); -#else - lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER); -#endif widget = lbl; } else { -// Glib::ustring blank(" "); -// if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) { -// blank = " "; -// } - GtkWidget* eekWidget = eek_preview_new(); EekPreview * preview = EEK_PREVIEW(eekWidget); Gtk::Widget* newBlot = Glib::wrap(eekWidget); - _regenPreview(preview); - eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::PreviewSize)size, ratio ); + eek_preview_set_details( preview, + (::ViewType)view, + (::PreviewSize)size, + ratio, + border ); def.addCallback( _colorDefChanged, this ); - - GValue val = {0, {{0}, {0}}}; - g_value_init( &val, G_TYPE_BOOLEAN ); - g_value_set_boolean( &val, FALSE ); - g_object_set_property( G_OBJECT(preview), "focus-on-click", &val ); - -/* - Gtk::Button *btn = new Gtk::Button(blank); - Gdk::Color color; - color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b); - btn->modify_bg(Gtk::STATE_NORMAL, color); - btn->modify_bg(Gtk::STATE_ACTIVE, color); - btn->modify_bg(Gtk::STATE_PRELIGHT, color); - btn->modify_bg(Gtk::STATE_SELECTED, color); - - Gtk::Widget* newBlot = btn; -*/ - + eek_preview_set_focus_on_click(preview, FALSE); newBlot->set_tooltip_text(def.descr); -/* - newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) ); - - sigc::signal<void> type_signal_something; -*/ - g_signal_connect( G_OBJECT(newBlot->gobj()), "clicked", G_CALLBACK(handleClick), @@ -659,26 +650,6 @@ Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, ::PreviewS G_CALLBACK(handleLeaveNotify), this); -// g_signal_connect( G_OBJECT(newBlot->gobj()), -// "drag-drop", -// G_CALLBACK(dragDropColorData), -// this); - - if ( def.isEditable() ) - { -// gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()), -// GTK_DEST_DEFAULT_ALL, -// destColorTargets, -// G_N_ELEMENTS(destColorTargets), -// GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) ); - - -// g_signal_connect( G_OBJECT(newBlot->gobj()), -// "drag-data-received", -// G_CALLBACK(_dropDataIn), -// this ); - } - g_signal_connect( G_OBJECT(newBlot->gobj()), "destroy", G_CALLBACK(dieDieDie), diff --git a/src/ui/dialog/color-item.h b/src/ui/dialog/color-item.h index e6f5c7b76..3a0b33193 100644 --- a/src/ui/dialog/color-item.h +++ b/src/ui/dialog/color-item.h @@ -53,12 +53,14 @@ public: virtual Gtk::Widget* getPreview(PreviewStyle style, ViewType view, ::PreviewSize size, - guint ratio); + guint ratio, + guint border); void buttonClicked(bool secondary = false); void setGradient(SPGradient *grad); SPGradient * getGradient() const { return _grad; } void setPattern(cairo_pattern_t *pattern); + void setName(const Glib::ustring name); void setState( bool fill, bool stroke ); bool isFill() { return _isFill; } diff --git a/src/ui/dialog/debug.cpp b/src/ui/dialog/debug.cpp index 7095d2611..9e2287f80 100644 --- a/src/ui/dialog/debug.cpp +++ b/src/ui/dialog/debug.cpp @@ -13,13 +13,17 @@ # include <config.h> #endif -#include <glibmm/i18n.h> +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> #include <gtkmm/dialog.h> #include <gtkmm/textview.h> #include <gtkmm/button.h> #include <gtkmm/menubar.h> #include <gtkmm/scrolledwindow.h> +#include <glibmm/i18n.h> #include "debug.h" @@ -69,16 +73,29 @@ DebugDialogImpl::DebugDialogImpl() set_title(_("Messages")); set_size_request(300, 400); +#if WITH_GTKMM_3_0 + Gtk::Box *mainVBox = get_content_area(); +#else Gtk::Box *mainVBox = get_vbox(); +#endif //## Add a menu for clear() - menuBar.items().push_back( Gtk::Menu_Helpers::MenuElem(_("_File"), fileMenu) ); - fileMenu.items().push_back( Gtk::Menu_Helpers::MenuElem(_("_Clear"), - sigc::mem_fun(*this, &DebugDialogImpl::clear) ) ); - fileMenu.items().push_back( Gtk::Menu_Helpers::MenuElem(_("Capture log messages"), - sigc::mem_fun(*this, &DebugDialogImpl::captureLogMessages) ) ); - fileMenu.items().push_back( Gtk::Menu_Helpers::MenuElem(_("Release log messages"), - sigc::mem_fun(*this, &DebugDialogImpl::releaseLogMessages) ) ); + Gtk::MenuItem* item = Gtk::manage(new Gtk::MenuItem(_("_File"), true)); + item->set_submenu(fileMenu); + menuBar.append(*item); + + item = Gtk::manage(new Gtk::MenuItem(_("_Clear"), true)); + item->signal_activate().connect(sigc::mem_fun(*this, &DebugDialogImpl::clear)); + fileMenu.append(*item); + + item = Gtk::manage(new Gtk::MenuItem(_("Capture log messages"))); + item->signal_activate().connect(sigc::mem_fun(*this, &DebugDialogImpl::captureLogMessages)); + fileMenu.append(*item); + + item = Gtk::manage(new Gtk::MenuItem(_("Release log messages"))); + item->signal_activate().connect(sigc::mem_fun(*this, &DebugDialogImpl::releaseLogMessages)); + fileMenu.append(*item); + mainVBox->pack_start(menuBar, Gtk::PACK_SHRINK); @@ -117,7 +134,7 @@ void DebugDialogImpl::show() { //call super() Gtk::Dialog::show(); - //sp_transientize((GtkWidget *)gobj()); //Make transient + //sp_transientize(GTK_WIDGET(gobj())); //Make transient raise(); Gtk::Dialog::present(); } @@ -162,10 +179,10 @@ void DebugDialog::showInstance() /*##### THIS IS THE IMPORTANT PART ##### */ -void dialogLoggingFunction(const gchar */*log_domain*/, - GLogLevelFlags /*log_level*/, - const gchar *messageText, - gpointer user_data) +static void dialogLoggingFunction(const gchar */*log_domain*/, + GLogLevelFlags /*log_level*/, + const gchar *messageText, + gpointer user_data) { DebugDialogImpl *dlg = static_cast<DebugDialogImpl *>(user_data); dlg->message(messageText); diff --git a/src/ui/dialog/desktop-tracker.h b/src/ui/dialog/desktop-tracker.h index 0c8af66bf..7da55cf2f 100644 --- a/src/ui/dialog/desktop-tracker.h +++ b/src/ui/dialog/desktop-tracker.h @@ -7,16 +7,15 @@ #ifndef SEEN_DIALOG_DESKTOP_TRACKER #define SEEN_DIALOG_DESKTOP_TRACKER -#include <stddef.h> +#include <cstddef> #include <sigc++/connection.h> -#include <glib.h> typedef struct _GtkWidget GtkWidget; class SPDesktop; namespace Inkscape { -class Application; +struct Application; namespace UI { namespace Dialog { diff --git a/src/ui/dialog/dialog-manager.cpp b/src/ui/dialog/dialog-manager.cpp index 528ddf5b3..32ceb397a 100644 --- a/src/ui/dialog/dialog-manager.cpp +++ b/src/ui/dialog/dialog-manager.cpp @@ -32,9 +32,10 @@ #include "ui/dialog/livepatheffect-editor.h" #include "ui/dialog/memory.h" #include "ui/dialog/messages.h" -#include "ui/dialog/scriptdialog.h" +#include "ui/dialog/symbols.h" #include "ui/dialog/tile.h" #include "ui/dialog/tracedialog.h" +#include "ui/dialog/pixelartdialog.h" #include "ui/dialog/transformation.h" #include "ui/dialog/undo-history.h" #include "ui/dialog/panel-dialog.h" @@ -52,10 +53,7 @@ #include "ui/dialog/export.h" #include "ui/dialog/xml-tree.h" #include "ui/dialog/clonetiler.h" - -#ifdef ENABLE_SVG_FONTS #include "ui/dialog/svg-fonts-dialog.h" -#endif // ENABLE_SVG_FONTS namespace Inkscape { namespace UI { @@ -116,13 +114,12 @@ DialogManager::DialogManager() { registerFactory("ObjectAttributes", &create<ObjectAttributes, FloatingBehavior>); registerFactory("ObjectProperties", &create<ObjectProperties, FloatingBehavior>); // registerFactory("PrintColorsPreviewDialog", &create<PrintColorsPreviewDialog, FloatingBehavior>); - registerFactory("Script", &create<ScriptDialog, FloatingBehavior>); -#ifdef ENABLE_SVG_FONTS registerFactory("SvgFontsDialog", &create<SvgFontsDialog, FloatingBehavior>); -#endif registerFactory("Swatches", &create<SwatchesPanel, FloatingBehavior>); registerFactory("TileDialog", &create<ArrangeDialog, FloatingBehavior>); + registerFactory("Symbols", &create<SymbolsDialog, FloatingBehavior>); registerFactory("Trace", &create<TraceDialog, FloatingBehavior>); + registerFactory("PixelArt", &create<PixelArtDialog, FloatingBehavior>); registerFactory("Transformation", &create<Transformation, FloatingBehavior>); registerFactory("UndoHistory", &create<UndoHistory, FloatingBehavior>); registerFactory("InputDevices", &create<InputDialog, FloatingBehavior>); @@ -151,13 +148,16 @@ DialogManager::DialogManager() { registerFactory("ObjectAttributes", &create<ObjectAttributes, DockBehavior>); registerFactory("ObjectProperties", &create<ObjectProperties, DockBehavior>); // registerFactory("PrintColorsPreviewDialog", &create<PrintColorsPreviewDialog, DockBehavior>); - registerFactory("Script", &create<ScriptDialog, DockBehavior>); -#ifdef ENABLE_SVG_FONTS registerFactory("SvgFontsDialog", &create<SvgFontsDialog, DockBehavior>); -#endif registerFactory("Swatches", &create<SwatchesPanel, DockBehavior>); +<<<<<<< TREE registerFactory("TileDialog", &create<ArrangeDialog, DockBehavior>); +======= + registerFactory("Symbols", &create<SymbolsDialog, DockBehavior>); + registerFactory("TileDialog", &create<TileDialog, DockBehavior>); +>>>>>>> MERGE-SOURCE registerFactory("Trace", &create<TraceDialog, DockBehavior>); + registerFactory("PixelArt", &create<PixelArtDialog, DockBehavior>); registerFactory("Transformation", &create<Transformation, DockBehavior>); registerFactory("UndoHistory", &create<UndoHistory, DockBehavior>); registerFactory("InputDevices", &create<InputDialog, DockBehavior>); @@ -247,14 +247,14 @@ Dialog *DialogManager::getDialog(GQuark name) { /** * Shows the named dialog, creating it if necessary. */ -void DialogManager::showDialog(gchar const *name) { - showDialog(g_quark_from_string(name)); +void DialogManager::showDialog(gchar const *name, bool grabfocus) { + showDialog(g_quark_from_string(name), grabfocus); } /** * Shows the named dialog, creating it if necessary. */ -void DialogManager::showDialog(GQuark name) { +void DialogManager::showDialog(GQuark name, bool grabfocus) { bool wantTiming = Inkscape::Preferences::get()->getBool("/dialogs/debug/trackAppear", false); GTimer *timer = (wantTiming) ? g_timer_new() : 0; // if needed, must be created/started before getDialog() Dialog *dialog = getDialog(name); @@ -265,7 +265,8 @@ void DialogManager::showDialog(GQuark name) { tracker->setAutodelete(true); timer = 0; } - dialog->present(); + if (grabfocus) + dialog->present(); } if ( timer ) { diff --git a/src/ui/dialog/dialog-manager.h b/src/ui/dialog/dialog-manager.h index 33b166aa1..15573f760 100644 --- a/src/ui/dialog/dialog-manager.h +++ b/src/ui/dialog/dialog-manager.h @@ -44,8 +44,8 @@ public: void registerFactory(GQuark name, DialogFactory factory); Dialog *getDialog(gchar const* dlgName); Dialog *getDialog(GQuark dlgName); - void showDialog(gchar const *name); - void showDialog(GQuark name); + void showDialog(gchar const *name, bool grabfocus=true); + void showDialog(GQuark name, bool grabfocus=true); protected: DialogManager(DialogManager const &d); // no copy diff --git a/src/ui/dialog/dialog.cpp b/src/ui/dialog/dialog.cpp index 14a26b716..3cc3f3d88 100644 --- a/src/ui/dialog/dialog.cpp +++ b/src/ui/dialog/dialog.cpp @@ -23,7 +23,7 @@ #include <gdk/gdkkeysyms.h> #include "inkscape.h" -#include "event-context.h" +#include "ui/tools/tool-base.h" #include "desktop.h" #include "desktop-handles.h" #include "modifier-fns.h" @@ -61,7 +61,7 @@ void sp_dialog_shutdown(GObject * /*object*/, gpointer dlgPtr) } -void hideCallback(GObject * /*object*/, gpointer dlgPtr) +static void hideCallback(GObject * /*object*/, gpointer dlgPtr) { g_return_if_fail( dlgPtr != NULL ); @@ -69,7 +69,7 @@ void hideCallback(GObject * /*object*/, gpointer dlgPtr) dlg->onHideF12(); } -void unhideCallback(GObject * /*object*/, gpointer dlgPtr) +static void unhideCallback(GObject * /*object*/, gpointer dlgPtr) { g_return_if_fail( dlgPtr != NULL ); @@ -270,15 +270,15 @@ bool Dialog::_onEvent(GdkEvent *event) switch (event->type) { case GDK_KEY_PRESS: { - switch (get_group0_keyval (&event->key)) { - case GDK_Escape: { + switch (Inkscape::UI::Tools::get_group0_keyval (&event->key)) { + case GDK_KEY_Escape: { _defocus(); ret = true; break; } - case GDK_F4: - case GDK_w: - case GDK_W: { + case GDK_KEY_F4: + case GDK_KEY_w: + case GDK_KEY_W: { if (mod_ctrl_only(event->key.state)) { _close(); ret = true; @@ -300,7 +300,7 @@ bool Dialog::_onEvent(GdkEvent *event) bool Dialog::_onKeyPress(GdkEventKey *event) { unsigned int shortcut; - shortcut = get_group0_keyval(event) | + shortcut = Inkscape::UI::Tools::get_group0_keyval(event) | ( event->state & GDK_SHIFT_MASK ? SP_SHORTCUT_SHIFT_MASK : 0 ) | ( event->state & GDK_CONTROL_MASK ? diff --git a/src/ui/dialog/dialog.h b/src/ui/dialog/dialog.h index 025e9eb58..ec5d203bc 100644 --- a/src/ui/dialog/dialog.h +++ b/src/ui/dialog/dialog.h @@ -21,7 +21,7 @@ class SPDesktop; namespace Inkscape { class Selection; -class Application; +struct Application; } namespace Inkscape { diff --git a/src/ui/dialog/document-metadata.cpp b/src/ui/dialog/document-metadata.cpp index 6318ffbbb..efe25d843 100644 --- a/src/ui/dialog/document-metadata.cpp +++ b/src/ui/dialog/document-metadata.cpp @@ -61,13 +61,30 @@ DocumentMetadata::getInstance() DocumentMetadata::DocumentMetadata() +#if WITH_GTKMM_3_0 + : UI::Widget::Panel ("", "/dialogs/documentmetadata", SP_VERB_DIALOG_METADATA) +#else : UI::Widget::Panel ("", "/dialogs/documentmetadata", SP_VERB_DIALOG_METADATA), _page_metadata1(1, 1), _page_metadata2(1, 1) +#endif { hide(); _getContents()->set_spacing (4); _getContents()->pack_start(_notebook, true, true); + _page_metadata1.set_border_width(2); + _page_metadata2.set_border_width(2); + +#if WITH_GTKMM_3_0 + _page_metadata1.set_column_spacing(2); + _page_metadata2.set_column_spacing(2); + _page_metadata1.set_row_spacing(2); + _page_metadata2.set_row_spacing(2); +#else + _page_metadata1.set_spacings(2); + _page_metadata2.set_spacings(2); +#endif + _notebook.append_page(_page_metadata1, _("Metadata")); _notebook.append_page(_page_metadata2, _("License")); @@ -98,50 +115,6 @@ DocumentMetadata::~DocumentMetadata() delete (*it); } -//======================================================================== - -/** - * Helper function that attachs widgets in a 3xn table. The widgets come in an - * array that has two entries per table row. The two entries code for four - * possible cases: (0,0) means insert space in first column; (0, non-0) means - * widget in columns 2-3; (non-0, 0) means label in columns 1-3; and - * (non-0, non-0) means two widgets in columns 2 and 3. - */ -inline void attach_all(Gtk::Table &table, const Gtk::Widget *arr[], unsigned size, int start = 0) -{ - for (unsigned i=0, r=start; i<size/sizeof(Gtk::Widget*); i+=2) - { - if (arr[i] && arr[i+1]) - { - table.attach (const_cast<Gtk::Widget&>(*arr[i]), 1, 2, r, r+1, - Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0); - table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 2, 3, r, r+1, - Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0); - } - else - { - if (arr[i+1]) - table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 1, 3, r, r+1, - Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0); - else if (arr[i]) - { - Gtk::Label& label = static_cast<Gtk::Label&> (const_cast<Gtk::Widget&>(*arr[i])); - label.set_alignment (0.0); - table.attach (label, 0, 3, r, r+1, - Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0); - } - else - { - Gtk::HBox *space = manage (new Gtk::HBox); - space->set_size_request (SPACE_SIZE_X, SPACE_SIZE_Y); - table.attach (*space, 0, 1, r, r+1, - (Gtk::AttachOptions)0, (Gtk::AttachOptions)0,0,0); - } - } - ++r; - } -} - void DocumentMetadata::build_metadata() { @@ -152,7 +125,14 @@ DocumentMetadata::build_metadata() Gtk::Label *label = manage (new Gtk::Label); label->set_markup (_("<b>Dublin Core Entities</b>")); label->set_alignment (0.0); - _page_metadata1.table().attach (*label, 0,3,0,1, Gtk::FILL, (Gtk::AttachOptions)0,0,0); + +#if WITH_GTKMM_3_0 + label->set_valign(Gtk::ALIGN_CENTER); + _page_metadata1.attach(*label, 0, 0, 3, 1); +#else + _page_metadata1.attach(*label, 0,3,0,1, Gtk::FILL, (Gtk::AttachOptions)0,0,0); +#endif + /* add generic metadata entry areas */ struct rdf_work_entity_t * entity; int row = 1; @@ -162,9 +142,22 @@ DocumentMetadata::build_metadata() _rdflist.push_back (w); Gtk::HBox *space = manage (new Gtk::HBox); space->set_size_request (SPACE_SIZE_X, SPACE_SIZE_Y); - _page_metadata1.table().attach (*space, 0,1, row, row+1, Gtk::FILL, (Gtk::AttachOptions)0,0,0); - _page_metadata1.table().attach (w->_label, 1,2, row, row+1, Gtk::FILL, (Gtk::AttachOptions)0,0,0); - _page_metadata1.table().attach (*w->_packable, 2,3, row, row+1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0); + +#if WITH_GTKMM_3_0 + space->set_valign(Gtk::ALIGN_CENTER); + _page_metadata1.attach(*space, 0, row, 1, 1); + + w->_label.set_valign(Gtk::ALIGN_CENTER); + _page_metadata1.attach(w->_label, 1, row, 1, 1); + + w->_packable->set_hexpand(); + w->_packable->set_valign(Gtk::ALIGN_CENTER); + _page_metadata1.attach(*w->_packable, 2, row, 1, 1); +#else + _page_metadata1.attach(*space, 0,1, row, row+1, Gtk::FILL, (Gtk::AttachOptions)0,0,0); + _page_metadata1.attach(w->_label, 1,2, row, row+1, Gtk::FILL, (Gtk::AttachOptions)0,0,0); + _page_metadata1.attach(*w->_packable, 2,3, row, row+1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0); +#endif } } @@ -174,14 +167,31 @@ DocumentMetadata::build_metadata() Gtk::Label *llabel = manage (new Gtk::Label); llabel->set_markup (_("<b>License</b>")); llabel->set_alignment (0.0); - _page_metadata2.table().attach (*llabel, 0,3, row, row+1, Gtk::FILL, (Gtk::AttachOptions)0,0,0); + +#if WITH_GTKMM_3_0 + llabel->set_valign(Gtk::ALIGN_CENTER); + _page_metadata2.attach(*llabel, 0, row, 3, 1); +#else + _page_metadata2.attach(*llabel, 0,3, row, row+1, Gtk::FILL, (Gtk::AttachOptions)0,0,0); +#endif + /* add license selector pull-down and URI */ ++row; _licensor.init (_wr); Gtk::HBox *space = manage (new Gtk::HBox); space->set_size_request (SPACE_SIZE_X, SPACE_SIZE_Y); - _page_metadata2.table().attach (*space, 0,1, row, row+1, Gtk::FILL, (Gtk::AttachOptions)0,0,0); - _page_metadata2.table().attach (_licensor, 1,3, row, row+1, Gtk::EXPAND|Gtk::FILL, (Gtk::AttachOptions)0,0,0); + +#if WITH_GTKMM_3_0 + space->set_valign(Gtk::ALIGN_CENTER); + _page_metadata2.attach(*space, 0, row, 1, 1); + + _licensor.set_hexpand(); + _licensor.set_valign(Gtk::ALIGN_CENTER); + _page_metadata2.attach(_licensor, 1, row, 2, 1); +#else + _page_metadata2.attach(*space, 0,1, row, row+1, Gtk::FILL, (Gtk::AttachOptions)0,0,0); + _page_metadata2.attach(_licensor, 1,3, row, row+1, Gtk::EXPAND|Gtk::FILL, (Gtk::AttachOptions)0,0,0); +#endif } /** diff --git a/src/ui/dialog/document-metadata.h b/src/ui/dialog/document-metadata.h index f201679b5..3b7ed1ec8 100644 --- a/src/ui/dialog/document-metadata.h +++ b/src/ui/dialog/document-metadata.h @@ -13,12 +13,22 @@ #ifndef INKSCAPE_UI_DIALOG_DOCUMENT_METADATA_H #define INKSCAPE_UI_DIALOG_DOCUMENT_METADATA_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + #include <list> #include <stddef.h> #include "ui/widget/panel.h" #include <gtkmm/notebook.h> + +#if WITH_GTKMM_3_0 +# include <gtkmm/grid.h> +#else +# include <gtkmm/table.h> +#endif + #include "ui/widget/licensor.h" -#include "ui/widget/notebook-page.h" #include "ui/widget/registry.h" namespace Inkscape { @@ -51,8 +61,13 @@ protected: Gtk::Notebook _notebook; - UI::Widget::NotebookPage _page_metadata1; - UI::Widget::NotebookPage _page_metadata2; +#if WITH_GTKMM_3_0 + Gtk::Grid _page_metadata1; + Gtk::Grid _page_metadata2; +#else + Gtk::Table _page_metadata1; + Gtk::Table _page_metadata2; +#endif //--------------------------------------------------------------- RDElist _rdflist; diff --git a/src/ui/dialog/document-properties.cpp b/src/ui/dialog/document-properties.cpp index f45b52f5b..a31ab1a09 100644 --- a/src/ui/dialog/document-properties.cpp +++ b/src/ui/dialog/document-properties.cpp @@ -22,31 +22,43 @@ # include <config.h> #endif +#include "ui/widget/notebook-page.h" #include "document-properties.h" #include "display/canvas-grid.h" #include "document.h" #include "desktop-handles.h" #include "desktop.h" -#include "helper/units.h" #include "inkscape.h" #include "io/sys.h" #include "preferences.h" +#include "shape-editor.h" #include "sp-namedview.h" -#include "sp-object-repr.h" #include "sp-root.h" #include "sp-script.h" +#include "style.h" +#include "svg/stringstream.h" +#include "tools-switch.h" #include "ui/widget/color-picker.h" #include "ui/widget/scalar-unit.h" +#include "ui/dialog/filedialog.h" #include "verbs.h" #include "widgets/icon.h" #include "xml/node-event-vector.h" #include "xml/repr.h" +#include "rdf.h" +#include "ui/widget/entity-entry.h" + #if defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2) #include "color-profile.h" #endif // defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2) +#include <gtkmm/imagemenuitem.h> #include <gtkmm/stock.h> +#include <gtkmm/table.h> + +#include <2geom/transforms.h> +#include "ui/icon-names.h" using std::pair; @@ -85,18 +97,21 @@ DocumentProperties& DocumentProperties::getInstance() DocumentProperties::DocumentProperties() : UI::Widget::Panel ("", "/dialogs/documentoptions", SP_VERB_DIALOG_NAMEDVIEW), - _page_page(1, 1, true, true), - _page_guides(1, 1), - _page_snap(1, 1), - _page_cms(1, 1), - _page_scripting(1, 1), - _page_external_scripts(1, 1), - _page_embedded_scripts(1, 1), + _page_page(Gtk::manage(new UI::Widget::NotebookPage(1, 1, true, true))), + _page_guides(Gtk::manage(new UI::Widget::NotebookPage(1, 1))), + _page_snap(Gtk::manage(new UI::Widget::NotebookPage(1, 1))), + _page_cms(Gtk::manage(new UI::Widget::NotebookPage(1, 1))), + _page_scripting(Gtk::manage(new UI::Widget::NotebookPage(1, 1))), + _page_external_scripts(Gtk::manage(new UI::Widget::NotebookPage(1, 1))), + _page_embedded_scripts(Gtk::manage(new UI::Widget::NotebookPage(1, 1))), + _page_metadata1(Gtk::manage(new UI::Widget::NotebookPage(1, 1))), + _page_metadata2(Gtk::manage(new UI::Widget::NotebookPage(1, 1))), //--------------------------------------------------------------- + _rcb_antialias(_("Use antialiasing"), _("If unset, no antialiasing will be done on the drawing"), "shape-rendering", _wr, false, NULL, NULL, NULL, "crispEdges"), _rcb_canb(_("Show page _border"), _("If set, rectangular page border is shown"), "showborder", _wr, false), _rcb_bord(_("Border on _top of drawing"), _("If set, border is always on top of the drawing"), "borderlayer", _wr, false), _rcb_shad(_("_Show border shadow"), _("If set, page border shows a shadow on its right and lower side"), "inkscape:showpageshadow", _wr, false), - _rcp_bg(_("Back_ground:"), _("Background color"), _("Color and transparency of the page background (also used for bitmap export)"), "pagecolor", "inkscape:pageopacity", _wr), + _rcp_bg(_("Back_ground color:"), _("Background color"), _("Color of the page background. Note: transparency setting ignored while editing but used when exporting to bitmap."), "pagecolor", "inkscape:pageopacity", _wr), _rcp_bord(_("Border _color:"), _("Page border color"), _("Color of the page border"), "bordercolor", "borderopacity", _wr), _rum_deflt(_("Default _units:"), "inkscape:document-units", _wr), _page_sizer(_wr), @@ -126,29 +141,24 @@ DocumentProperties::DocumentProperties() _rcb_perp(_("Snap perpendicularly"), _("When snapping to paths or guides, then also try snapping perpendicularly"), "inkscape:snap-perpendicular", _wr), _rcb_tang(_("Snap tangentially"), _("When snapping to paths or guides, then also try snapping tangentially"), "inkscape:snap-tangential", _wr), //--------------------------------------------------------------- -#if WITH_GTKMM_2_22 _grids_label_crea("", Gtk::ALIGN_START), -#else - _grids_label_crea("", Gtk::ALIGN_LEFT), -#endif _grids_button_new(C_("Grid", "_New"), _("Create new grid.")), _grids_button_remove(C_("Grid", "_Remove"), _("Remove selected grid.")), -#if WITH_GTKMM_2_22 _grids_label_def("", Gtk::ALIGN_START) -#else - _grids_label_def("", Gtk::ALIGN_LEFT) -#endif { _getContents()->set_spacing (4); _getContents()->pack_start(_notebook, true, true); - _notebook.append_page(_page_page, _("Page")); - _notebook.append_page(_page_guides, _("Guides")); + _notebook.append_page(*_page_page, _("Page")); + _notebook.append_page(*_page_guides, _("Guides")); _notebook.append_page(_grids_vbox, _("Grids")); - _notebook.append_page(_page_snap, _("Snap")); - _notebook.append_page(_page_cms, _("Color Management")); - _notebook.append_page(_page_scripting, _("Scripting")); + _notebook.append_page(*_page_snap, _("Snap")); + _notebook.append_page(*_page_cms, _("Color")); + _notebook.append_page(*_page_scripting, _("Scripting")); + _notebook.append_page(*_page_metadata1, _("Metadata")); + _notebook.append_page(*_page_metadata2, _("License")); + _wr.setUpdating (true); build_page(); build_guides(); build_gridspage(); @@ -157,6 +167,8 @@ DocumentProperties::DocumentProperties() build_cms(); #endif // defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2) build_scripting(); + build_metadata(); + _wr.setUpdating (false); _grids_button_new.signal_clicked().connect(sigc::mem_fun(*this, &DocumentProperties::onNewGrid)); _grids_button_remove.signal_clicked().connect(sigc::mem_fun(*this, &DocumentProperties::onRemoveGrid)); @@ -164,6 +176,9 @@ DocumentProperties::DocumentProperties() signalDocumentReplaced().connect(sigc::mem_fun(*this, &DocumentProperties::_handleDocumentReplaced)); signalActivateDesktop().connect(sigc::mem_fun(*this, &DocumentProperties::_handleActivateDesktop)); signalDeactiveDesktop().connect(sigc::mem_fun(*this, &DocumentProperties::_handleDeactivateDesktop)); + + _rum_deflt._changed_connection.block(); + _rum_deflt.getUnitMenu()->signal_changed().connect(sigc::mem_fun(*this, &DocumentProperties::onDocUnitChange)); } void DocumentProperties::init() @@ -185,6 +200,9 @@ DocumentProperties::~DocumentProperties() repr->removeListenerByData (this); Inkscape::XML::Node *root = sp_desktop_document(getDesktop())->getRoot()->getRepr(); root->removeListenerByData (this); + + for (RDElist::iterator it = _rdflist.begin(); it != _rdflist.end(); ++it) + delete (*it); } //======================================================================== @@ -196,41 +214,99 @@ DocumentProperties::~DocumentProperties() * widget in columns 2-3; (non-0, 0) means label in columns 1-3; and * (non-0, non-0) means two widgets in columns 2 and 3. */ -inline void attach_all(Gtk::Table &table, Gtk::Widget *const arr[], unsigned const n, int start = 0) +#if WITH_GTKMM_3_0 +inline void attach_all(Gtk::Grid &table, Gtk::Widget *const arr[], unsigned const n, int start = 0, int docum_prop_flag = 0) +#else +inline void attach_all(Gtk::Table &table, Gtk::Widget *const arr[], unsigned const n, int start = 0, int docum_prop_flag = 0) +#endif { - for (unsigned i = 0, r = start; i < n; i += 2) - { - if (arr[i] && arr[i+1]) - { - table.attach(*arr[i], 1, 2, r, r+1, - Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0); - table.attach(*arr[i+1], 2, 3, r, r+1, - Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0); - } - else - { + for (unsigned i = 0, r = start; i < n; i += 2) { + if (arr[i] && arr[i+1]) { +#if WITH_GTKMM_3_0 + arr[i]->set_hexpand(); + arr[i+1]->set_hexpand(); + arr[i]->set_valign(Gtk::ALIGN_CENTER); + arr[i+1]->set_valign(Gtk::ALIGN_CENTER); + table.attach(*arr[i], 1, r, 1, 1); + table.attach(*arr[i+1], 2, r, 1, 1); +#else + table.attach(*arr[i], 1, 2, r, r+1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0); + table.attach(*arr[i+1], 2, 3, r, r+1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0); +#endif + } else { if (arr[i+1]) { Gtk::AttachOptions yoptions = (Gtk::AttachOptions)0; if (dynamic_cast<Inkscape::UI::Widget::PageSizer*>(arr[i+1])) { // only the PageSizer in Document Properties|Page should be stretched vertically yoptions = Gtk::FILL|Gtk::EXPAND; } - table.attach(*arr[i+1], 1, 3, r, r+1, - Gtk::FILL|Gtk::EXPAND, yoptions, 0,0); - } - else if (arr[i]) - { + if (docum_prop_flag) { + // this sets the padding for subordinate widgets on the "Page" page + if( i==(n-8) || i==(n-10) ) { +#if WITH_GTKMM_3_0 + arr[i+1]->set_hexpand(); + arr[i+1]->set_margin_left(20); + arr[i+1]->set_margin_right(20); + + if (yoptions & Gtk::EXPAND) + arr[i+1]->set_vexpand(); + else + arr[i+1]->set_valign(Gtk::ALIGN_CENTER); + + table.attach(*arr[i+1], 1, r, 2, 1); +#else + table.attach(*arr[i+1], 1, 3, r, r+1, Gtk::FILL|Gtk::EXPAND, yoptions, 20,0); +#endif + } else { +#if WITH_GTKMM_3_0 + arr[i+1]->set_hexpand(); + + if (yoptions & Gtk::EXPAND) + arr[i+1]->set_vexpand(); + else + arr[i+1]->set_valign(Gtk::ALIGN_CENTER); + + table.attach(*arr[i+1], 1, r, 2, 1); +#else + table.attach(*arr[i+1], 1, 3, r, r+1, Gtk::FILL|Gtk::EXPAND, yoptions, 0,0); +#endif + } + } else { +#if WITH_GTKMM_3_0 + arr[i+1]->set_hexpand(); + + if (yoptions & Gtk::EXPAND) + arr[i+1]->set_vexpand(); + else + arr[i+1]->set_valign(Gtk::ALIGN_CENTER); + + table.attach(*arr[i+1], 1, r, 2, 1); +#else + table.attach(*arr[i+1], 1, 3, r, r+1, Gtk::FILL|Gtk::EXPAND, yoptions, 0,0); +#endif + } + } else if (arr[i]) { Gtk::Label& label = reinterpret_cast<Gtk::Label&>(*arr[i]); label.set_alignment (0.0); - table.attach (label, 0, 3, r, r+1, - Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0); - } - else - { + +#if WITH_GTKMM_3_0 + label.set_hexpand(); + label.set_valign(Gtk::ALIGN_CENTER); + table.attach(label, 0, r, 3, 1); +#else + table.attach (label, 0, 3, r, r+1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0); +#endif + } else { Gtk::HBox *space = manage (new Gtk::HBox); space->set_size_request (SPACE_SIZE_X, SPACE_SIZE_Y); - table.attach (*space, 0, 1, r, r+1, - (Gtk::AttachOptions)0, (Gtk::AttachOptions)0,0,0); + +#if WITH_GTKMM_3_0 + space->set_halign(Gtk::ALIGN_CENTER); + space->set_valign(Gtk::ALIGN_CENTER); + table.attach(*space, 0, r, 1, 1); +#else + table.attach (*space, 0, 1, r, r+1, (Gtk::AttachOptions)0, (Gtk::AttachOptions)0,0,0); +#endif } } ++r; @@ -239,38 +315,46 @@ inline void attach_all(Gtk::Table &table, Gtk::Widget *const arr[], unsigned con void DocumentProperties::build_page() { - _page_page.show(); + _page_page->show(); Gtk::Label* label_gen = manage (new Gtk::Label); label_gen->set_markup (_("<b>General</b>")); - Gtk::Label* label_bor = manage (new Gtk::Label); - label_bor->set_markup (_("<b>Border</b>")); Gtk::Label *label_for = manage (new Gtk::Label); label_for->set_markup (_("<b>Page Size</b>")); + Gtk::Label* label_dsp = manage (new Gtk::Label); + label_dsp->set_markup (_("<b>Display</b>")); _page_sizer.init(); Gtk::Widget *const widget_array[] = { label_gen, 0, 0, &_rum_deflt, - _rcp_bg._label, &_rcp_bg, + //label_col, 0, + //_rcp_bg._label, &_rcp_bg, 0, 0, label_for, 0, 0, &_page_sizer, 0, 0, - label_bor, 0, + label_dsp, 0, 0, &_rcb_canb, 0, &_rcb_bord, 0, &_rcb_shad, + 0, &_rcb_antialias, + _rcp_bg._label, &_rcp_bg, _rcp_bord._label, &_rcp_bord, }; - attach_all(_page_page.table(), widget_array, G_N_ELEMENTS(widget_array)); + std::list<Gtk::Widget*> _slaveList; + _slaveList.push_back(&_rcb_bord); + _slaveList.push_back(&_rcb_shad); + _rcb_canb.setSlaveWidgets(_slaveList); + + attach_all(_page_page->table(), widget_array, G_N_ELEMENTS(widget_array),0,1); } void DocumentProperties::build_guides() { - _page_guides.show(); + _page_guides->show(); Gtk::Label *label_gui = manage (new Gtk::Label); label_gui->set_markup (_("<b>Guides</b>")); @@ -283,12 +367,12 @@ void DocumentProperties::build_guides() _rcp_hgui._label, &_rcp_hgui }; - attach_all(_page_guides.table(), widget_array, G_N_ELEMENTS(widget_array)); + attach_all(_page_guides->table(), widget_array, G_N_ELEMENTS(widget_array)); } void DocumentProperties::build_snap() { - _page_snap.show(); + _page_snap->show(); Gtk::Label *label_o = manage (new Gtk::Label); label_o->set_markup (_("<b>Snap to objects</b>")); @@ -317,27 +401,19 @@ void DocumentProperties::build_snap() 0, &_rcb_tang }; - attach_all(_page_snap.table(), array, G_N_ELEMENTS(array)); + attach_all(_page_snap->table(), array, G_N_ELEMENTS(array)); } #if defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2) /// Populates the available color profiles combo box void DocumentProperties::populate_available_profiles(){ -#if WITH_GTKMM_2_24 _combo_avail.remove_all(); // Clear any existing items in the combo box -#else - _combo_avail.clear_items(); // Clear any existing items in the combo box -#endif // Iterate through the list of profiles and add the name to the combo box. std::vector<std::pair<Glib::ustring, Glib::ustring> > pairs = ColorProfile::getProfileFilesWithNames(); for ( std::vector<std::pair<Glib::ustring, Glib::ustring> >::const_iterator it = pairs.begin(); it != pairs.end(); ++it ) { Glib::ustring name = it->second; -#if WITH_GTKMM_2_24 _combo_avail.append(name); -#else - _combo_avail.append_text(name); -#endif } } @@ -490,6 +566,15 @@ void DocumentProperties::embedded_create_popup_menu(Gtk::Widget& parent, sigc::s _EmbeddedScriptsContextMenu.accelerate(parent); } +void DocumentProperties::onColorProfileSelectRow() +{ + Glib::RefPtr<Gtk::TreeSelection> sel = _LinkedProfilesList.get_selection(); + if (sel) { + _unlink_btn.set_sensitive(sel->count_selected_rows () > 0); + } +} + + void DocumentProperties::removeSelectedProfile(){ Glib::ustring name; if(_LinkedProfilesList.get_selection()) { @@ -516,46 +601,104 @@ void DocumentProperties::removeSelectedProfile(){ } populate_linked_profiles_box(); + onColorProfileSelectRow(); } void DocumentProperties::build_cms() { - _page_cms.show(); - -#if WITH_GTKMM_2_22 + _page_cms->show(); Gtk::Label *label_link= manage (new Gtk::Label("", Gtk::ALIGN_START)); -#else - Gtk::Label *label_link= manage (new Gtk::Label("", Gtk::ALIGN_LEFT)); -#endif label_link->set_markup (_("<b>Linked Color Profiles:</b>")); -#if WITH_GTKMM_2_22 Gtk::Label *label_avail = manage (new Gtk::Label("", Gtk::ALIGN_START)); + label_avail->set_markup (_("<b>Available Color Profiles:</b>")); + + _link_btn.set_tooltip_text(_("Link Profile")); +#if GTK_CHECK_VERSION(3,10,0) + _link_btn.set_image_from_icon_name(INKSCAPE_ICON("list-add"), Gtk::ICON_SIZE_SMALL_TOOLBAR); #else - Gtk::Label *label_avail = manage (new Gtk::Label("", Gtk::ALIGN_LEFT)); + Gtk::Image *image_link = Gtk::manage(new Gtk::Image()); + image_link->set_from_icon_name(INKSCAPE_ICON("list-add"), Gtk::ICON_SIZE_SMALL_TOOLBAR); + _link_btn.set_image(*image_link); #endif - label_avail->set_markup (_("<b>Available Color Profiles:</b>")); - _link_btn.set_label(_("Link Profile")); + _unlink_btn.set_tooltip_text(_("Unlink Profile")); +#if GTK_CHECK_VERSION(3,10,0) + _unlink_btn.set_image_from_icon_name(INKSCAPE_ICON("list-remove"), Gtk::ICON_SIZE_SMALL_TOOLBAR); +#else + Gtk::Image *image_unlink = Gtk::manage(new Gtk::Image()); + image_unlink->set_from_icon_name(INKSCAPE_ICON("list-remove"), Gtk::ICON_SIZE_SMALL_TOOLBAR); + _unlink_btn.set_image(*image_unlink); +#endif - _page_cms.set_spacing(4); + _page_cms->set_spacing(4); gint row = 0; label_link->set_alignment(0.0); - _page_cms.table().attach(*label_link, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); + +#if WITH_GTKMM_3_0 + label_link->set_hexpand(); + label_link->set_valign(Gtk::ALIGN_CENTER); + _page_cms->table().attach(*label_link, 0, row, 3, 1); +#else + _page_cms->table().attach(*label_link, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#endif + row++; - _page_cms.table().attach(_LinkedProfilesListScroller, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); + +#if WITH_GTKMM_3_0 + _LinkedProfilesListScroller.set_hexpand(); + _LinkedProfilesListScroller.set_valign(Gtk::ALIGN_CENTER); + _page_cms->table().attach(_LinkedProfilesListScroller, 0, row, 3, 1); +#else + _page_cms->table().attach(_LinkedProfilesListScroller, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#endif + row++; Gtk::HBox* spacer = Gtk::manage(new Gtk::HBox()); spacer->set_size_request(SPACE_SIZE_X, SPACE_SIZE_Y); - _page_cms.table().attach(*spacer, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); + +#if WITH_GTKMM_3_0 + spacer->set_hexpand(); + spacer->set_valign(Gtk::ALIGN_CENTER); + _page_cms->table().attach(*spacer, 0, row, 3, 1); +#else + _page_cms->table().attach(*spacer, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#endif + row++; label_avail->set_alignment(0.0); - _page_cms.table().attach(*label_avail, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); + +#if WITH_GTKMM_3_0 + label_avail->set_hexpand(); + label_avail->set_valign(Gtk::ALIGN_CENTER); + _page_cms->table().attach(*label_avail, 0, row, 3, 1); +#else + _page_cms->table().attach(*label_avail, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#endif + row++; - _page_cms.table().attach(_combo_avail, 0, 2, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); - _page_cms.table().attach(_link_btn, 2, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); + +#if WITH_GTKMM_3_0 + _combo_avail.set_hexpand(); + _combo_avail.set_valign(Gtk::ALIGN_CENTER); + _page_cms->table().attach(_combo_avail, 0, row, 1, 1); + + _link_btn.set_halign(Gtk::ALIGN_CENTER); + _link_btn.set_valign(Gtk::ALIGN_CENTER); + _link_btn.set_margin_left(2); + _link_btn.set_margin_right(2); + _page_cms->table().attach(_link_btn, 1, row, 1, 1); + + _unlink_btn.set_halign(Gtk::ALIGN_CENTER); + _unlink_btn.set_valign(Gtk::ALIGN_CENTER); + _page_cms->table().attach(_unlink_btn, 2, row, 1, 1); +#else + _page_cms->table().attach(_combo_avail, 0, 1, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); + _page_cms->table().attach(_link_btn, 1, 2, row, row + 1, (Gtk::AttachOptions)0, (Gtk::AttachOptions)0, 2, 0); + _page_cms->table().attach(_unlink_btn, 2, 3, row, row + 1, (Gtk::AttachOptions)0, (Gtk::AttachOptions)0, 0, 0); +#endif populate_available_profiles(); @@ -575,6 +718,9 @@ void DocumentProperties::build_cms() _LinkedProfilesListScroller.set_size_request(-1, 90); _link_btn.signal_clicked().connect(sigc::mem_fun(*this, &DocumentProperties::linkSelectedProfile)); + _unlink_btn.signal_clicked().connect(sigc::mem_fun(*this, &DocumentProperties::removeSelectedProfile)); + + _LinkedProfilesList.get_selection()->signal_changed().connect( sigc::mem_fun(*this, &DocumentProperties::onColorProfileSelectRow) ); _LinkedProfilesList.signal_button_release_event().connect_notify(sigc::mem_fun(*this, &DocumentProperties::linked_profiles_list_button_release)); cms_create_popup_menu(_LinkedProfilesList, sigc::mem_fun(*this, &DocumentProperties::removeSelectedProfile)); @@ -584,49 +730,101 @@ void DocumentProperties::build_cms() _emb_profiles_observer.set(SP_OBJECT(current->data)->parent); } _emb_profiles_observer.signal_changed().connect(sigc::mem_fun(*this, &DocumentProperties::populate_linked_profiles_box)); + onColorProfileSelectRow(); } #endif // defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2) void DocumentProperties::build_scripting() { - _page_scripting.show(); + _page_scripting->show(); - _page_scripting.set_spacing (4); - _page_scripting.pack_start(_scripting_notebook, true, true); + _page_scripting->set_spacing (4); + _page_scripting->pack_start(_scripting_notebook, true, true); - _scripting_notebook.append_page(_page_external_scripts, _("External scripts")); - _scripting_notebook.append_page(_page_embedded_scripts, _("Embedded scripts")); + _scripting_notebook.append_page(*_page_external_scripts, _("External scripts")); + _scripting_notebook.append_page(*_page_embedded_scripts, _("Embedded scripts")); //# External scripts tab - _page_external_scripts.show(); - -#if WITH_GTKMM_2_22 + _page_external_scripts->show(); Gtk::Label *label_external= manage (new Gtk::Label("", Gtk::ALIGN_START)); + label_external->set_markup (_("<b>External script files:</b>")); + + _external_add_btn.set_tooltip_text(_("Add the current file name or browse for a file")); +#if GTK_CHECK_VERSION(3,10,0) + _external_add_btn.set_image_from_icon_name(INKSCAPE_ICON("list-add"), Gtk::ICON_SIZE_SMALL_TOOLBAR); #else - Gtk::Label *label_external= manage (new Gtk::Label("", Gtk::ALIGN_LEFT)); + Gtk::Image *image_ext_add = Gtk::manage(new Gtk::Image()); + image_ext_add->set_from_icon_name(INKSCAPE_ICON("list-add"), Gtk::ICON_SIZE_SMALL_TOOLBAR); + _external_add_btn.set_image(*image_ext_add); #endif - label_external->set_markup (_("<b>External script files:</b>")); - _add_btn.set_label(_("Add")); + _external_remove_btn.set_tooltip_text(_("Remove")); +#if GTK_CHECK_VERSION(3,10,0) + _external_remove_btn.set_image_from_icon_name(INKSCAPE_ICON("list-remove"), Gtk::ICON_SIZE_SMALL_TOOLBAR); +#else + Gtk::Image *image_ext_rm = Gtk::manage(new Gtk::Image()); + image_ext_rm->set_from_icon_name(INKSCAPE_ICON("list-remove"), Gtk::ICON_SIZE_SMALL_TOOLBAR); + _external_remove_btn.set_image(*image_ext_rm); +#endif - _page_external_scripts.set_spacing(4); + _page_external_scripts->set_spacing(4); gint row = 0; label_external->set_alignment(0.0); - _page_external_scripts.table().attach(*label_external, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); + +#if WITH_GTKMM_3_0 + label_external->set_hexpand(); + label_external->set_valign(Gtk::ALIGN_CENTER); + _page_external_scripts->table().attach(*label_external, 0, row, 3, 1); +#else + _page_external_scripts->table().attach(*label_external, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#endif + row++; - _page_external_scripts.table().attach(_ExternalScriptsListScroller, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); + +#if WITH_GTKMM_3_0 + _ExternalScriptsListScroller.set_hexpand(); + _ExternalScriptsListScroller.set_valign(Gtk::ALIGN_CENTER); + _page_external_scripts->table().attach(_ExternalScriptsListScroller, 0, row, 3, 1); +#else + _page_external_scripts->table().attach(_ExternalScriptsListScroller, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#endif + row++; Gtk::HBox* spacer_external = Gtk::manage(new Gtk::HBox()); spacer_external->set_size_request(SPACE_SIZE_X, SPACE_SIZE_Y); - _page_external_scripts.table().attach(*spacer_external, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); - row++; - _page_external_scripts.table().attach(_script_entry, 0, 2, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); - _page_external_scripts.table().attach(_add_btn, 2, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#if WITH_GTKMM_3_0 + spacer_external->set_hexpand(); + spacer_external->set_valign(Gtk::ALIGN_CENTER); + _page_external_scripts->table().attach(*spacer_external, 0, row, 3, 1); +#else + _page_external_scripts->table().attach(*spacer_external, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#endif + row++; +#if WITH_GTKMM_3_0 + _script_entry.set_hexpand(); + _script_entry.set_valign(Gtk::ALIGN_CENTER); + _page_external_scripts->table().attach(_script_entry, 0, row, 1, 1); + + _external_add_btn.set_halign(Gtk::ALIGN_CENTER); + _external_add_btn.set_valign(Gtk::ALIGN_CENTER); + _external_add_btn.set_margin_left(2); + _external_add_btn.set_margin_right(2); + _page_external_scripts->table().attach(_external_add_btn, 1, row, 1, 1); + + _external_remove_btn.set_halign(Gtk::ALIGN_CENTER); + _external_remove_btn.set_valign(Gtk::ALIGN_CENTER); + _page_external_scripts->table().attach(_external_remove_btn, 2, row, 1, 1); +#else + _page_external_scripts->table().attach(_script_entry, 0, 1, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); + _page_external_scripts->table().attach(_external_add_btn, 1, 2, row, row + 1, (Gtk::AttachOptions)0, (Gtk::AttachOptions)0, 2, 0); + _page_external_scripts->table().attach(_external_remove_btn, 2, 3, row, row + 1, (Gtk::AttachOptions)0, (Gtk::AttachOptions)0, 0, 0); +#endif + //# Set up the External Scripts box _ExternalScriptsListStore = Gtk::ListStore::create(_ExternalScriptsListColumns); _ExternalScriptsList.set_model(_ExternalScriptsListStore); @@ -636,32 +834,84 @@ void DocumentProperties::build_scripting() //# Embedded scripts tab - _page_embedded_scripts.show(); - -#if WITH_GTKMM_2_22 + _page_embedded_scripts->show(); Gtk::Label *label_embedded= manage (new Gtk::Label("", Gtk::ALIGN_START)); + label_embedded->set_markup (_("<b>Embedded script files:</b>")); + + _embed_new_btn.set_tooltip_text(_("New")); +#if GTK_CHECK_VERSION(3,10,0) + _embed_new_btn.set_image_from_icon_name(INKSCAPE_ICON("list-add"), Gtk::ICON_SIZE_SMALL_TOOLBAR); #else - Gtk::Label *label_embedded= manage (new Gtk::Label("", Gtk::ALIGN_LEFT)); + Gtk::Image *image_embed_new = Gtk::manage(new Gtk::Image()); + image_embed_new->set_from_icon_name(INKSCAPE_ICON("list-add"), Gtk::ICON_SIZE_SMALL_TOOLBAR); + _embed_new_btn.set_image(*image_embed_new); +#endif + + _embed_remove_btn.set_tooltip_text(_("Remove")); +#if GTK_CHECK_VERSION(3,10,0) + _embed_remove_btn.set_image_from_icon_name(INKSCAPE_ICON("list-remove"), Gtk::ICON_SIZE_SMALL_TOOLBAR); +#else + Gtk::Image *image_embed_rm = Gtk::manage(new Gtk::Image()); + image_embed_rm->set_from_icon_name(INKSCAPE_ICON("list-remove"), Gtk::ICON_SIZE_SMALL_TOOLBAR); + _embed_remove_btn.set_image(*image_embed_rm); #endif - label_embedded->set_markup (_("<b>Embedded script files:</b>")); - _new_btn.set_label(_("New")); +#if !WITH_GTKMM_3_0 + // TODO: This has been removed from Gtkmm 3.0. Check that + // everything still looks OK! + _embed_button_box.set_child_min_width( 16 ); + _embed_button_box.set_spacing( 4 ); +#endif + _embed_button_box.set_layout (Gtk::BUTTONBOX_START); + _embed_button_box.add(_embed_new_btn); + _embed_button_box.add(_embed_remove_btn); - _page_embedded_scripts.set_spacing(4); + _page_embedded_scripts->set_spacing(4); row = 0; label_embedded->set_alignment(0.0); - _page_embedded_scripts.table().attach(*label_embedded, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); + +#if WITH_GTKMM_3_0 + label_embedded->set_hexpand(); + label_embedded->set_valign(Gtk::ALIGN_CENTER); + _page_embedded_scripts->table().attach(*label_embedded, 0, row, 3, 1); +#else + _page_embedded_scripts->table().attach(*label_embedded, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#endif + + row++; + +#if WITH_GTKMM_3_0 + _EmbeddedScriptsListScroller.set_hexpand(); + _EmbeddedScriptsListScroller.set_valign(Gtk::ALIGN_CENTER); + _page_embedded_scripts->table().attach(_EmbeddedScriptsListScroller, 0, row, 3, 1); +#else + _page_embedded_scripts->table().attach(_EmbeddedScriptsListScroller, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#endif + row++; - _page_embedded_scripts.table().attach(_EmbeddedScriptsListScroller, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); + +#if WITH_GTKMM_3_0 + _embed_button_box.set_hexpand(); + _embed_button_box.set_valign(Gtk::ALIGN_CENTER); + _page_embedded_scripts->table().attach(_embed_button_box, 0, row, 1, 1); +#else + _page_embedded_scripts->table().attach(_embed_button_box, 0, 1, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#endif + row++; Gtk::HBox* spacer_embedded = Gtk::manage(new Gtk::HBox()); spacer_embedded->set_size_request(SPACE_SIZE_X, SPACE_SIZE_Y); - _page_embedded_scripts.table().attach(*spacer_embedded, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); - row++; - _page_embedded_scripts.table().attach(_new_btn, 2, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#if WITH_GTKMM_3_0 + spacer_embedded->set_hexpand(); + spacer_embedded->set_valign(Gtk::ALIGN_CENTER); + _page_embedded_scripts->table().attach(*spacer_embedded, 0, row, 3, 1); +#else + _page_embedded_scripts->table().attach(*spacer_embedded, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#endif + row++; //# Set up the Embedded Scripts box @@ -672,25 +922,39 @@ void DocumentProperties::build_scripting() // TODO restore? _EmbeddedScriptsList.set_fixed_height_mode(true); //# Set up the Embedded Scripts content box -#if WITH_GTKMM_2_22 Gtk::Label *label_embedded_content= manage (new Gtk::Label("", Gtk::ALIGN_START)); -#else - Gtk::Label *label_embedded_content= manage (new Gtk::Label("", Gtk::ALIGN_LEFT)); -#endif label_embedded_content->set_markup (_("<b>Content:</b>")); label_embedded_content->set_alignment(0.0); - _page_embedded_scripts.table().attach(*label_embedded_content, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); + +#if WITH_GTKMM_3_0 + label_embedded_content->set_hexpand(); + label_embedded_content->set_valign(Gtk::ALIGN_CENTER); + _page_embedded_scripts->table().attach(*label_embedded_content, 0, row, 3, 1); +#else + _page_embedded_scripts->table().attach(*label_embedded_content, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#endif + row++; - _page_embedded_scripts.table().attach(_EmbeddedContentScroller, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#if WITH_GTKMM_3_0 + _EmbeddedContentScroller.set_hexpand(); + _EmbeddedContentScroller.set_valign(Gtk::ALIGN_CENTER); + _page_embedded_scripts->table().attach(_EmbeddedContentScroller, 0, row, 3, 1); +#else + _page_embedded_scripts->table().attach(_EmbeddedContentScroller, 0, 3, row, row + 1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0, 0, 0); +#endif _EmbeddedContentScroller.add(_EmbeddedContent); _EmbeddedContentScroller.set_shadow_type(Gtk::SHADOW_IN); _EmbeddedContentScroller.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); - _EmbeddedContentScroller.set_size_request(-1, -1); + _EmbeddedContentScroller.set_size_request(-1, 140); _EmbeddedScriptsList.signal_cursor_changed().connect(sigc::mem_fun(*this, &DocumentProperties::changeEmbeddedScript)); + _EmbeddedScriptsList.get_selection()->signal_changed().connect( sigc::mem_fun(*this, &DocumentProperties::onEmbeddedScriptSelectRow) ); + + _ExternalScriptsList.get_selection()->signal_changed().connect( sigc::mem_fun(*this, &DocumentProperties::onExternalScriptSelectRow) ); + _EmbeddedContent.get_buffer()->signal_changed().connect(sigc::mem_fun(*this, &DocumentProperties::editEmbeddedScript)); populate_script_lists(); @@ -700,17 +964,20 @@ void DocumentProperties::build_scripting() _ExternalScriptsListScroller.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_ALWAYS); _ExternalScriptsListScroller.set_size_request(-1, 90); - _add_btn.signal_clicked().connect(sigc::mem_fun(*this, &DocumentProperties::addExternalScript)); + _external_add_btn.signal_clicked().connect(sigc::mem_fun(*this, &DocumentProperties::addExternalScript)); _EmbeddedScriptsListScroller.add(_EmbeddedScriptsList); _EmbeddedScriptsListScroller.set_shadow_type(Gtk::SHADOW_IN); _EmbeddedScriptsListScroller.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_ALWAYS); _EmbeddedScriptsListScroller.set_size_request(-1, 90); - _new_btn.signal_clicked().connect(sigc::mem_fun(*this, &DocumentProperties::addEmbeddedScript)); - + _embed_new_btn.signal_clicked().connect(sigc::mem_fun(*this, &DocumentProperties::addEmbeddedScript)); #if defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2) + + _external_remove_btn.signal_clicked().connect(sigc::mem_fun(*this, &DocumentProperties::removeExternalScript)); + _embed_remove_btn.signal_clicked().connect(sigc::mem_fun(*this, &DocumentProperties::removeEmbeddedScript)); + _ExternalScriptsList.signal_button_release_event().connect_notify(sigc::mem_fun(*this, &DocumentProperties::external_scripts_list_button_release)); external_create_popup_menu(_ExternalScriptsList, sigc::mem_fun(*this, &DocumentProperties::removeExternalScript)); @@ -724,14 +991,123 @@ void DocumentProperties::build_scripting() _scripts_observer.set(SP_OBJECT(current->data)->parent); } _scripts_observer.signal_changed().connect(sigc::mem_fun(*this, &DocumentProperties::populate_script_lists)); + onEmbeddedScriptSelectRow(); + onExternalScriptSelectRow(); } +void DocumentProperties::build_metadata() +{ + using Inkscape::UI::Widget::EntityEntry; + + _page_metadata1->show(); + + Gtk::Label *label = manage (new Gtk::Label); + label->set_markup (_("<b>Dublin Core Entities</b>")); + label->set_alignment (0.0); + +#if WITH_GTKMM_3_0 + label->set_valign(Gtk::ALIGN_CENTER); + _page_metadata1->table().attach (*label, 0,0,3,1); +#else + _page_metadata1->table().attach (*label, 0,3,0,1, Gtk::FILL, (Gtk::AttachOptions)0,0,0); +#endif + + /* add generic metadata entry areas */ + struct rdf_work_entity_t * entity; + int row = 1; + for (entity = rdf_work_entities; entity && entity->name; entity++, row++) { + if ( entity->editable == RDF_EDIT_GENERIC ) { + EntityEntry *w = EntityEntry::create (entity, _wr); + _rdflist.push_back (w); + Gtk::HBox *space = manage (new Gtk::HBox); + space->set_size_request (SPACE_SIZE_X, SPACE_SIZE_Y); + +#if WITH_GTKMM_3_0 + space->set_valign(Gtk::ALIGN_CENTER); + _page_metadata1->table().attach(*space, 0, row, 1, 1); + + w->_label.set_valign(Gtk::ALIGN_CENTER); + _page_metadata1->table().attach(w->_label, 1, row, 1, 1); + + w->_packable->set_hexpand(); + w->_packable->set_valign(Gtk::ALIGN_CENTER); + _page_metadata1->table().attach(*w->_packable, 2, row, 1, 1); +#else + _page_metadata1->table().attach (*space, 0,1, row, row+1, Gtk::FILL, (Gtk::AttachOptions)0,0,0); + _page_metadata1->table().attach (w->_label, 1,2, row, row+1, Gtk::FILL, (Gtk::AttachOptions)0,0,0); + _page_metadata1->table().attach (*w->_packable, 2,3, row, row+1, Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0); +#endif + } + } + + Gtk::Button *button_save = manage (new Gtk::Button(_("_Save as default"),1)); + button_save->set_tooltip_text(_("Save this metadata as the default metadata")); + Gtk::Button *button_load = manage (new Gtk::Button(_("Use _default"),1)); + button_load->set_tooltip_text(_("Use the previously saved default metadata here")); + +#if WITH_GTKMM_3_0 + Gtk::ButtonBox *box_buttons = manage (new Gtk::ButtonBox); +#else + Gtk::HButtonBox *box_buttons = manage (new Gtk::HButtonBox); +#endif + + box_buttons->set_layout(Gtk::BUTTONBOX_END); + box_buttons->set_spacing(4); + box_buttons->pack_start(*button_save, true, true, 6); + box_buttons->pack_start(*button_load, true, true, 6); + _page_metadata1->pack_end(*box_buttons, false, false, 0); + + button_save->signal_clicked().connect(sigc::mem_fun(*this, &DocumentProperties::save_default_metadata)); + button_load->signal_clicked().connect(sigc::mem_fun(*this, &DocumentProperties::load_default_metadata)); + + _page_metadata2->show(); + + row = 0; + Gtk::Label *llabel = manage (new Gtk::Label); + llabel->set_markup (_("<b>License</b>")); + llabel->set_alignment (0.0); + +#if WITH_GTKMM_3_0 + llabel->set_valign(Gtk::ALIGN_CENTER); + _page_metadata2->table().attach(*llabel, 0, row, 3, 1); +#else + _page_metadata2->table().attach (*llabel, 0,3, row, row+1, Gtk::FILL, (Gtk::AttachOptions)0,0,0); +#endif + + /* add license selector pull-down and URI */ + ++row; + _licensor.init (_wr); + Gtk::HBox *space = manage (new Gtk::HBox); + space->set_size_request (SPACE_SIZE_X, SPACE_SIZE_Y); + +#if WITH_GTKMM_3_0 + space->set_valign(Gtk::ALIGN_CENTER); + _page_metadata2->table().attach(*space, 0, row, 1, 1); + + _licensor.set_hexpand(); + _licensor.set_valign(Gtk::ALIGN_CENTER); + _page_metadata2->table().attach(_licensor, 1, row, 3, 1); +#else + _page_metadata2->table().attach (*space, 0,1, row, row+1, Gtk::FILL, (Gtk::AttachOptions)0,0,0); + _page_metadata2->table().attach (_licensor, 1,3, row, row+1, Gtk::EXPAND|Gtk::FILL, (Gtk::AttachOptions)0,0,0); +#endif +} void DocumentProperties::addExternalScript(){ + SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if (!desktop){ + if (!desktop) { g_warning("No active desktop"); - } else { + return; + } + + if (_script_entry.get_text().empty() ) { + // Click Add button with no filename, show a Browse dialog + browseExternalScript(); + } + + if (!_script_entry.get_text().empty()) { + Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); Inkscape::XML::Node *scriptRepr = xml_doc->createElement("svg:script"); scriptRepr->setAttribute("xlink:href", (gchar*) _script_entry.get_text().c_str()); @@ -744,6 +1120,56 @@ void DocumentProperties::addExternalScript(){ populate_script_lists(); } + +} + +static Inkscape::UI::Dialog::FileOpenDialog * selectPrefsFileInstance = NULL; + +void DocumentProperties::browseExternalScript() { + + //# Get the current directory for finding files + static Glib::ustring open_path; + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + + Glib::ustring attr = prefs->getString(_prefs_path); + if (!attr.empty()) open_path = attr; + + //# Test if the open_path directory exists + if (!Inkscape::IO::file_test(open_path.c_str(), + (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) + open_path = ""; + + //# If no open path, default to our home directory + if (open_path.empty()) + { + open_path = g_get_home_dir(); + open_path.append(G_DIR_SEPARATOR_S); + } + + //# Create a dialog + SPDesktop *desktop = SP_ACTIVE_DESKTOP; + if (!selectPrefsFileInstance) { + selectPrefsFileInstance = + Inkscape::UI::Dialog::FileOpenDialog::create( + *desktop->getToplevel(), + open_path, + Inkscape::UI::Dialog::CUSTOM_TYPE, + _("Select a script to load")); + selectPrefsFileInstance->addFilterMenu("Javascript Files", "*.js"); + } + + //# Show the dialog + bool const success = selectPrefsFileInstance->show(); + + if (!success) { + return; + } + + //# User selected something. Get name and type + Glib::ustring fileName = selectPrefsFileInstance->getFilename(); + + _script_entry.set_text(fileName); } void DocumentProperties::addEmbeddedScript(){ @@ -777,17 +1203,19 @@ void DocumentProperties::removeExternalScript(){ const GSList *current = SP_ACTIVE_DOCUMENT->getResourceList( "script" ); while ( current ) { - SPObject* obj = SP_OBJECT(current->data); - SPScript* script = (SPScript*) obj; - if (name == script->xlinkhref){ - - //XML Tree being used directly here while it shouldn't be. - Inkscape::XML::Node *repr = obj->getRepr(); - if (repr){ - sp_repr_unparent(repr); - - // inform the document, so we can undo - DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_EDIT_REMOVE_EXTERNAL_SCRIPT, _("Remove external script")); + if (current->data && SP_IS_OBJECT(current->data)) { + SPObject* obj = SP_OBJECT(current->data); + SPScript* script = SP_SCRIPT(obj); + if (name == script->xlinkhref){ + + //XML Tree being used directly here while it shouldn't be. + Inkscape::XML::Node *repr = obj->getRepr(); + if (repr){ + sp_repr_unparent(repr); + + // inform the document, so we can undo + DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_EDIT_REMOVE_EXTERNAL_SCRIPT, _("Remove external script")); + } } } current = g_slist_next(current); @@ -810,16 +1238,18 @@ void DocumentProperties::removeEmbeddedScript(){ const GSList *current = SP_ACTIVE_DOCUMENT->getResourceList( "script" ); while ( current ) { - SPObject* obj = SP_OBJECT(current->data); - if (id == obj->getId()){ + if (current->data && SP_IS_OBJECT(current->data)) { + SPObject* obj = SP_OBJECT(current->data); + if (id == obj->getId()){ - //XML Tree being used directly here while it shouldn't be. - Inkscape::XML::Node *repr = obj->getRepr(); - if (repr){ - sp_repr_unparent(repr); + //XML Tree being used directly here while it shouldn't be. + Inkscape::XML::Node *repr = obj->getRepr(); + if (repr){ + sp_repr_unparent(repr); - // inform the document, so we can undo - DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_EDIT_REMOVE_EMBEDDED_SCRIPT, _("Remove embedded script")); + // inform the document, so we can undo + DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_EDIT_REMOVE_EMBEDDED_SCRIPT, _("Remove embedded script")); + } } } current = g_slist_next(current); @@ -828,6 +1258,22 @@ void DocumentProperties::removeEmbeddedScript(){ populate_script_lists(); } +void DocumentProperties::onExternalScriptSelectRow() +{ + Glib::RefPtr<Gtk::TreeSelection> sel = _ExternalScriptsList.get_selection(); + if (sel) { + _external_remove_btn.set_sensitive(sel->count_selected_rows () > 0); + } +} + +void DocumentProperties::onEmbeddedScriptSelectRow() +{ + Glib::RefPtr<Gtk::TreeSelection> sel = _EmbeddedScriptsList.get_selection(); + if (sel) { + _embed_remove_btn.set_sensitive(sel->count_selected_rows () > 0); + } +} + void DocumentProperties::changeEmbeddedScript(){ Glib::ustring id; if(_EmbeddedScriptsList.get_selection()) { @@ -916,7 +1362,7 @@ void DocumentProperties::populate_script_lists(){ if (current) _scripts_observer.set(SP_OBJECT(current->data)->parent); while ( current ) { SPObject* obj = SP_OBJECT(current->data); - SPScript* script = (SPScript*) obj; + SPScript* script = SP_SCRIPT(obj); if (script->xlinkhref) { Gtk::TreeModel::Row row = *(_ExternalScriptsListStore->append()); @@ -991,11 +1437,7 @@ void DocumentProperties::build_gridspage() _grids_hbox_crea.pack_start(_grids_button_new, true, true); for (gint t = 0; t <= GRID_MAXTYPENR; t++) { -#if WITH_GTKMM_2_24 _grids_combo_gridtype.append( CanvasGrid::getName( (GridType) t ) ); -#else - _grids_combo_gridtype.append_text( CanvasGrid::getName( (GridType) t ) ); -#endif } _grids_combo_gridtype.set_active_text( CanvasGrid::getName(GRID_RECTANGULAR) ); @@ -1034,12 +1476,31 @@ void DocumentProperties::update() _rcp_bord.setRgba32 (nv->bordercolor); _rcb_shad.setActive (nv->showpageshadow); - if (nv->doc_units) - _rum_deflt.setUnit (nv->doc_units); + SPRoot *root = dt->getDocument()->getRoot(); + _rcb_antialias.set_xml_target(root->getRepr(), dt->getDocument()); + _rcb_antialias.setActive(root->style->shape_rendering.computed != SP_CSS_SHAPE_RENDERING_CRISPEDGES); + + if (nv->doc_units) { + _rum_deflt.setUnit (nv->doc_units->abbr); + } - double const doc_w_px = sp_desktop_document(dt)->getWidth(); - double const doc_h_px = sp_desktop_document(dt)->getHeight(); - _page_sizer.setDim (doc_w_px, doc_h_px); + double doc_w = sp_desktop_document(dt)->getRoot()->width.value; + Glib::ustring doc_w_unit = unit_table.getUnit(sp_desktop_document(dt)->getRoot()->width.unit)->abbr; + if (doc_w_unit == "") { + doc_w_unit = "px"; + } else if (doc_w_unit == "%" && sp_desktop_document(dt)->getRoot()->viewBox_set) { + doc_w_unit = "px"; + doc_w = sp_desktop_document(dt)->getRoot()->viewBox.width(); + } + double doc_h = sp_desktop_document(dt)->getRoot()->height.value; + Glib::ustring doc_h_unit = unit_table.getUnit(sp_desktop_document(dt)->getRoot()->height.unit)->abbr; + if (doc_h_unit == "") { + doc_h_unit = "px"; + } else if (doc_h_unit == "%" && sp_desktop_document(dt)->getRoot()->viewBox_set) { + doc_h_unit = "px"; + doc_h = sp_desktop_document(dt)->getRoot()->viewBox.height(); + } + _page_sizer.setDim(Inkscape::Util::Quantity(doc_w, doc_w_unit), Inkscape::Util::Quantity(doc_h, doc_h_unit)); _page_sizer.updateFitMarginsUI(nv->getRepr()); //-----------------------------------------------------------guide page @@ -1069,6 +1530,14 @@ void DocumentProperties::update() populate_available_profiles(); #endif // defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2) + //-----------------------------------------------------------meta pages + /* update the RDF entities */ + for (RDElist::iterator it = _rdflist.begin(); it != _rdflist.end(); ++it) + (*it)->update (SP_ACTIVE_DOCUMENT); + + _licensor.update (SP_ACTIVE_DOCUMENT); + + _wr.setUpdating (false); } @@ -1104,6 +1573,23 @@ void DocumentProperties::on_response (int id) hide(); } +void DocumentProperties::load_default_metadata() +{ + /* Get the data RDF entities data from preferences*/ + for (RDElist::iterator it = _rdflist.begin(); it != _rdflist.end(); ++it) { + (*it)->load_from_preferences (); + } +} + +void DocumentProperties::save_default_metadata() +{ + /* Save these RDF entities to preferences*/ + for (RDElist::iterator it = _rdflist.begin(); it != _rdflist.end(); ++it) { + (*it)->save_to_preferences (SP_ACTIVE_DOCUMENT); + } +} + + void DocumentProperties::_handleDocumentReplaced(SPDesktop* desktop, SPDocument *document) { Inkscape::XML::Node *repr = sp_desktop_namedview(desktop)->getRepr(); @@ -1197,6 +1683,83 @@ void DocumentProperties::onRemoveGrid() } } +/** Callback for document unit change. */ +void DocumentProperties::onDocUnitChange() +{ + SPDocument *doc = SP_ACTIVE_DOCUMENT; + // Don't execute when change is being undone + if (!DocumentUndo::getUndoSensitive(doc)) { + return; + } + // Don't execute when initializing widgets + if (_wr.isUpdating()) { + return; + } + + + Inkscape::XML::Node *repr = sp_desktop_namedview(getDesktop())->getRepr(); + Inkscape::Util::Unit const *old_doc_unit = unit_table.getUnit("px"); + if(repr->attribute("inkscape:document-units")) { + old_doc_unit = unit_table.getUnit(repr->attribute("inkscape:document-units")); + } + Inkscape::Util::Unit const *doc_unit = _rum_deflt.getUnit(); + + // Set document unit + Inkscape::SVGOStringStream os; + os << doc_unit->abbr; + repr->setAttribute("inkscape:document-units", os.str().c_str()); + + // Set viewBox + if (doc->getRoot()->viewBox_set) { + gdouble scale = Inkscape::Util::Quantity::convert(1, old_doc_unit, doc_unit); + doc->setViewBox(doc->getRoot()->viewBox*Geom::Scale(scale)); + } else { + Inkscape::Util::Quantity width = doc->getWidth(); + Inkscape::Util::Quantity height = doc->getHeight(); + doc->setViewBox(Geom::Rect::from_xywh(0, 0, width.value(doc_unit), height.value(doc_unit))); + } + + // TODO: Fix bug in nodes tool instead of switching away from it + if (tools_active(getDesktop()) == TOOLS_NODES) { + tools_switch(getDesktop(), TOOLS_SELECT); + } + + // Scale and translate objects + // set transform options to scale all things with the transform, so all things scale properly after the viewbox change. + /// \todo this "low-level" code of changing viewbox/unit should be moved somewhere else + + // save prefs + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + bool transform_stroke = prefs->getBool("/options/transform/stroke", true); + bool transform_rectcorners = prefs->getBool("/options/transform/rectcorners", true); + bool transform_pattern = prefs->getBool("/options/transform/pattern", true); + bool transform_gradient = prefs->getBool("/options/transform/gradient", true); + + prefs->setBool("/options/transform/stroke", true); + prefs->setBool("/options/transform/rectcorners", true); + prefs->setBool("/options/transform/pattern", true); + prefs->setBool("/options/transform/gradient", true); + { + ShapeEditor::blockSetItem(true); + gdouble viewscale = doc->getWidth().value("px")/doc->getRoot()->viewBox.width(); + if (doc->getHeight().value("px")/doc->getRoot()->viewBox.height() < viewscale) + viewscale = doc->getHeight().value("px")/doc->getRoot()->viewBox.height(); + gdouble scale = Inkscape::Util::Quantity::convert(1, old_doc_unit, doc_unit); + doc->getRoot()->scaleChildItemsRec(Geom::Scale(scale), Geom::Point(-viewscale*doc->getRoot()->viewBox.min()[Geom::X] + + (doc->getWidth().value("px") - viewscale*doc->getRoot()->viewBox.width())/2, + viewscale*doc->getRoot()->viewBox.min()[Geom::Y] + + (doc->getHeight().value("px") + viewscale*doc->getRoot()->viewBox.height())/2)); + ShapeEditor::blockSetItem(false); + } + prefs->setBool("/options/transform/stroke", transform_stroke); + prefs->setBool("/options/transform/rectcorners", transform_rectcorners); + prefs->setBool("/options/transform/pattern", transform_pattern); + prefs->setBool("/options/transform/gradient", transform_gradient); + + doc->setModifiedSinceSave(); + + DocumentUndo::done(doc, SP_VERB_NONE, _("Changed document unit")); +} } // namespace Dialog } // namespace UI diff --git a/src/ui/dialog/document-properties.h b/src/ui/dialog/document-properties.h index 21453141a..495f3177d 100644 --- a/src/ui/dialog/document-properties.h +++ b/src/ui/dialog/document-properties.h @@ -15,11 +15,11 @@ #define INKSCAPE_UI_DIALOG_DOCUMENT_PREFERENCES_H #include <stddef.h> -#include <sigc++/sigc++.h>// -#include "ui/widget/notebook-page.h" +#include <sigc++/sigc++.h> #include <gtkmm/comboboxtext.h> #include <gtkmm/liststore.h> #include <gtkmm/notebook.h> +#include <gtkmm/buttonbox.h> #include <gtkmm/textview.h> #include "ui/widget/page-sizer.h" @@ -27,13 +27,23 @@ #include "ui/widget/registry.h" #include "ui/widget/tolerance-slider.h" #include "ui/widget/panel.h" +#include "ui/widget/licensor.h" #include "xml/helper-observer.h" namespace Inkscape { + namespace XML { + class Node; + } namespace UI { + namespace Widget { + class EntityEntry; + class NotebookPage; + } namespace Dialog { +typedef std::list<UI::Widget::EntityEntry*> RDElist; + class DocumentProperties : public UI::Widget::Panel { public: void update(); @@ -52,6 +62,7 @@ protected: void build_cms(); #endif // defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2) void build_scripting(); + void build_metadata(); void init(); virtual void on_response (int); @@ -60,6 +71,7 @@ protected: void populate_linked_profiles_box(); void linkSelectedProfile(); void removeSelectedProfile(); + void onColorProfileSelectRow(); void linked_profiles_list_button_release(GdkEventButton* event); void cms_create_popup_menu(Gtk::Widget& parent, sigc::slot<void> rem); #endif // defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2) @@ -68,13 +80,18 @@ protected: void embedded_scripts_list_button_release(GdkEventButton* event); void populate_script_lists(); void addExternalScript(); + void browseExternalScript(); void addEmbeddedScript(); void removeExternalScript(); void removeEmbeddedScript(); void changeEmbeddedScript(); + void onExternalScriptSelectRow(); + void onEmbeddedScriptSelectRow(); void editEmbeddedScript(); void external_create_popup_menu(Gtk::Widget& parent, sigc::slot<void> rem); void embedded_create_popup_menu(Gtk::Widget& parent, sigc::slot<void> rem); + void load_default_metadata(); + void save_default_metadata(); void _handleDocumentReplaced(SPDesktop* desktop, SPDocument *document); void _handleActivateDesktop(Inkscape::Application *application, SPDesktop *desktop); @@ -83,20 +100,24 @@ protected: Inkscape::XML::SignalObserver _emb_profiles_observer, _scripts_observer; Gtk::Notebook _notebook; - UI::Widget::NotebookPage _page_page; - UI::Widget::NotebookPage _page_guides; - UI::Widget::NotebookPage _page_snap; - UI::Widget::NotebookPage _page_cms; - UI::Widget::NotebookPage _page_scripting; + UI::Widget::NotebookPage *_page_page; + UI::Widget::NotebookPage *_page_guides; + UI::Widget::NotebookPage *_page_snap; + UI::Widget::NotebookPage *_page_cms; + UI::Widget::NotebookPage *_page_scripting; Gtk::Notebook _scripting_notebook; - UI::Widget::NotebookPage _page_external_scripts; - UI::Widget::NotebookPage _page_embedded_scripts; + UI::Widget::NotebookPage *_page_external_scripts; + UI::Widget::NotebookPage *_page_embedded_scripts; + + UI::Widget::NotebookPage *_page_metadata1; + UI::Widget::NotebookPage *_page_metadata2; Gtk::VBox _grids_vbox; UI::Widget::Registry _wr; //--------------------------------------------------------------- + UI::Widget::RegisteredCheckButton _rcb_antialias; UI::Widget::RegisteredCheckButton _rcb_canb; UI::Widget::RegisteredCheckButton _rcb_bord; UI::Widget::RegisteredCheckButton _rcb_shad; @@ -119,6 +140,7 @@ protected: //--------------------------------------------------------------- Gtk::ComboBoxText _combo_avail; Gtk::Button _link_btn; + Gtk::Button _unlink_btn; class LinkedProfilesColumns : public Gtk::TreeModel::ColumnRecord { public: @@ -134,8 +156,16 @@ protected: Gtk::Menu _EmbProfContextMenu; //--------------------------------------------------------------- - Gtk::Button _add_btn; - Gtk::Button _new_btn; + Gtk::Button _external_add_btn; + Gtk::Button _external_remove_btn; + Gtk::Button _embed_new_btn; + Gtk::Button _embed_remove_btn; +#if WITH_GTKMM_3_0 + Gtk::ButtonBox _embed_button_box; +#else + Gtk::HButtonBox _embed_button_box; +#endif + class ExternalScriptsColumns : public Gtk::TreeModel::ColumnRecord { public: @@ -175,6 +205,9 @@ protected: Gtk::HBox _grids_space; //--------------------------------------------------------------- + RDElist _rdflist; + UI::Widget::Licensor _licensor; + Gtk::HBox& _createPageTabLabel(const Glib::ustring& label, const char *label_image); private: @@ -184,6 +217,9 @@ private: // callback methods for buttons on grids page. void onNewGrid(); void onRemoveGrid(); + + // callback for document unit change + void onDocUnitChange(); }; } // namespace Dialog diff --git a/src/ui/dialog/export.cpp b/src/ui/dialog/export.cpp index e10668473..913713e5c 100644 --- a/src/ui/dialog/export.cpp +++ b/src/ui/dialog/export.cpp @@ -1,11 +1,8 @@ -/** - * @file - * PNG export dialog. - */ /* Authors: * Lauris Kaplinski <lauris@kaplinski.com> * bulia byak <buliabyak@users.sf.net> * Johan Engelen <j.b.c.engelen@ewi.utwente.nl> + * Peter Bostrom * Jon A. Cruz <jon@joncruz.org> * Abhishek Sharma * Kris De Gussem <Kris.DeGussem@gmail.com> @@ -23,24 +20,36 @@ // This has to be included prior to anything that includes setjmp.h, it croaks otherwise #include <png.h> +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> #include <gtkmm/buttonbox.h> -#include <gtkmm/label.h> -#include <gtkmm/widget.h> -#include <gtkmm/togglebutton.h> +#include <gtkmm/dialog.h> #include <gtkmm/entry.h> #include <gtkmm/image.h> -#include <gtkmm/stockid.h> +#include <gtkmm/label.h> +#include <gtkmm/spinbutton.h> #include <gtkmm/stock.h> -#include <gtkmm/table.h> +#include <gtkmm/stockid.h> +#if WITH_GTKMM_3_0 +# include <gtkmm/grid.h> +#else +# include <gtkmm/table.h> +#endif +#include <gtkmm/togglebutton.h> +#include <gtkmm/widget.h> + #ifdef WITH_GNOME_VFS # include <libgnomevfs/gnome-vfs-init.h> // gnome_vfs_initialized #endif #include <glibmm/i18n.h> -#include "helper/unit-menu.h" -#include "helper/units.h" -#include "unit-constants.h" +#include <glibmm/miscutils.h> + +#include "ui/widget/unit-menu.h" +#include "util/units.h" #include "helper/window.h" #include "inkscape-private.h" #include "document.h" @@ -66,17 +75,29 @@ #include "helper/png-write.h" +#if WITH_EXT_GDL +#include <gdl/gdl-dock-item.h> +#else +#include "libgdl/gdl-dock-item.h" +#endif + + +// required to set status message after export +#include "desktop.h" +#include "message-stack.h" + #ifdef WIN32 #include <windows.h> #include <commdlg.h> #include <gdk/gdkwin32.h> +#include <glibmm/fileutils.h> #endif #include <gtk/gtk.h> #define SP_EXPORT_MIN_SIZE 1.0 -#define DPI_BASE PX_PER_IN +#define DPI_BASE Inkscape::Util::Quantity::convert(1, "in", "px") #define EXPORT_COORD_PRECISION 3 @@ -86,11 +107,51 @@ #include "verbs.h" #include "export.h" +using Inkscape::Util::unit_table; + +namespace { + +class MessageCleaner +{ +public: + MessageCleaner(Inkscape::MessageId messageId, SPDesktop *desktop) : + _desktop(desktop), + _messageId(messageId) + { + } + + ~MessageCleaner() + { + if (_messageId && _desktop) { + _desktop->messageStack()->cancel(_messageId); + } + } + +private: + MessageCleaner(MessageCleaner const &other); + MessageCleaner &operator=(MessageCleaner const &other); + + SPDesktop *_desktop; + Inkscape::MessageId _messageId; +}; + +} // namespace namespace Inkscape { namespace UI { namespace Dialog { +/** A list of strings that is used both in the preferences, and in the + data fields to describe the various values of \c selection_type. */ +static const char * selection_names[SELECTION_NUMBER_OF] = { + "page", "drawing", "selection", "custom" +}; + +/** The names on the buttons for the various selection types. */ +static const char * selection_labels[SELECTION_NUMBER_OF] = { + N_("_Page"), N_("_Drawing"), N_("_Selection"), N_("_Custom") +}; + Export::Export (void) : UI::Widget::Panel ("", "/dialogs/export/", SP_VERB_DIALOG_EXPORT), current_key(SELECTION_PAGE), @@ -105,17 +166,20 @@ Export::Export (void) : size_box(false, 3), file_box(false, 3), unitbox(false, 0), + unit_selector(), units_label(_("Units:")), filename_box(false, 5), - browse_label(_("_Browse..."), 1), + browse_label(_("_Export As..."), 1), browse_image(Gtk::StockID(Gtk::Stock::INDEX), Gtk::ICON_SIZE_BUTTON), batch_box(false, 5), batch_export(_("B_atch export all selected objects"), _("Export each selected object into its own PNG file, using export hints if any (caution, overwrites without asking!)")), hide_box(false, 5), hide_export(_("Hide a_ll except selected"), _("In the exported image, hide all objects except those that are selected")), - button_box(Gtk::BUTTONBOX_END), + closeWhenDone(_("Close when complete"), _("Once the export completes, close this dialog")), + button_box(false, 3), export_label(_("_Export"), 1), export_image(Gtk::StockID(Gtk::Stock::APPLY), Gtk::ICON_SIZE_BUTTON), + _prog(), prog_dlg(NULL), interrupted(false), prefs(NULL), @@ -131,23 +195,21 @@ Export::Export (void) : /* Export area frame */ { - - #if WITH_GTKMM_2_22 - Gtk::Label* lbl = new Gtk::Label(_("<big><b>Export area</b></big>"), Gtk::ALIGN_START); - #else - Gtk::Label* lbl = new Gtk::Label(_("<big><b>Export area</b></big>"), Gtk::ALIGN_LEFT); - #endif + Gtk::Label* lbl = new Gtk::Label(_("<b>Export area</b>"), Gtk::ALIGN_START); lbl->set_use_markup(true); area_box.pack_start(*lbl); /* Units box */ /* gets added to the vbox later, but the unit selector is needed earlier than that */ - unit_selector = Glib::wrap(sp_unit_selector_new (SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE)); + unit_selector.setUnitType(Inkscape::Util::UNIT_TYPE_LINEAR); + SPDesktop *desktop = SP_ACTIVE_DESKTOP; - if (desktop) - sp_unit_selector_set_unit (SP_UNIT_SELECTOR(unit_selector->gobj()), sp_desktop_namedview(desktop)->doc_units); - unitbox.pack_end(*unit_selector, false, false, 0); + if (desktop) { + unit_selector.setUnit(sp_desktop_namedview(desktop)->doc_units->abbr); + } + unitChangedConn = unit_selector.signal_changed().connect(sigc::mem_fun(*this, &Export::onUnitChanged)); + unitbox.pack_end(unit_selector, false, false, 0); unitbox.pack_end(units_label, false, false, 3); for (int i = 0; i < SELECTION_NUMBER_OF; i++) { @@ -161,33 +223,39 @@ Export::Export (void) : selectiontype_buttons[i]->signal_clicked().connect(sigc::mem_fun(*this, &Export::onAreaToggled)); } - Gtk::Table* t = new Gtk::Table(2, 6, false); +#if WITH_GTKMM_3_0 + Gtk::Grid* t = new Gtk::Grid(); + t->set_row_spacing(4); + t->set_column_spacing(4); +#else + Gtk::Table* t = new Gtk::Table(3, 4, false); t->set_row_spacings (4); t->set_col_spacings (4); +#endif - x0_adj = createSpinbutton ( "x0", 0.0, -1000000.0, 1000000.0, 0.1, 1.0, unit_selector->gobj(), - t, 0, 0, _("_x0:"), "", EXPORT_COORD_PRECISION, 1, - &Export::onAreaX0Change); + x0_adj = createSpinbutton ( "x0", 0.0, -1000000.0, 1000000.0, 0.1, 1.0, + t, 0, 0, _("_x0:"), "", EXPORT_COORD_PRECISION, 1, + &Export::onAreaX0Change); - x1_adj = createSpinbutton ( "x1", 0.0, -1000000.0, 1000000.0, 0.1, 1.0, unit_selector->gobj(), - t, 2, 0, _("x_1:"), "", EXPORT_COORD_PRECISION, 1, - &Export::onAreaX1Change); + x1_adj = createSpinbutton ( "x1", 0.0, -1000000.0, 1000000.0, 0.1, 1.0, + t, 0, 1, _("x_1:"), "", EXPORT_COORD_PRECISION, 1, + &Export::onAreaX1Change); width_adj = createSpinbutton ( "width", 0.0, 0.0, PNG_UINT_31_MAX, 0.1, 1.0, - unit_selector->gobj(), t, 4, 0, _("Wid_th:"), "", EXPORT_COORD_PRECISION, 1, - &Export::onAreaWidthChange); + t, 0, 2, _("Wid_th:"), "", EXPORT_COORD_PRECISION, 1, + &Export::onAreaWidthChange); - y0_adj = createSpinbutton ( "y0", 0.0, -1000000.0, 1000000.0, 0.1, 1.0, unit_selector->gobj(), - t, 0, 1, _("_y0:"), "", EXPORT_COORD_PRECISION, 1, - &Export::onAreaY0Change); + y0_adj = createSpinbutton ( "y0", 0.0, -1000000.0, 1000000.0, 0.1, 1.0, + t, 2, 0, _("_y0:"), "", EXPORT_COORD_PRECISION, 1, + &Export::onAreaY0Change); - y1_adj = createSpinbutton ( "y1", 0.0, -1000000.0, 1000000.0, 0.1, 1.0, unit_selector->gobj(), - t, 2, 1, _("y_1:"), "", EXPORT_COORD_PRECISION, 1, - &Export::onAreaY1Change); + y1_adj = createSpinbutton ( "y1", 0.0, -1000000.0, 1000000.0, 0.1, 1.0, + t, 2, 1, _("y_1:"), "", EXPORT_COORD_PRECISION, 1, + &Export::onAreaY1Change); height_adj = createSpinbutton ( "height", 0.0, 0.0, PNG_UINT_31_MAX, 0.1, 1.0, - unit_selector->gobj(), t, 4, 1, _("Hei_ght:"), "", EXPORT_COORD_PRECISION, 1, - &Export::onAreaHeightChange); + t, 2, 2, _("Hei_ght:"), "", EXPORT_COORD_PRECISION, 1, + &Export::onAreaHeightChange); area_box.pack_start(togglebox, false, false, 3); area_box.pack_start(*t, false, false, 0); @@ -201,41 +269,44 @@ Export::Export (void) : /* Bitmap size frame */ { size_box.set_border_width(3); - -#if WITH_GTKMM_2_22 - bm_label = new Gtk::Label(_("<big><b>Bitmap size</b></big>"), Gtk::ALIGN_START); -#else - bm_label = new Gtk::Label(_("<big><b>Bitmap size</b></big>"), Gtk::ALIGN_LEFT); -#endif + bm_label = new Gtk::Label(_("<b>Image size</b>"), Gtk::ALIGN_START); bm_label->set_use_markup(true); size_box.pack_start(*bm_label, false, false, 0); + +#if WITH_GTKMM_3_0 + Gtk::Grid *t = new Gtk::Grid(); + t->set_row_spacing(4); + t->set_column_spacing(4); +#else Gtk::Table *t = new Gtk::Table(2, 5, false); t->set_row_spacings (4); t->set_col_spacings (4); +#endif + size_box.pack_start(*t); bmwidth_adj = createSpinbutton ( "bmwidth", 16.0, 1.0, 1000000.0, 1.0, 10.0, - NULL, t, 0, 0, - _("_Width:"), _("pixels at"), 0, 1, - &Export::onBitmapWidthChange); + t, 0, 0, + _("_Width:"), _("pixels at"), 0, 1, + &Export::onBitmapWidthChange); xdpi_adj = createSpinbutton ( "xdpi", - prefs->getDouble("/dialogs/export/defaultxdpi/value", DPI_BASE), - 0.01, 100000.0, 0.1, 1.0, NULL, t, 3, 0, - "", _("dp_i"), 2, 1, - &Export::onExportXdpiChange); + prefs->getDouble("/dialogs/export/defaultxdpi/value", DPI_BASE), + 0.01, 100000.0, 0.1, 1.0, t, 3, 0, + "", _("dp_i"), 2, 1, + &Export::onExportXdpiChange); bmheight_adj = createSpinbutton ( "bmheight", 16.0, 1.0, 1000000.0, 1.0, 10.0, - NULL, t, 0, 1, - _("_Height:"), _("pixels at"), 0, 1, - &Export::onBitmapHeightChange); + t, 0, 1, + _("_Height:"), _("pixels at"), 0, 1, + &Export::onBitmapHeightChange); /** TODO * There's no way to set ydpi currently, so we use the defaultxdpi value here, too... */ ydpi_adj = createSpinbutton ( "ydpi", prefs->getDouble("/dialogs/export/defaultxdpi/value", DPI_BASE), - 0.01, 100000.0, 0.1, 1.0, NULL, t, 3, 1, - "", _("dpi"), 2, 0, NULL ); + 0.01, 100000.0, 0.1, 1.0, t, 3, 1, + "", _("dpi"), 2, 0, NULL ); singleexport_box.pack_start(size_box); } @@ -243,12 +314,7 @@ Export::Export (void) : /* File entry */ { file_box.set_border_width(3); - -#if WITH_GTKMM_2_22 - flabel = new Gtk::Label(_("<big><b>_Filename</b></big>"), Gtk::ALIGN_START, Gtk::ALIGN_CENTER, true); -#else - flabel = new Gtk::Label(_("<big><b>_Filename</b></big>"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, true); -#endif + flabel = new Gtk::Label(_("<b>_Filename</b>"), Gtk::ALIGN_START, Gtk::ALIGN_CENTER, true); flabel->set_use_markup(true); file_box.pack_start(*flabel, false, false, 0); @@ -279,8 +345,10 @@ Export::Export (void) : batch_box.pack_start(batch_export, false, false); hide_export.set_sensitive(true); + hide_export.set_active (prefs->getBool("/dialogs/export/hideexceptselected/value", false)); hide_box.pack_start(hide_export, false, false); + /* Export Button row */ button_box.set_border_width(3); Gtk::HBox* export_image_label = new Gtk::HBox(false, 3); @@ -289,8 +357,9 @@ Export::Export (void) : export_button.add(*export_image_label); export_button.set_tooltip_text (_("Export the bitmap file with these settings")); - button_box.pack_end(export_button, false, false, 0); + button_box.pack_start(closeWhenDone, true, true, 0 ); + button_box.pack_end(export_button, false, false, 0); /* Main dialog */ Gtk::Box *contents = _getContents(); @@ -298,7 +367,8 @@ Export::Export (void) : contents->pack_start(singleexport_box); contents->pack_start(batch_box); contents->pack_start(hide_box); - contents->pack_end(button_box, false, false, 0); + contents->pack_end(button_box, false, 0); + contents->pack_end(_prog, Gtk::PACK_EXPAND_WIDGET); /* Signal handlers */ filename_entry.signal_changed().connect( sigc::mem_fun(*this, &Export::onFilenameModified) ); @@ -307,11 +377,13 @@ Export::Export (void) : browse_button.signal_clicked().connect(sigc::mem_fun(*this, &Export::onBrowse)); batch_export.signal_clicked().connect(sigc::mem_fun(*this, &Export::onBatchClicked)); export_button.signal_clicked().connect(sigc::mem_fun(*this, &Export::onExport)); + hide_export.signal_clicked().connect(sigc::mem_fun(*this, &Export::onHideExceptSelected)); desktopChangeConn = deskTrack.connectDesktopChanged( sigc::mem_fun(*this, &Export::setTargetDesktop) ); deskTrack.connect(GTK_WIDGET(gobj())); show_all_children(); + setExporting(false); findDefaultSelection(); onAreaToggled(); @@ -370,7 +442,6 @@ void Export::set_default_filename () { if ( SP_ACTIVE_DOCUMENT && SP_ACTIVE_DOCUMENT->getURI() ) { - gchar *name; SPDocument * doc = SP_ACTIVE_DOCUMENT; const gchar *uri = doc->getURI(); const gchar *text_extension = get_file_save_extension (Inkscape::Extension::FILE_SAVE_METHOD_SAVE_AS).c_str(); @@ -393,13 +464,16 @@ void Export::set_default_filename () { final_name = g_strconcat(uri_copy, ".png", NULL); filename_entry.set_text(final_name); + filename_entry.set_position(strlen(final_name)); g_free(final_name); g_free(uri_copy); } } else { - name = g_strconcat(uri, ".png", NULL); + gchar *name = g_strconcat(uri, ".png", NULL); filename_entry.set_text(name); + filename_entry.set_position(strlen(name)); + g_free(name); } @@ -410,18 +484,18 @@ void Export::set_default_filename () { #if WITH_GTKMM_3_0 Glib::RefPtr<Gtk::Adjustment> Export::createSpinbutton( gchar const * /*key*/, float val, float min, float max, - float step, float page, GtkWidget *us, - Gtk::Table *t, int x, int y, - const Glib::ustring ll, const Glib::ustring lr, - int digits, unsigned int sensitive, - void (Export::*cb)() ) + float step, float page, + Gtk::Grid *t, int x, int y, + const Glib::ustring& ll, const Glib::ustring& lr, + int digits, unsigned int sensitive, + void (Export::*cb)() ) #else Gtk::Adjustment * Export::createSpinbutton( gchar const * /*key*/, float val, float min, float max, - float step, float page, GtkWidget *us, - Gtk::Table *t, int x, int y, - const Glib::ustring ll, const Glib::ustring lr, - int digits, unsigned int sensitive, - void (Export::*cb)() ) + float step, float page, + Gtk::Table *t, int x, int y, + const Glib::ustring& ll, const Glib::ustring& lr, + int digits, unsigned int sensitive, + void (Export::*cb)() ) #endif { #if WITH_GTKMM_3_0 @@ -429,9 +503,6 @@ Gtk::Adjustment * Export::createSpinbutton( gchar const * /*key*/, float val, fl #else Gtk::Adjustment *adj = new Gtk::Adjustment ( val, min, max, step, page, 0 ); #endif - if (us) { - sp_unit_selector_add_adjustment ( SP_UNIT_SELECTOR (us), GTK_ADJUSTMENT (adj->gobj()) ); - } int pos = 0; Gtk::Label *l = NULL; @@ -439,27 +510,49 @@ Gtk::Adjustment * Export::createSpinbutton( gchar const * /*key*/, float val, fl if (!ll.empty()) { l = new Gtk::Label(ll,true); l->set_alignment (1.0, 0.5); + +#if WITH_GTKMM_3_0 + l->set_hexpand(); + l->set_vexpand(); + t->attach(*l, x + pos, y, 1, 1); +#else t->attach (*l, x + pos, x + pos + 1, y, y + 1, Gtk::EXPAND, Gtk::EXPAND, 0, 0 ); +#endif + l->set_sensitive(sensitive); pos++; } #if WITH_GTKMM_3_0 Gtk::SpinButton *sb = new Gtk::SpinButton(adj, 1.0, digits); + sb->set_hexpand(); + sb->set_vexpand(); + t->attach(*sb, x + pos, y, 1, 1); #else Gtk::SpinButton *sb = new Gtk::SpinButton(*adj, 1.0, digits); -#endif t->attach (*sb, x + pos, x + pos + 1, y, y + 1, Gtk::EXPAND, Gtk::EXPAND, 0, 0 ); - sb->set_size_request (80, -1); +#endif + + sb->set_width_chars(7); sb->set_sensitive (sensitive); pos++; - if (!ll.empty()) { l->set_mnemonic_widget(*sb);} + if (!ll.empty()) { + l->set_mnemonic_widget(*sb); + } if (!lr.empty()) { l = new Gtk::Label(lr,true); l->set_alignment (0.0, 0.5); + +#if WITH_GTKMM_3_0 + l->set_hexpand(); + l->set_vexpand(); + t->attach(*l, x + pos, y, 1, 1); +#else t->attach (*l, x + pos, x + pos + 1, y, y + 1, Gtk::EXPAND, Gtk::EXPAND, 0, 0 ); +#endif + l->set_sensitive (sensitive); pos++; l->set_mnemonic_widget (*sb); @@ -476,7 +569,7 @@ Gtk::Adjustment * Export::createSpinbutton( gchar const * /*key*/, float val, fl Glib::ustring Export::create_filepath_from_id (Glib::ustring id, const Glib::ustring &file_entry_text) { if (id.empty()) - { /* This should never happen */ + { /* This should never happen */ id = "bitmap"; } @@ -521,11 +614,8 @@ void Export::updateCheckbuttons () batch_export.set_active (false); batch_export.set_sensitive(false); } - if (num > 0) { - hide_export.set_sensitive(true); - } else { - hide_export.set_sensitive(false); - } + + //hide_export.set_sensitive (num > 0); } inline void Export::findDefaultSelection() @@ -592,35 +682,35 @@ void Export::onSelectionModified ( guint /*flags*/ ) { Inkscape::Selection * Sel; switch (current_key) { - case SELECTION_DRAWING: - if ( SP_ACTIVE_DESKTOP ) { - SPDocument *doc; - doc = sp_desktop_document (SP_ACTIVE_DESKTOP); - Geom::OptRect bbox = doc->getRoot()->desktopVisualBounds(); - if (bbox) { - setArea ( bbox->left(), - bbox->top(), - bbox->right(), - bbox->bottom()); - } + case SELECTION_DRAWING: + if ( SP_ACTIVE_DESKTOP ) { + SPDocument *doc; + doc = sp_desktop_document (SP_ACTIVE_DESKTOP); + Geom::OptRect bbox = doc->getRoot()->desktopVisualBounds(); + if (bbox) { + setArea ( bbox->left(), + bbox->top(), + bbox->right(), + bbox->bottom()); } - break; - case SELECTION_SELECTION: - Sel = sp_desktop_selection(SP_ACTIVE_DESKTOP); - if (Sel->isEmpty() == false) { - Geom::OptRect bbox = Sel->visualBounds(); - if (bbox) - { - setArea ( bbox->left(), - bbox->top(), - bbox->right(), - bbox->bottom()); - } + } + break; + case SELECTION_SELECTION: + Sel = sp_desktop_selection(SP_ACTIVE_DESKTOP); + if (Sel->isEmpty() == false) { + Geom::OptRect bbox = Sel->visualBounds(); + if (bbox) + { + setArea ( bbox->left(), + bbox->top(), + bbox->right(), + bbox->bottom()); } - break; - default: - /* Do nothing for page or for custom */ - break; + } + break; + default: + /* Do nothing for page or for custom */ + break; } return; @@ -652,39 +742,39 @@ void Export::onAreaToggled () various backups. If you modify this without noticing you'll probabaly screw something up. */ switch (key) { - case SELECTION_SELECTION: - if ((sp_desktop_selection(SP_ACTIVE_DESKTOP))->isEmpty() == false) - { - bbox = sp_desktop_selection (SP_ACTIVE_DESKTOP)->visualBounds(); - /* Only if there is a selection that we can set - do we break, otherwise we fall through to the - drawing */ - // std::cout << "Using selection: SELECTION" << std::endl; - key = SELECTION_SELECTION; - break; - } - case SELECTION_DRAWING: - /** \todo - * This returns wrong values if the document has a viewBox. - */ - bbox = doc->getRoot()->desktopVisualBounds(); - /* If the drawing is valid, then we'll use it and break - otherwise we drop through to the page settings */ - if (bbox) { - // std::cout << "Using selection: DRAWING" << std::endl; - key = SELECTION_DRAWING; - break; - } - case SELECTION_PAGE: - bbox = Geom::Rect(Geom::Point(0.0, 0.0), - Geom::Point(doc->getWidth(), doc->getHeight())); - - // std::cout << "Using selection: PAGE" << std::endl; - key = SELECTION_PAGE; + case SELECTION_SELECTION: + if ((sp_desktop_selection(SP_ACTIVE_DESKTOP))->isEmpty() == false) + { + bbox = sp_desktop_selection (SP_ACTIVE_DESKTOP)->visualBounds(); + /* Only if there is a selection that we can set + do we break, otherwise we fall through to the + drawing */ + // std::cout << "Using selection: SELECTION" << std::endl; + key = SELECTION_SELECTION; break; - case SELECTION_CUSTOM: - default: + } + case SELECTION_DRAWING: + /** \todo + * This returns wrong values if the document has a viewBox. + */ + bbox = doc->getRoot()->desktopVisualBounds(); + /* If the drawing is valid, then we'll use it and break + otherwise we drop through to the page settings */ + if (bbox) { + // std::cout << "Using selection: DRAWING" << std::endl; + key = SELECTION_DRAWING; break; + } + case SELECTION_PAGE: + bbox = Geom::Rect(Geom::Point(0.0, 0.0), + Geom::Point(doc->getWidth().value("px"), doc->getHeight().value("px"))); + + // std::cout << "Using selection: PAGE" << std::endl; + key = SELECTION_PAGE; + break; + case SELECTION_CUSTOM: + default: + break; } // switch current_key = key; @@ -694,9 +784,9 @@ void Export::onAreaToggled () if ( key != SELECTION_CUSTOM && bbox ) { setArea ( bbox->min()[Geom::X], - bbox->min()[Geom::Y], - bbox->max()[Geom::X], - bbox->max()[Geom::Y]); + bbox->min()[Geom::Y], + bbox->max()[Geom::X], + bbox->max()[Geom::Y]); } } // end of if ( SP_ACTIVE_DESKTOP ) @@ -707,48 +797,49 @@ void Export::onAreaToggled () float xdpi = 0.0, ydpi = 0.0; switch (key) { - case SELECTION_PAGE: - case SELECTION_DRAWING: { - SPDocument * doc = SP_ACTIVE_DOCUMENT; - sp_document_get_export_hints (doc, filename, &xdpi, &ydpi); - - if (filename.empty()) { - if (!doc_export_name.empty()) { - filename = doc_export_name; - } + case SELECTION_PAGE: + case SELECTION_DRAWING: { + SPDocument * doc = SP_ACTIVE_DOCUMENT; + sp_document_get_export_hints (doc, filename, &xdpi, &ydpi); + + if (filename.empty()) { + if (!doc_export_name.empty()) { + filename = doc_export_name; } - break; } - case SELECTION_SELECTION: - if ((sp_desktop_selection(SP_ACTIVE_DESKTOP))->isEmpty() == false) { - - sp_selection_get_export_hints (sp_desktop_selection(SP_ACTIVE_DESKTOP), filename, &xdpi, &ydpi); - - /* If we still don't have a filename -- let's build - one that's nice */ - if (filename.empty()) { - const gchar * id = NULL; - const GSList * reprlst = sp_desktop_selection(SP_ACTIVE_DESKTOP)->reprList(); - for(; reprlst != NULL; reprlst = reprlst->next) { - Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data; - if (repr->attribute("id")) { - id = repr->attribute("id"); - break; - } - } + break; + } + case SELECTION_SELECTION: + if ((sp_desktop_selection(SP_ACTIVE_DESKTOP))->isEmpty() == false) { - filename = create_filepath_from_id (id, filename_entry.get_text()); + sp_selection_get_export_hints (sp_desktop_selection(SP_ACTIVE_DESKTOP), filename, &xdpi, &ydpi); + + /* If we still don't have a filename -- let's build + one that's nice */ + if (filename.empty()) { + const gchar * id = "object"; + const GSList * reprlst = sp_desktop_selection(SP_ACTIVE_DESKTOP)->reprList(); + for(; reprlst != NULL; reprlst = reprlst->next) { + Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data; + if (repr->attribute("id")) { + id = repr->attribute("id"); + break; + } } + + filename = create_filepath_from_id (id, filename_entry.get_text()); } - break; - case SELECTION_CUSTOM: - default: - break; + } + break; + case SELECTION_CUSTOM: + default: + break; } if (!filename.empty()) { original_name = filename; filename_entry.set_text(filename); + filename_entry.set_position(filename.length()); } if (xdpi != 0.0) { @@ -782,32 +873,62 @@ void Export::onProgressCancel () /// Called for every progress iteration -unsigned int Export::onProgressCallback (float value, void *dlg) +unsigned int Export::onProgressCallback(float value, void *dlg) { Gtk::Dialog *dlg2 = reinterpret_cast<Gtk::Dialog*>(dlg); - if (dlg2->get_data("cancel")){ + if (dlg2->get_data("cancel")) { return FALSE; } - Gtk::ProgressBar *prg = (Gtk::ProgressBar *) dlg2->get_data ("progress"); + gint current = GPOINTER_TO_INT(dlg2->get_data("current")); + gint total = GPOINTER_TO_INT(dlg2->get_data("total")); + if (total > 0) { + double completed = current; + completed /= static_cast<double>(total); + + value = completed + (value / static_cast<double>(total)); + } + + Gtk::ProgressBar *prg = reinterpret_cast<Gtk::ProgressBar *>(dlg2->get_data("progress")); prg->set_fraction(value); + Export *self = reinterpret_cast<Export *>(dlg2->get_data("exportPanel")); + if (self) { + self->_prog.set_fraction(value); + } + int evtcount = 0; - while ((evtcount < 16) && gdk_events_pending ()) { - gtk_main_iteration_do (FALSE); - evtcount += 1; + while ((evtcount < 16) && gdk_events_pending()) { + gtk_main_iteration_do(FALSE); + evtcount += 1; } - gtk_main_iteration_do (FALSE); + gtk_main_iteration_do(FALSE); return TRUE; } // end of sp_export_progress_callback() +void Export::setExporting(bool exporting, Glib::ustring const &text) +{ + if (exporting) { + _prog.set_text(text); + _prog.set_fraction(0.0); + _prog.set_sensitive(true); + + export_button.set_sensitive(false); + } else { + _prog.set_text(""); + _prog.set_fraction(0.0); + _prog.set_sensitive(false); + + export_button.set_sensitive(true); + } +} + Gtk::Dialog * Export::create_progress_dialog (Glib::ustring progress_text) { Gtk::Dialog *dlg = new Gtk::Dialog(_("Export in progress"), TRUE); - + Gtk::ProgressBar *prg = new Gtk::ProgressBar (); prg->set_text(progress_text); - prg->set_orientation(Gtk::PROGRESS_LEFT_TO_RIGHT); dlg->set_data ("progress", prg); #if GTK_CHECK_VERSION(3,0,0) Gtk::Box* CA = dlg->get_content_area(); @@ -829,7 +950,7 @@ Gtk::Dialog * Export::create_progress_dialog (Glib::ustring progress_text) { Glib::ustring Export::filename_add_extension (Glib::ustring filename, Glib::ustring extension) { Glib::ustring::size_type dot; - + dot = filename.find_last_of("."); if ( !dot ) { @@ -843,7 +964,7 @@ Glib::ustring Export::filename_add_extension (Glib::ustring filename, Glib::ustr } else { - return filename = filename + "." + extension; + return filename = filename + "." + extension; } } } @@ -864,34 +985,53 @@ Glib::ustring Export::absolutize_path_from_document_location (SPDocument *doc, c return path; } +// Called when unit is changed +void Export::onUnitChanged() +{ + onAreaToggled(); +} + +void Export::onHideExceptSelected () +{ + prefs->setBool("/dialogs/export/hideexceptselected/value", hide_export.get_active()); +} + /// Called when export button is clicked void Export::onExport () { - if (!SP_ACTIVE_DESKTOP) return; + SPDesktop *desktop = SP_ACTIVE_DESKTOP; + if (!desktop) return; + + SPNamedView *nv = sp_desktop_namedview(desktop); + SPDocument *doc = sp_desktop_document (desktop); - SPNamedView *nv = sp_desktop_namedview(SP_ACTIVE_DESKTOP); - SPDocument *doc = sp_desktop_document (SP_ACTIVE_DESKTOP); + bool exportSuccessful = false; bool hide = hide_export.get_active (); if (batch_export.get_active ()) { // Batch export of selected objects - gint num = g_slist_length(const_cast<GSList *>(sp_desktop_selection(SP_ACTIVE_DESKTOP)->itemList())); + gint num = g_slist_length(const_cast<GSList *>(sp_desktop_selection(desktop)->itemList())); gint n = 0; - if (num < 1) + if (num < 1) { + desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("No items selected.")); return; + } - prog_dlg = create_progress_dialog (Glib::ustring::compose(_("Exporting %1 files"),num)); + prog_dlg = create_progress_dialog(Glib::ustring::compose(_("Exporting %1 files"), num)); + prog_dlg->set_data("exportPanel", this); + setExporting(true, Glib::ustring::compose(_("Exporting %1 files"), num)); - for (GSList *i = const_cast<GSList *>(sp_desktop_selection(SP_ACTIVE_DESKTOP)->itemList()); - i != NULL; - i = i->next) { - if (interrupted){ - break; - } + gint export_count = 0; + + for (GSList *i = const_cast<GSList *>(sp_desktop_selection(desktop)->itemList()); i && !interrupted; i = i->next) { SPItem *item = reinterpret_cast<SPItem *>(i->data); + prog_dlg->set_data("current", GINT_TO_POINTER(n)); + prog_dlg->set_data("total", GINT_TO_POINTER(num)); + onProgressCallback(0.0, prog_dlg); + // retrieve export filename hint const gchar *filename = item->getRepr()->attribute("inkscape:export-filename"); Glib::ustring path; @@ -909,47 +1049,63 @@ void Export::onExport () dpi = atof(dpi_hint); } if (dpi == 0.0) { - dpi = DPI_BASE; + dpi = getValue(xdpi_adj); } Geom::OptRect area = item->desktopVisualBounds(); if (area) { - gint width = (gint) (area->width() * dpi / PX_PER_IN + 0.5); - gint height = (gint) (area->height() * dpi / PX_PER_IN + 0.5); + gint width = (gint) (area->width() * dpi / DPI_BASE + 0.5); + gint height = (gint) (area->height() * dpi / DPI_BASE + 0.5); if (width > 1 && height > 1) { - /* Do export */ + // Do export + gchar * safeFile = Inkscape::IO::sanitizeString(path.c_str()); + MessageCleaner msgCleanup(desktop->messageStack()->pushF(Inkscape::IMMEDIATE_MESSAGE, + _("Exporting file <b>%s</b>..."), safeFile), desktop); + MessageCleaner msgFlashCleanup(desktop->messageStack()->flashF(Inkscape::IMMEDIATE_MESSAGE, + _("Exporting file <b>%s</b>..."), safeFile), desktop); + if (!sp_export_png_file (doc, path.c_str(), *area, width, height, dpi, dpi, nv->pagecolor, - NULL, NULL, TRUE, // overwrite without asking - hide ? const_cast<GSList *>(sp_desktop_selection(SP_ACTIVE_DESKTOP)->itemList()) : NULL - )) { - gchar * error; - gchar * safeFile = Inkscape::IO::sanitizeString(path.c_str()); - error = g_strdup_printf(_("Could not export to filename %s.\n"), safeFile); + onProgressCallback, (void*)prog_dlg, + TRUE, // overwrite without asking + hide ? const_cast<GSList *>(sp_desktop_selection(desktop)->itemList()) : NULL + )) { + gchar * error = g_strdup_printf(_("Could not export to filename %s.\n"), safeFile); + + desktop->messageStack()->flashF(Inkscape::ERROR_MESSAGE, + _("Could not export to filename <b>%s</b>."), safeFile); + sp_ui_error_dialog(error); - g_free(safeFile); g_free(error); + } else { + ++export_count; // one more item exported successfully } + g_free(safeFile); } } + n++; - onProgressCallback((float)n/num, prog_dlg); } + desktop->messageStack()->flashF(Inkscape::INFORMATION_MESSAGE, + _("Successfully exported <b>%d</b> files from <b>%d</b> selected items."), export_count, num); + + setExporting(false); delete prog_dlg; prog_dlg = NULL; interrupted = false; - + exportSuccessful = (export_count > 0); } else { Glib::ustring filename = filename_entry.get_text(); - if (filename.empty()){ + if (filename.empty()) { + desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You have to enter a filename.")); sp_ui_error_dialog(_("You have to enter a filename")); return; } - + float const x0 = getValuePx(x0_adj); float const y0 = getValuePx(y0_adj); float const x1 = getValuePx(x1_adj); @@ -960,23 +1116,28 @@ void Export::onExport () unsigned long int const height = int(getValue(bmheight_adj) + 0.5); if (!((x1 > x0) && (y1 > y0) && (width > 0) && (height > 0))) { - sp_ui_error_dialog (_("The chosen area to be exported is invalid")); + desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The chosen area to be exported is invalid.")); + sp_ui_error_dialog(_("The chosen area to be exported is invalid")); return; } // make sure that .png is the extension of the file: Glib::ustring const filename_ext = filename_add_extension(filename, "png"); filename_entry.set_text(filename_ext); + filename_entry.set_position(filename_ext.length()); Glib::ustring path = absolutize_path_from_document_location(doc, filename_ext); Glib::ustring dirname = Glib::path_get_dirname(path); if ( dirname.empty() - || !Inkscape::IO::file_test(dirname.c_str(), (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)) ) + || !Inkscape::IO::file_test(dirname.c_str(), (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)) ) { gchar *safeDir = Inkscape::IO::sanitizeString(dirname.c_str()); gchar *error = g_strdup_printf(_("Directory %s does not exist or is not a directory.\n"), safeDir); + + desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, error); sp_ui_error_dialog(error); + g_free(safeDir); g_free(error); return; @@ -984,21 +1145,40 @@ void Export::onExport () Glib::ustring fn = path_get_basename (path); + /* TRANSLATORS: %1 will be the filename, %2 the width, and %3 the height of the image */ prog_dlg = create_progress_dialog (Glib::ustring::compose(_("Exporting %1 (%2 x %3)"), fn, width, height)); + prog_dlg->set_data("exportPanel", this); + setExporting(true, Glib::ustring::compose(_("Exporting %1 (%2 x %3)"), fn, width, height)); + + prog_dlg->set_data("current", GINT_TO_POINTER(0)); + prog_dlg->set_data("total", GINT_TO_POINTER(0)); /* Do export */ - if (!sp_export_png_file (sp_desktop_document (SP_ACTIVE_DESKTOP), path.c_str(), - Geom::Rect(Geom::Point(x0, y0), Geom::Point(x1, y1)), width, height, xdpi, ydpi, - nv->pagecolor, - onProgressCallback, (void*)prog_dlg, FALSE, - hide ? const_cast<GSList *>(sp_desktop_selection(SP_ACTIVE_DESKTOP)->itemList()) : NULL - )) { - gchar * error; + ExportResult status = sp_export_png_file(sp_desktop_document(desktop), path.c_str(), + Geom::Rect(Geom::Point(x0, y0), Geom::Point(x1, y1)), width, height, xdpi, ydpi, + nv->pagecolor, + onProgressCallback, (void*)prog_dlg, + FALSE, + hide ? const_cast<GSList *>(sp_desktop_selection(desktop)->itemList()) : NULL + ); + if (status == EXPORT_ERROR) { gchar * safeFile = Inkscape::IO::sanitizeString(path.c_str()); - error = g_strdup_printf(_("Could not export to filename %s.\n"), safeFile); + gchar * error = g_strdup_printf(_("Could not export to filename %s.\n"), safeFile); + + desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, error); sp_ui_error_dialog(error); + g_free(safeFile); g_free(error); + } else if (status == EXPORT_OK) { + exportSuccessful = true; + gchar *safeFile = Inkscape::IO::sanitizeString(path.c_str()); + + desktop->messageStack()->flashF(Inkscape::INFORMATION_MESSAGE, _("Drawing exported to <b>%s</b>."), safeFile); + + g_free(safeFile); + } else { + desktop->messageStack()->flash(Inkscape::INFORMATION_MESSAGE, _("Export aborted.")); } /* Reset the filename so that it can be changed again by changing @@ -1006,25 +1186,72 @@ void Export::onExport () original_name = filename_ext; filename_modified = false; + setExporting(false); delete prog_dlg; prog_dlg = NULL; interrupted = false; /* Setup the values in the document */ switch (current_key) { - case SELECTION_PAGE: - case SELECTION_DRAWING: { - SPDocument * doc = SP_ACTIVE_DOCUMENT; - Inkscape::XML::Node * repr = doc->getReprRoot(); - bool modified = false; - - bool saved = DocumentUndo::getUndoSensitive(doc); - DocumentUndo::setUndoSensitive(doc, false); - - gchar const *temp_string = repr->attribute("inkscape:export-filename"); - if (temp_string == NULL || (filename_ext != temp_string)) { - repr->setAttribute("inkscape:export-filename", filename_ext.c_str()); - modified = true; + case SELECTION_PAGE: + case SELECTION_DRAWING: { + SPDocument * doc = SP_ACTIVE_DOCUMENT; + Inkscape::XML::Node * repr = doc->getReprRoot(); + bool modified = false; + + bool saved = DocumentUndo::getUndoSensitive(doc); + DocumentUndo::setUndoSensitive(doc, false); + + gchar const *temp_string = repr->attribute("inkscape:export-filename"); + if (temp_string == NULL || (filename_ext != temp_string)) { + repr->setAttribute("inkscape:export-filename", filename_ext.c_str()); + modified = true; + } + temp_string = repr->attribute("inkscape:export-xdpi"); + if (temp_string == NULL || xdpi != atof(temp_string)) { + sp_repr_set_svg_double(repr, "inkscape:export-xdpi", xdpi); + modified = true; + } + temp_string = repr->attribute("inkscape:export-ydpi"); + if (temp_string == NULL || ydpi != atof(temp_string)) { + sp_repr_set_svg_double(repr, "inkscape:export-ydpi", ydpi); + modified = true; + } + DocumentUndo::setUndoSensitive(doc, saved); + + if (modified) { + doc->setModifiedSinceSave(); + } + break; + } + case SELECTION_SELECTION: { + const GSList * reprlst; + SPDocument * doc = SP_ACTIVE_DOCUMENT; + bool modified = false; + + bool saved = DocumentUndo::getUndoSensitive(doc); + DocumentUndo::setUndoSensitive(doc, false); + reprlst = sp_desktop_selection(desktop)->reprList(); + + for(; reprlst != NULL; reprlst = reprlst->next) { + Inkscape::XML::Node * repr = static_cast<Inkscape::XML::Node *>(reprlst->data); + const gchar * temp_string; + Glib::ustring dir = Glib::path_get_dirname(filename.c_str()); + const gchar* docURI=SP_ACTIVE_DOCUMENT->getURI(); + Glib::ustring docdir; + if (docURI) + { + docdir = Glib::path_get_dirname(docURI); + } + if (repr->attribute("id") == NULL || + !(filename_ext.find_last_of(repr->attribute("id")) && + ( !docURI || + (dir == docdir)))) { + temp_string = repr->attribute("inkscape:export-filename"); + if (temp_string == NULL || (filename_ext != temp_string)) { + repr->setAttribute("inkscape:export-filename", filename_ext.c_str()); + modified = true; + } } temp_string = repr->attribute("inkscape:export-xdpi"); if (temp_string == NULL || xdpi != atof(temp_string)) { @@ -1036,65 +1263,30 @@ void Export::onExport () sp_repr_set_svg_double(repr, "inkscape:export-ydpi", ydpi); modified = true; } - DocumentUndo::setUndoSensitive(doc, saved); + } + DocumentUndo::setUndoSensitive(doc, saved); - if (modified) { - doc->setModifiedSinceSave(); - } - break; + if (modified) { + doc->setModifiedSinceSave(); } - case SELECTION_SELECTION: { - const GSList * reprlst; - SPDocument * doc = SP_ACTIVE_DOCUMENT; - bool modified = false; - - bool saved = DocumentUndo::getUndoSensitive(doc); - DocumentUndo::setUndoSensitive(doc, false); - reprlst = sp_desktop_selection(SP_ACTIVE_DESKTOP)->reprList(); - - for(; reprlst != NULL; reprlst = reprlst->next) { - Inkscape::XML::Node * repr = static_cast<Inkscape::XML::Node *>(reprlst->data); - const gchar * temp_string; - Glib::ustring dir = Glib::path_get_dirname(filename.c_str()); - const gchar* docURI=SP_ACTIVE_DOCUMENT->getURI(); - Glib::ustring docdir; - if (docURI) - { - docdir = Glib::path_get_dirname(docURI); - } - if (repr->attribute("id") == NULL || - !(filename_ext.find_last_of(repr->attribute("id")) && - ( !docURI || - (dir == docdir)))) { - temp_string = repr->attribute("inkscape:export-filename"); - if (temp_string == NULL || (filename_ext != temp_string)) { - repr->setAttribute("inkscape:export-filename", filename_ext.c_str()); - modified = true; - } - } - temp_string = repr->attribute("inkscape:export-xdpi"); - if (temp_string == NULL || xdpi != atof(temp_string)) { - sp_repr_set_svg_double(repr, "inkscape:export-xdpi", xdpi); - modified = true; - } - temp_string = repr->attribute("inkscape:export-ydpi"); - if (temp_string == NULL || ydpi != atof(temp_string)) { - sp_repr_set_svg_double(repr, "inkscape:export-ydpi", ydpi); - modified = true; - } - } - DocumentUndo::setUndoSensitive(doc, saved); + break; + } + default: + break; + } + } - if (modified) { - doc->setModifiedSinceSave(); + if (exportSuccessful && closeWhenDone.get_active()) { + for ( Gtk::Container *parent = get_parent(); parent; parent = parent->get_parent()) { + if ( GDL_IS_DOCK_ITEM(parent->gobj()) ) { + GdlDockItem *item = GDL_DOCK_ITEM(parent->gobj()); + if (item) { + gdl_dock_item_hide_item(item); } break; } - default: - break; } } - } // end of sp_export_export_clicked() /// Called when Browse button is clicked @@ -1107,8 +1299,8 @@ void Export::onBrowse () fs = gtk_file_chooser_dialog_new (_("Select a filename for exporting"), (GtkWindow*)desktop->getToplevel(), GTK_FILE_CHOOSER_ACTION_SAVE, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, + _("_Cancel"), GTK_RESPONSE_CANCEL, + _("_Save"), GTK_RESPONSE_ACCEPT, NULL ); #ifdef WITH_GNOME_VFS @@ -1141,13 +1333,29 @@ void Export::onBrowse () WCHAR* title_string = (WCHAR*)g_utf8_to_utf16(_("Select a filename for exporting"), -1, NULL, NULL, NULL); WCHAR* extension_string = (WCHAR*)g_utf8_to_utf16("*.png", -1, NULL, NULL, NULL); // Copy the selected file name, converting from UTF-8 to UTF-16 + std::string dirname = Glib::path_get_dirname(filename.raw()); + if ( !Glib::file_test(dirname, Glib::FILE_TEST_EXISTS) || + Glib::file_test(filename, Glib::FILE_TEST_IS_DIR) || + dirname.empty() ) + { + Glib::ustring tmp; + filename = create_filepath_from_id(tmp, tmp); + } WCHAR _filename[_MAX_PATH + 1]; memset(_filename, 0, sizeof(_filename)); gunichar2* utf16_path_string = g_utf8_to_utf16(filename.c_str(), -1, NULL, NULL, NULL); - wcsncpy(_filename, (wchar_t*)utf16_path_string, _MAX_PATH); + wcsncpy(_filename, reinterpret_cast<wchar_t*>(utf16_path_string), _MAX_PATH); g_free(utf16_path_string); - opf.hwndOwner = (HWND)(GDK_WINDOW_HWND(gtk_widget_get_window(GTK_WIDGET(this)))); + SPDesktop *desktop = SP_ACTIVE_DESKTOP; + Glib::RefPtr<const Gdk::Window> parentWindow = desktop->getToplevel()->get_window(); + g_assert(parentWindow->gobj() != NULL); + +#if WITH_GTKMM_3_0 + opf.hwndOwner = (HWND)gdk_win32_window_get_handle((GdkWindow*)parentWindow->gobj()); +#else + opf.hwndOwner = (HWND)gdk_win32_drawable_get_handle((GdkDrawable*)parentWindow->gobj()); +#endif opf.lpstrFilter = filter_string; opf.lpstrCustomFilter = 0; opf.nMaxCustFilter = 0L; @@ -1170,6 +1378,7 @@ void Export::onBrowse () // Copy the selected file name, converting from UTF-16 to UTF-8 gchar *utf8string = g_utf16_to_utf8((const gunichar2*)opf.lpstrFile, _MAX_PATH, NULL, NULL, NULL); filename_entry.set_text(utf8string); + filename_entry.set_position(strlen(utf8string)); g_free(utf8string); } @@ -1185,6 +1394,7 @@ void Export::onBrowse () gchar * utf8file = g_filename_to_utf8( file, -1, NULL, NULL, NULL ); filename_entry.set_text (utf8file); + filename_entry.set_position(strlen(utf8file)); g_free(utf8file); g_free(file); @@ -1201,11 +1411,11 @@ bool Export::bbox_equal(Geom::Rect const &one, Geom::Rect const &two) { double const epsilon = pow(10.0, -EXPORT_COORD_PRECISION); return ( - (fabs(one.min()[Geom::X] - two.min()[Geom::X]) < epsilon) && - (fabs(one.min()[Geom::Y] - two.min()[Geom::Y]) < epsilon) && - (fabs(one.max()[Geom::X] - two.max()[Geom::X]) < epsilon) && - (fabs(one.max()[Geom::Y] - two.max()[Geom::Y]) < epsilon) - ); + (fabs(one.min()[Geom::X] - two.min()[Geom::X]) < epsilon) && + (fabs(one.min()[Geom::Y] - two.min()[Geom::Y]) < epsilon) && + (fabs(one.max()[Geom::X] - two.max()[Geom::X]) < epsilon) && + (fabs(one.max()[Geom::Y] - two.max()[Geom::Y]) < epsilon) + ); } /** @@ -1234,7 +1444,7 @@ void Export::detectSize() { static const selection_type test_order[SELECTION_NUMBER_OF] = {SELECTION_SELECTION, SELECTION_DRAWING, SELECTION_PAGE, SELECTION_CUSTOM}; selection_type this_test[SELECTION_NUMBER_OF + 1]; selection_type key = SELECTION_NUMBER_OF; - + Geom::Point x(getValuePx(x0_adj), getValuePx(y0_adj)); Geom::Point y(getValuePx(x1_adj), @@ -1248,48 +1458,48 @@ void Export::detectSize() { for (int i = 0; i < SELECTION_NUMBER_OF + 1 && - key == SELECTION_NUMBER_OF && - SP_ACTIVE_DESKTOP != NULL; + key == SELECTION_NUMBER_OF && + SP_ACTIVE_DESKTOP != NULL; i++) { switch (this_test[i]) { - case SELECTION_SELECTION: - if ((sp_desktop_selection(SP_ACTIVE_DESKTOP))->isEmpty() == false) { - Geom::OptRect bbox = (sp_desktop_selection (SP_ACTIVE_DESKTOP))->bounds(SPItem::VISUAL_BBOX); + case SELECTION_SELECTION: + if ((sp_desktop_selection(SP_ACTIVE_DESKTOP))->isEmpty() == false) { + Geom::OptRect bbox = (sp_desktop_selection (SP_ACTIVE_DESKTOP))->bounds(SPItem::VISUAL_BBOX); - if ( bbox && bbox_equal(*bbox,current_bbox)) { - key = SELECTION_SELECTION; - } + if ( bbox && bbox_equal(*bbox,current_bbox)) { + key = SELECTION_SELECTION; } - break; - case SELECTION_DRAWING: { - SPDocument *doc = sp_desktop_document (SP_ACTIVE_DESKTOP); + } + break; + case SELECTION_DRAWING: { + SPDocument *doc = sp_desktop_document (SP_ACTIVE_DESKTOP); - Geom::OptRect bbox = doc->getRoot()->desktopVisualBounds(); + Geom::OptRect bbox = doc->getRoot()->desktopVisualBounds(); - if ( bbox && bbox_equal(*bbox,current_bbox) ) { - key = SELECTION_DRAWING; - } - break; + if ( bbox && bbox_equal(*bbox,current_bbox) ) { + key = SELECTION_DRAWING; } + break; + } - case SELECTION_PAGE: { - SPDocument *doc; + case SELECTION_PAGE: { + SPDocument *doc; - doc = sp_desktop_document (SP_ACTIVE_DESKTOP); + doc = sp_desktop_document (SP_ACTIVE_DESKTOP); - Geom::Point x(0.0, 0.0); - Geom::Point y(doc->getWidth(), - doc->getHeight()); - Geom::Rect bbox(x, y); + Geom::Point x(0.0, 0.0); + Geom::Point y(doc->getWidth().value("px"), + doc->getHeight().value("px")); + Geom::Rect bbox(x, y); - if (bbox_equal(bbox,current_bbox)) { - key = SELECTION_PAGE; - } + if (bbox_equal(bbox,current_bbox)) { + key = SELECTION_PAGE; + } - break; - } + break; + } default: - break; + break; } } // std::cout << std::endl; @@ -1317,10 +1527,6 @@ void Export::areaXChange (Gtk::Adjustment *adj) return; } - if (sp_unit_selector_update_test ((SPUnitSelector *)unit_selector->gobj())) { - return; - } - update = true; x0 = getValuePx(x0_adj); @@ -1364,10 +1570,6 @@ void Export::areaYChange (Gtk::Adjustment *adj) return; } - if (sp_unit_selector_update_test ((SPUnitSelector *)unit_selector->gobj())) { - return; - } - update = true; y0 = getValuePx(y0_adj); @@ -1381,7 +1583,7 @@ void Export::areaYChange (Gtk::Adjustment *adj) height = SP_EXPORT_MIN_SIZE; //key = (const gchar *)g_object_get_data(G_OBJECT (adj), "key"); if (adj == y1_adj) { - //if (!strcmp (key, "y0")) { + //if (!strcmp (key, "y0")) { y1 = y0 + height * DPI_BASE / ydpi; setValuePx(y1_adj, y1); } else { @@ -1407,10 +1609,6 @@ void Export::onAreaWidthChange() return; } - if (sp_unit_selector_update_test(reinterpret_cast<SPUnitSelector *>(unit_selector->gobj()))) { - return; - } - update = true; float x0 = getValuePx(x0_adj); @@ -1440,10 +1638,6 @@ void Export::onAreaHeightChange() return; } - if (sp_unit_selector_update_test(reinterpret_cast<SPUnitSelector *>(unit_selector->gobj()))) { - return; - } - update = true; float y0 = getValuePx(y0_adj); @@ -1519,10 +1713,6 @@ void Export::onBitmapWidthChange () return; } - if (sp_unit_selector_update_test ((SPUnitSelector *)unit_selector->gobj())) { - return; - } - update = true; x0 = getValuePx(x0_adj); @@ -1553,10 +1743,6 @@ void Export::onBitmapHeightChange () return; } - if (sp_unit_selector_update_test ((SPUnitSelector *)unit_selector->gobj())) { - return; - } - update = true; y0 = getValuePx(y0_adj); @@ -1613,10 +1799,6 @@ void Export::onExportXdpiChange() return; } - if (sp_unit_selector_update_test ((SPUnitSelector *)unit_selector->gobj())) { - return; - } - update = true; x0 = getValuePx(x0_adj); @@ -1715,9 +1897,9 @@ void Export::setValuePx(Glib::RefPtr<Gtk::Adjustment>& adj, double val) void Export::setValuePx( Gtk::Adjustment *adj, double val) #endif { - const SPUnit *unit = sp_unit_selector_get_unit ((SPUnitSelector *)unit_selector->gobj() ); + Unit const *unit = unit_selector.getUnit(); - setValue(adj, sp_pixels_get_units (val, *unit)); + setValue(adj, Inkscape::Util::Quantity::convert(val, "px", unit)); return; } @@ -1765,9 +1947,9 @@ float Export::getValuePx( Gtk::Adjustment *adj ) #endif { float value = getValue( adj); - const SPUnit *unit = sp_unit_selector_get_unit ((SPUnitSelector *)unit_selector->gobj()); + Unit const *unit = unit_selector.getUnit(); - return sp_units_get_pixels (value, *unit); + return Inkscape::Util::Quantity::convert(value, unit, "px"); } // end of sp_export_value_get_px() /** diff --git a/src/ui/dialog/export.h b/src/ui/dialog/export.h index 5e421c66b..6f3c0dfac 100644 --- a/src/ui/dialog/export.h +++ b/src/ui/dialog/export.h @@ -1,6 +1,3 @@ -/** @file - * @brief export to bitmap dialog - */ /* Authors: * Lauris Kaplinski <lauris@kaplinski.com> * bulia byak <buliabyak@users.sf.net> @@ -17,23 +14,27 @@ #include <gtk/gtk.h> #include <glibmm/i18n.h> + +#include <gtkmm/comboboxtext.h> #include <gtkmm/expander.h> #include <gtkmm/frame.h> +#include <gtkmm/progressbar.h> #include <gtkmm/textview.h> -#include <gtkmm/comboboxtext.h> #include "desktop.h" #include "ui/dialog/desktop-tracker.h" #include "ui/widget/panel.h" #include "ui/widget/button.h" #include "ui/widget/entry.h" -#include "widgets/sp-attribute-widget.h" + +namespace Gtk { +class Dialog; +} namespace Inkscape { namespace UI { namespace Dialog { - /** What type of button is being pressed */ enum selection_type { SELECTION_PAGE = 0, /**< Export the whole page */ @@ -43,16 +44,6 @@ enum selection_type { SELECTION_NUMBER_OF /**< A counter for the number of these guys */ }; -/** A list of strings that is used both in the preferences, and in the - data fields to describe the various values of \c selection_type. */ -static const char * selection_names[SELECTION_NUMBER_OF] = { - "page", "drawing", "selection", "custom"}; - -/** The names on the buttons for the various selection types. */ -static const char * selection_labels[SELECTION_NUMBER_OF] = { - N_("_Page"), N_("_Drawing"), N_("_Selection"), N_("_Custom")}; - - /** * A dialog widget to export to various image formats such as bitmap and png. * @@ -65,7 +56,9 @@ public: Export (); ~Export (); - static Export &getInstance() { return *new Export(); } + static Export &getInstance() { + return *new Export(); + } private: @@ -78,6 +71,7 @@ private: * */ void setImageX(); + /** * A function to set the ydpi. * @@ -105,7 +99,7 @@ private: float getValue (Gtk::Adjustment *adj); float getValuePx (Gtk::Adjustment *adj); #endif - + /** * Helper function to create, style and pack spinbuttons for the export dialog. * @@ -116,7 +110,6 @@ private: * @param max Maximum value for the spin button * @param step The step size for the spin button * @param page Size of the page increment - * @param us Unit selector that effects this spin button * @param t Table to put the spin button in * @param x X location in the table \c t to start with * @param y Y location in the table \c t to start with @@ -125,23 +118,25 @@ private: * @param digits Number of digits to display after the decimal * @param sensitive Whether the spin button is sensitive or not * @param cb Callback for when this spin button is changed (optional) + * + * No unit_selector is stored in the created spinbutton, relies on external unit management */ #if WITH_GTKMM_3_0 Glib::RefPtr<Gtk::Adjustment> createSpinbutton( gchar const *key, float val, float min, float max, - float step, float page, GtkWidget *us, - Gtk::Table *t, int x, int y, - const Glib::ustring ll, const Glib::ustring lr, - int digits, unsigned int sensitive, - void (Export::*cb)() ); + float step, float page, + Gtk::Grid *t, int x, int y, + const Glib::ustring& ll, const Glib::ustring& lr, + int digits, unsigned int sensitive, + void (Export::*cb)() ); #else Gtk::Adjustment * createSpinbutton( gchar const *key, float val, float min, float max, - float step, float page, GtkWidget *us, - Gtk::Table *t, int x, int y, - const Glib::ustring ll, const Glib::ustring lr, - int digits, unsigned int sensitive, - void (Export::*cb)() ); + float step, float page, + Gtk::Table *t, int x, int y, + const Glib::ustring& ll, const Glib::ustring& lr, + int digits, unsigned int sensitive, + void (Export::*cb)() ); #endif - + /** * One of the area select radio buttons was pressed */ @@ -160,8 +155,12 @@ private: /** * Area X value changed callback */ - void onAreaX0Change() {areaXChange(x0_adj);} ; - void onAreaX1Change() {areaXChange(x1_adj);} ; + void onAreaX0Change() { + areaXChange(x0_adj); + } ; + void onAreaX1Change() { + areaXChange(x1_adj); + } ; #if WITH_GTKMM_3_0 void areaXChange(Glib::RefPtr<Gtk::Adjustment>& adj); #else @@ -171,8 +170,12 @@ private: /** * Area Y value changed callback */ - void onAreaY0Change() {areaYChange(y0_adj);} ; - void onAreaY1Change() {areaYChange(y1_adj);} ; + void onAreaY0Change() { + areaYChange(y0_adj); + } ; + void onAreaY1Change() { + areaYChange(y1_adj); + } ; #if WITH_GTKMM_3_0 void areaYChange(Glib::RefPtr<Gtk::Adjustment>& adj); #else @@ -180,6 +183,16 @@ private: #endif /** + * Unit changed callback + */ + void onUnitChanged(); + + /** + * Hide except selected callback + */ + void onHideExceptSelected (); + + /** * Area width value changed callback */ void onAreaWidthChange (); @@ -232,26 +245,34 @@ private: /** * Creates progress dialog for batch exporting. - * + * * @param progress_text Text to be shown in the progress bar */ Gtk::Dialog * create_progress_dialog (Glib::ustring progress_text); + /** * Callback to be used in for loop to update the progress bar. - * + * * @param value number between 0 and 1 indicating the fraction of progress (0.17 = 17 % progress) * @param dlg void pointer to the Gtk::Dialog progress dialog */ - static unsigned int onProgressCallback (float value, void *dlg); + static unsigned int onProgressCallback(float value, void *dlg); + /** * Callback for pressing the cancel button. */ void onProgressCancel (); + /** * Callback invoked on closing the progress dialog. */ bool onProgressDelete (GdkEventAny *event); + /** + * Handles state changes as exporting starts or stops. + */ + void setExporting(bool exporting, Glib::ustring const &text = ""); + /* * Utility filename and path functions */ @@ -325,7 +346,7 @@ private: /* Unit selector widgets */ Gtk::HBox unitbox; - Gtk::Widget* unit_selector; + Inkscape::UI::Widget::UnitMenu unit_selector; Gtk::Label units_label; /* Filename widgets */ @@ -340,12 +361,16 @@ private: Gtk::HBox hide_box; Inkscape::UI::Widget::CheckButton hide_export; + Inkscape::UI::Widget::CheckButton closeWhenDone; + /* Export Button widgets */ - Gtk::HButtonBox button_box; + Gtk::HBox button_box; Gtk::Button export_button; Gtk::Label export_label; Gtk::Image export_image; + Gtk::ProgressBar _prog; + Gtk::Dialog *prog_dlg; bool interrupted; // indicates whether export needs to be interrupted (read: user pressed cancel in the progress dialog) @@ -356,6 +381,7 @@ private: sigc::connection selectChangedConn; sigc::connection subselChangedConn; sigc::connection selectModifiedConn; + sigc::connection unitChangedConn; }; diff --git a/src/ui/dialog/filedialog.cpp b/src/ui/dialog/filedialog.cpp index 47ba6c748..e71605739 100644 --- a/src/ui/dialog/filedialog.cpp +++ b/src/ui/dialog/filedialog.cpp @@ -15,15 +15,17 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ +#include "filedialogimpl-win32.h" #include "filedialogimpl-gtkmm.h" #include "filedialog.h" -#include "filedialogimpl-win32.h" #include "gc-core.h" #include <dialogs/dialog-events.h> #include "extension/output.h" #include "preferences.h" +#include <glibmm/convert.h> + namespace Inkscape { namespace UI @@ -152,6 +154,9 @@ Glib::ustring FileSaveDialog::getDocTitle() void FileSaveDialog::appendExtension(Glib::ustring& path, Inkscape::Extension::Output* outputExtension) { + if (!outputExtension) + return; + try { bool appendExtension = true; Glib::ustring utf8Name = Glib::filename_to_utf8( path ); diff --git a/src/ui/dialog/filedialog.h b/src/ui/dialog/filedialog.h index 9b0e6a291..8dfcf5dce 100644 --- a/src/ui/dialog/filedialog.h +++ b/src/ui/dialog/filedialog.h @@ -16,12 +16,13 @@ #ifndef __FILE_DIALOG_H__ #define __FILE_DIALOG_H__ -#include <glibmm.h> #include <vector> #include <set> #include "extension/system.h" +#include <glibmm/ustring.h> + class SPDocument; namespace Inkscape { @@ -46,7 +47,8 @@ typedef enum { SVG_TYPES, IMPORT_TYPES, EXPORT_TYPES, - EXE_TYPES + EXE_TYPES, + CUSTOM_TYPE } FileDialogType; /** @@ -124,6 +126,8 @@ public: virtual Glib::ustring getCurrentDirectory() = 0; + virtual void addFilterMenu(Glib::ustring name, Glib::ustring pattern) = 0; + protected: /** * Filename that was given @@ -205,6 +209,8 @@ public: virtual Glib::ustring getCurrentDirectory() = 0; + virtual void addFileType(Glib::ustring name, Glib::ustring pattern) = 0; + protected: /** diff --git a/src/ui/dialog/filedialogimpl-gtkmm.cpp b/src/ui/dialog/filedialogimpl-gtkmm.cpp index 6cdd202bb..fdc9cecc3 100644 --- a/src/ui/dialog/filedialogimpl-gtkmm.cpp +++ b/src/ui/dialog/filedialogimpl-gtkmm.cpp @@ -34,7 +34,12 @@ #include <gtkmm/expander.h> #include <gtkmm/stock.h> + +#include <glibmm/convert.h> +#include <glibmm/fileutils.h> #include <glibmm/i18n.h> +#include <glibmm/miscutils.h> + #include "extension/input.h" #include "extension/output.h" #include "extension/db.h" @@ -100,9 +105,9 @@ findEntryWidgets(Gtk::Container *parent, Gtk::Widget *child = children[i]; GtkWidget *wid = child->gobj(); if (GTK_IS_ENTRY(wid)) - result.push_back((Gtk::Entry *)child); + result.push_back(dynamic_cast<Gtk::Entry *>(child)); else if (GTK_IS_CONTAINER(wid)) - findEntryWidgets((Gtk::Container *)child, result); + findEntryWidgets(dynamic_cast<Gtk::Container *>(child), result); } } @@ -119,9 +124,9 @@ findExpanderWidgets(Gtk::Container *parent, Gtk::Widget *child = children[i]; GtkWidget *wid = child->gobj(); if (GTK_IS_EXPANDER(wid)) - result.push_back((Gtk::Expander *)child); + result.push_back(dynamic_cast<Gtk::Expander *>(child)); else if (GTK_IS_CONTAINER(wid)) - findExpanderWidgets((Gtk::Container *)child, result); + findExpanderWidgets(dynamic_cast<Gtk::Container *>(child), result); } } @@ -141,13 +146,12 @@ bool SVGPreview::setDocument(SPDocument *doc) //This should remove it from the box, and free resources if (viewerGtk) - gtk_widget_destroy(viewerGtk); - - viewerGtk = sp_svg_view_widget_new(doc); - GtkWidget *vbox = (GtkWidget *)gobj(); - gtk_box_pack_start(GTK_BOX(vbox), viewerGtk, TRUE, TRUE, 0); - gtk_widget_show(viewerGtk); + Gtk::Container::remove(*viewerGtk); + viewerGtk = Glib::wrap(sp_svg_view_widget_new(doc)); + Gtk::VBox *vbox = Glib::wrap(gobj()); + vbox->pack_start(*viewerGtk, TRUE, TRUE, 0); + viewerGtk->show(); return true; } @@ -523,9 +527,9 @@ bool SVGPreview::set(Glib::ustring &fileName, int dialogType) if (Glib::file_test(fileName, Glib::FILE_TEST_IS_REGULAR)) { Glib::ustring fileNameUtf8 = Glib::filename_to_utf8(fileName); - gchar *fName = (gchar *)fileNameUtf8.c_str(); + gchar *fName = const_cast<gchar *>(fileNameUtf8.c_str()); struct stat info; - if (g_stat(fName, &info)) + if (g_file_test (fName, G_FILE_TEST_EXISTS) && g_stat(fName, &info)) { g_warning("SVGPreview::set() : %s : %s", fName, strerror(errno)); @@ -732,38 +736,86 @@ FileOpenDialogImplGtk::~FileOpenDialogImplGtk() } +void FileOpenDialogImplGtk::addFilterMenu(Glib::ustring name, Glib::ustring pattern) +{ + +#if WITH_GTKMM_3_0 + Glib::RefPtr<Gtk::FileFilter> allFilter = Gtk::FileFilter::create(); + allFilter->set_name(_(name.c_str())); + allFilter->add_pattern(pattern); +#else + Gtk::FileFilter allFilter; + allFilter.set_name(_(name.c_str())); + allFilter.add_pattern(pattern); +#endif + extensionMap[Glib::ustring(_("All Files"))]=NULL; + add_filter(allFilter); +} + void FileOpenDialogImplGtk::createFilterMenu() { + if (_dialogType == CUSTOM_TYPE) { + return; + } + if (_dialogType == EXE_TYPES) { +#if WITH_GTKMM_3_0 + Glib::RefPtr<Gtk::FileFilter> allFilter = Gtk::FileFilter::create(); + allFilter->set_name(_("All Files")); + allFilter->add_pattern("*"); +#else Gtk::FileFilter allFilter; allFilter.set_name(_("All Files")); - extensionMap[Glib::ustring(_("All Files"))]=NULL; allFilter.add_pattern("*"); +#endif + extensionMap[Glib::ustring(_("All Files"))]=NULL; add_filter(allFilter); } else { +#if WITH_GTKMM_3_0 + Glib::RefPtr<Gtk::FileFilter> allInkscapeFilter = Gtk::FileFilter::create(); + allInkscapeFilter->set_name(_("All Inkscape Files")); + + Glib::RefPtr<Gtk::FileFilter> allFilter = Gtk::FileFilter::create(); + allFilter->set_name(_("All Files")); + allFilter->add_pattern("*"); + + Glib::RefPtr<Gtk::FileFilter> allImageFilter = Gtk::FileFilter::create(); + allImageFilter->set_name(_("All Images")); + + Glib::RefPtr<Gtk::FileFilter> allVectorFilter = Gtk::FileFilter::create(); + allVectorFilter->set_name(_("All Vectors")); + + Glib::RefPtr<Gtk::FileFilter> allBitmapFilter = Gtk::FileFilter::create(); + allBitmapFilter->set_name(_("All Bitmaps")); +#else Gtk::FileFilter allInkscapeFilter; allInkscapeFilter.set_name(_("All Inkscape Files")); + + Gtk::FileFilter allFilter; + allFilter.set_name(_("All Files")); + allFilter.add_pattern("*"); + + Gtk::FileFilter allImageFilter; + allImageFilter.set_name(_("All Images")); + + Gtk::FileFilter allVectorFilter; + allVectorFilter.set_name(_("All Vectors")); + + Gtk::FileFilter allBitmapFilter; + allBitmapFilter.set_name(_("All Bitmaps")); +#endif extensionMap[Glib::ustring(_("All Inkscape Files"))]=NULL; add_filter(allInkscapeFilter); - Gtk::FileFilter allFilter; - allFilter.set_name(_("All Files")); extensionMap[Glib::ustring(_("All Files"))]=NULL; - allFilter.add_pattern("*"); add_filter(allFilter); - Gtk::FileFilter allImageFilter; - allImageFilter.set_name(_("All Images")); extensionMap[Glib::ustring(_("All Images"))]=NULL; add_filter(allImageFilter); - Gtk::FileFilter allVectorFilter; - allVectorFilter.set_name(_("All Vectors")); extensionMap[Glib::ustring(_("All Vectors"))]=NULL; add_filter(allVectorFilter); - Gtk::FileFilter allBitmapFilter; - allBitmapFilter.set_name(_("All Bitmaps")); extensionMap[Glib::ustring(_("All Bitmaps"))]=NULL; add_filter(allBitmapFilter); @@ -783,17 +835,31 @@ void FileOpenDialogImplGtk::createFilterMenu() Glib::ustring extension = imod->get_extension(); fileDialogExtensionToPattern(upattern, extension); - Gtk::FileFilter filter; Glib::ustring uname(_(imod->get_filetypename())); + +#if WITH_GTKMM_3_0 + Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create(); + filter->set_name(uname); + filter->add_pattern(upattern); +#else + Gtk::FileFilter filter; filter.set_name(uname); filter.add_pattern(upattern); +#endif + add_filter(filter); extensionMap[uname] = imod; //g_message("ext %s:%s '%s'\n", ioext->name, ioext->mimetype, upattern.c_str()); +#if WITH_GTKMM_3_0 + allInkscapeFilter->add_pattern(upattern); + if ( strncmp("image", imod->get_mimetype(), 5)==0 ) + allImageFilter->add_pattern(upattern); +#else allInkscapeFilter.add_pattern(upattern); if ( strncmp("image", imod->get_mimetype(), 5)==0 ) allImageFilter.add_pattern(upattern); +#endif // uncomment this to find out all mime types supported by Inkscape import/open // g_print ("%s\n", imod->get_mimetype()); @@ -814,9 +880,17 @@ void FileOpenDialogImplGtk::createFilterMenu() strncmp("image/x-tga", imod->get_mimetype(), 11)==0 || strncmp("image/x-pcx", imod->get_mimetype(), 11)==0 ) +#if WITH_GTKMM_3_0 + allBitmapFilter->add_pattern(upattern); +#else allBitmapFilter.add_pattern(upattern); +#endif else +#if WITH_GTKMM_3_0 + allVectorFilter->add_pattern(upattern); +#else allVectorFilter.add_pattern(upattern); +#endif } } return; @@ -829,7 +903,7 @@ bool FileOpenDialogImplGtk::show() { set_modal (TRUE); //Window - sp_transientize((GtkWidget *)gobj()); //Make transient + sp_transientize(GTK_WIDGET(gobj())); //Make transient gint b = run(); //Dialog svgPreview.showNoPreview(); hide(); @@ -889,7 +963,20 @@ FileOpenDialogImplGtk::getFilename (void) */ std::vector<Glib::ustring>FileOpenDialogImplGtk::getFilenames() { +#if WITH_GTKMM_3_0 + std::vector<std::string> result_tmp = get_filenames(); + + // Copy filenames to a vector of type Glib::ustring + std::vector<Glib::ustring> result; + + for (std::vector<std::string>::iterator it = result_tmp.begin(); + it != result_tmp.end(); ++it) + result.push_back(*it); + +#else std::vector<Glib::ustring> result = get_filenames(); +#endif + #ifdef WITH_GNOME_VFS if (result.empty() && gnome_vfs_initialized()) result = get_uris(); @@ -965,7 +1052,9 @@ FileSaveDialogImplGtk::FileSaveDialogImplGtk( Gtk::Window &parentWindow, fileTypeCheckbox.set_active(prefs->getBool("/dialogs/save_as/append_extension", true)); } - createFileTypeMenu(); + if (_dialogType != CUSTOM_TYPE) + createFileTypeMenu(); + fileTypeComboBox.set_size_request(200,40); fileTypeComboBox.signal_changed().connect( sigc::mem_fun(*this, &FileSaveDialogImplGtk::fileTypeChangedCallback) ); @@ -984,7 +1073,7 @@ FileSaveDialogImplGtk::FileSaveDialogImplGtk( Gtk::Window &parentWindow, std::vector<Gtk::Entry *> entries; findEntryWidgets(cont, entries); //g_message("Found %d entry widgets\n", entries.size()); - if (entries.size() >=1 ) + if (!entries.empty()) { //Catch when user hits [return] on the text field fileNameEntry = entries[0]; @@ -996,7 +1085,7 @@ FileSaveDialogImplGtk::FileSaveDialogImplGtk( Gtk::Window &parentWindow, std::vector<Gtk::Expander *> expanders; findExpanderWidgets(cont, expanders); //g_message("Found %d expander widgets\n", expanders.size()); - if (expanders.size() >=1 ) + if (!expanders.empty()) { //Always show the file list Gtk::Expander *expander = expanders[0]; @@ -1080,15 +1169,33 @@ void FileSaveDialogImplGtk::fileTypeChangedCallback() //g_message("selected: %s\n", type.name.c_str()); extension = type.extension; +#if WITH_GTKMM_3_0 + Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create(); + filter->add_pattern(type.pattern); +#else Gtk::FileFilter filter; filter.add_pattern(type.pattern); +#endif set_filter(filter); updateNameAndExtension(); } +void FileSaveDialogImplGtk::addFileType(Glib::ustring name, Glib::ustring pattern) +{ + //#Let user choose + FileType guessType; + guessType.name = name; + guessType.pattern = pattern; + guessType.extension = NULL; + fileTypeComboBox.append(guessType.name); + fileTypes.push_back(guessType); + fileTypeComboBox.set_active(0); + fileTypeChangedCallback(); //call at least once to set the filter +} + void FileSaveDialogImplGtk::createFileTypeMenu() { Inkscape::Extension::DB::OutputList extension_list; @@ -1110,11 +1217,7 @@ void FileSaveDialogImplGtk::createFileTypeMenu() knownExtensions.insert( extension.casefold() ); fileDialogExtensionToPattern (type.pattern, extension); type.extension= omod; -#if WITH_GTKMM_2_24 fileTypeComboBox.append(type.name); -#else - fileTypeComboBox.append_text(type.name); -#endif fileTypes.push_back(type); } @@ -1123,11 +1226,7 @@ void FileSaveDialogImplGtk::createFileTypeMenu() guessType.name = _("Guess from extension"); guessType.pattern = "*"; guessType.extension = NULL; -#if WITH_GTKMM_2_24 fileTypeComboBox.append(guessType.name); -#else - fileTypeComboBox.append_text(guessType.name); -#endif fileTypes.push_back(guessType); @@ -1147,7 +1246,7 @@ FileSaveDialogImplGtk::show() { change_path(myFilename); set_modal (TRUE); //Window - sp_transientize((GtkWidget *)gobj()); //Make transient + sp_transientize(GTK_WIDGET(gobj())); //Make transient gint b = run(); //Dialog svgPreview.showNoPreview(); set_preview_widget_active(false); @@ -1545,7 +1644,7 @@ FileExportDialogImpl::FileExportDialogImpl( Gtk::Window& parentWindow, std::vector<Gtk::Entry *> entries; findEntryWidgets(cont, entries); //g_message("Found %d entry widgets\n", entries.size()); - if (entries.size() >=1 ) + if (!entries.empty()) { //Catch when user hits [return] on the text field fileNameEntry = entries[0]; @@ -1557,7 +1656,7 @@ FileExportDialogImpl::FileExportDialogImpl( Gtk::Window& parentWindow, std::vector<Gtk::Expander *> expanders; findExpanderWidgets(cont, expanders); //g_message("Found %d expander widgets\n", expanders.size()); - if (expanders.size() >=1 ) + if (!expanders.empty()) { //Always show the file list Gtk::Expander *expander = expanders[0]; @@ -1594,7 +1693,7 @@ FileExportDialogImpl::show() s = getcwd (NULL, 0); set_current_folder(Glib::filename_from_utf8(s)); //hack to force initial dir listing set_modal (TRUE); //Window - sp_transientize((GtkWidget *)gobj()); //Make transient + sp_transientize(GTK_WIDGET(gobj())); //Make transient gint b = run(); //Dialog svgPreview.showNoPreview(); hide(); diff --git a/src/ui/dialog/filedialogimpl-gtkmm.h b/src/ui/dialog/filedialogimpl-gtkmm.h index 4caa106ad..6687915d7 100644 --- a/src/ui/dialog/filedialogimpl-gtkmm.h +++ b/src/ui/dialog/filedialogimpl-gtkmm.h @@ -17,6 +17,14 @@ #ifndef __FILE_DIALOGIMPL_H__ #define __FILE_DIALOGIMPL_H__ +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + //Gtk includes #include <gtkmm/filechooserdialog.h> #include <glib/gstdio.h> @@ -121,7 +129,7 @@ private: /** * The sp_svg_view widget */ - GtkWidget *viewerGtk; + Gtk::Widget *viewerGtk; /** * are we currently showing the "no preview" image? @@ -236,6 +244,12 @@ public: Glib::ustring getCurrentDirectory(); + /// Add a custom file filter menu item + /// @param name - Name of the filter (such as "Javscript") + /// @param pattern - File filtering patter (such as "*.js") + /// Use the FileDialogType::CUSTOM_TYPE in constructor to not include other file types + void addFilterMenu(Glib::ustring name, Glib::ustring pattern); + private: /** @@ -243,6 +257,7 @@ private: */ void createFilterMenu(); + /** * Filter name->extension lookup */ @@ -284,6 +299,7 @@ public: virtual void setSelectionType( Inkscape::Extension::Extension * key ); Glib::ustring getCurrentDirectory(); + void addFileType(Glib::ustring name, Glib::ustring pattern); private: //void change_title(const Glib::ustring& title); diff --git a/src/ui/dialog/filedialogimpl-win32.cpp b/src/ui/dialog/filedialogimpl-win32.cpp index 089ec1737..9d91f5d56 100644 --- a/src/ui/dialog/filedialogimpl-win32.cpp +++ b/src/ui/dialog/filedialogimpl-win32.cpp @@ -16,7 +16,7 @@ #ifdef HAVE_CONFIG_H # include <config.h> #endif - +#include "filedialogimpl-win32.h" //General includes #include <list> #include <unistd.h> @@ -26,6 +26,7 @@ #include <gdk/gdkwin32.h> #include <glib/gstdio.h> #include <glibmm/i18n.h> +#include <glibmm/fileutils.h> #include <gtkmm/window.h> //Inkscape includes @@ -41,7 +42,7 @@ #include "display/canvas-arena.h" #include "filedialog.h" -#include "filedialogimpl-win32.h" + #include "sp-root.h" #include <zlib.h> @@ -133,7 +134,11 @@ FileDialogBaseWin32::FileDialogBaseWin32(Gtk::Window &parent, Glib::RefPtr<const Gdk::Window> parentWindow = parent.get_window(); g_assert(parentWindow->gobj() != NULL); +#if WITH_GTKMM_3_0 + _ownerHwnd = (HWND)gdk_win32_window_get_handle((GdkWindow*)parentWindow->gobj()); +#else _ownerHwnd = (HWND)gdk_win32_drawable_get_handle((GdkDrawable*)parentWindow->gobj()); +#endif } FileDialogBaseWin32::~FileDialogBaseWin32() @@ -188,7 +193,8 @@ FileOpenDialogImplWin32::FileOpenDialogImplWin32(Gtk::Window &parent, _mutex = NULL; - createFilterMenu(); + if (dialogType != CUSTOM_TYPE) + createFilterMenu(); } @@ -203,6 +209,64 @@ FileOpenDialogImplWin32::~FileOpenDialogImplWin32() delete[] _extension_map; } +void FileOpenDialogImplWin32::addFilterMenu(Glib::ustring name, Glib::ustring pattern) +{ + list<Filter> filter_list; + + int extension_index = 0; + int filter_length = 1; + + ustring all_exe_files_filter = pattern; + Filter all_exe_files; + + const gchar *all_exe_files_filter_name = name.data(); + + // Calculate the amount of memory required + int filter_count = 1; + + _extension_map = new Inkscape::Extension::Extension*[filter_count]; + + // Filter Executable Files + all_exe_files.name = g_utf8_to_utf16(all_exe_files_filter_name, + -1, NULL, &all_exe_files.name_length, NULL); + all_exe_files.filter = g_utf8_to_utf16(all_exe_files_filter.data(), + -1, NULL, &all_exe_files.filter_length, NULL); + all_exe_files.mod = NULL; + filter_list.push_front(all_exe_files); + + _filter = new wchar_t[filter_length]; + wchar_t *filterptr = _filter; + + for(list<Filter>::iterator filter_iterator = filter_list.begin(); + filter_iterator != filter_list.end(); ++filter_iterator) + { + const Filter &filter = *filter_iterator; + + wcsncpy(filterptr, (wchar_t*)filter.name, filter.name_length); + filterptr += filter.name_length; + g_free(filter.name); + + *(filterptr++) = L'\0'; + *(filterptr++) = L'*'; + + if(filter.filter != NULL) + { + wcsncpy(filterptr, (wchar_t*)filter.filter, filter.filter_length); + filterptr += filter.filter_length; + g_free(filter.filter); + } + + *(filterptr++) = L'\0'; + + // Associate this input extension with the file type name + _extension_map[extension_index++] = filter.mod; + } + *(filterptr++) = L'\0'; + + _filter_count = extension_index; + _filter_index = 1; // Select the 1st filter in the list +} + void FileOpenDialogImplWin32::createFilterMenu() { list<Filter> filter_list; @@ -210,6 +274,10 @@ void FileOpenDialogImplWin32::createFilterMenu() int extension_index = 0; int filter_length = 1; + if (dialogType == CUSTOM_TYPE) { + return; + } + if (dialogType != EXE_TYPES) { // Compose the filter string Inkscape::Extension::DB::InputList extension_list; @@ -1513,16 +1581,23 @@ FileOpenDialogImplWin32::show() // We can only run one worker thread at a time if(_mutex != NULL) return false; +#if !GLIB_CHECK_VERSION(2,32,0) if(!Glib::thread_supported()) Glib::thread_init(); +#endif _result = false; _finished = false; _file_selected = false; - _mutex = new Glib::Mutex(); _main_loop = g_main_loop_new(g_main_context_default(), FALSE); +#if GLIB_CHECK_VERSION(2,32,0) + _mutex = new Glib::Threads::Mutex(); + if(Glib::Threads::Thread::create(sigc::mem_fun(*this, &FileOpenDialogImplWin32::GetOpenFileName_thread))) +#else + _mutex = new Glib::Mutex(); if(Glib::Thread::create(sigc::mem_fun(*this, &FileOpenDialogImplWin32::GetOpenFileName_thread), true)) +#endif { while(1) { @@ -1686,6 +1761,72 @@ void FileSaveDialogImplWin32::createFilterMenu() _filter_index = 1; // A value of 1 selects the 1st filter - NOT the 2nd } + +void FileSaveDialogImplWin32::addFileType(Glib::ustring name, Glib::ustring pattern) +{ + list<Filter> filter_list; + + knownExtensions.clear(); + + int extension_index = 0; + int filter_length = 1; + + ustring all_exe_files_filter = pattern; + Filter all_exe_files; + + const gchar *all_exe_files_filter_name = name.data(); + + // Calculate the amount of memory required + int filter_count = 1; + + + // Filter Executable Files + all_exe_files.name = g_utf8_to_utf16(all_exe_files_filter_name, + -1, NULL, &all_exe_files.name_length, NULL); + all_exe_files.filter = g_utf8_to_utf16(all_exe_files_filter.data(), + -1, NULL, &all_exe_files.filter_length, NULL); + all_exe_files.mod = NULL; + filter_list.push_front(all_exe_files); + + knownExtensions.insert( Glib::ustring(all_exe_files_filter).casefold() ); + + _extension_map = new Inkscape::Extension::Extension*[filter_count]; + + _filter = new wchar_t[filter_length]; + wchar_t *filterptr = _filter; + + for(list<Filter>::iterator filter_iterator = filter_list.begin(); + filter_iterator != filter_list.end(); ++filter_iterator) + { + const Filter &filter = *filter_iterator; + + wcsncpy(filterptr, (wchar_t*)filter.name, filter.name_length); + filterptr += filter.name_length; + g_free(filter.name); + + *(filterptr++) = L'\0'; + *(filterptr++) = L'*'; + + if(filter.filter != NULL) + { + wcsncpy(filterptr, (wchar_t*)filter.filter, filter.filter_length); + filterptr += filter.filter_length; + g_free(filter.filter); + } + + *(filterptr++) = L'\0'; + + // Associate this input extension with the file type name + _extension_map[extension_index++] = filter.mod; + } + *(filterptr++) = L'\0'; + + _filter_count = extension_index; + _filter_index = 1; // Select the 1st filter in the list + + +} + void FileSaveDialogImplWin32::GetSaveFileName_thread() { OPENFILENAMEEXW ofn; @@ -1741,18 +1882,24 @@ void FileSaveDialogImplWin32::GetSaveFileName_thread() bool FileSaveDialogImplWin32::show() { +#if !GLIB_CHECK_VERSION(2,32,0) if(!Glib::thread_supported()) Glib::thread_init(); +#endif _result = false; _main_loop = g_main_loop_new(g_main_context_default(), FALSE); if(_main_loop != NULL) { +#if GLIB_CHECK_VERSION(2,32,0) + if(Glib::Threads::Thread::create(sigc::mem_fun(*this, &FileSaveDialogImplWin32::GetSaveFileName_thread))) +#else if(Glib::Thread::create(sigc::mem_fun(*this, &FileSaveDialogImplWin32::GetSaveFileName_thread), true)) +#endif g_main_loop_run(_main_loop); - if(_result) + if(_result && _extension) appendExtension(myFilename, (Inkscape::Extension::Output*)_extension); } @@ -1765,6 +1912,7 @@ void FileSaveDialogImplWin32::setSelectionType( Inkscape::Extension::Extension * } + UINT_PTR CALLBACK FileSaveDialogImplWin32::GetSaveFileName_hookproc( HWND hdlg, UINT uiMsg, WPARAM, LPARAM lParam) { diff --git a/src/ui/dialog/filedialogimpl-win32.h b/src/ui/dialog/filedialogimpl-win32.h index a6f7d6239..29bcb9a45 100644 --- a/src/ui/dialog/filedialogimpl-win32.h +++ b/src/ui/dialog/filedialogimpl-win32.h @@ -9,11 +9,21 @@ * * Released under GNU GPL, read the file 'COPYING' for more information */ +#if HAVE_CONFIG_H +# include "config.h" +#endif #ifdef WIN32 +#if WITH_GLIBMM_2_32 +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +# include <glibmm/threads.h> +#endif +#endif #include "gc-core.h" #include <windows.h> +#include "filedialogimpl-gtkmm.h" + namespace Inkscape { @@ -54,6 +64,7 @@ public: /// Get the path of the current directory Glib::ustring getCurrentDirectory(); + protected: /// The dialog type FileDialogType dialogType; @@ -129,7 +140,7 @@ public: /// Shows the file dialog, and blocks until a file /// has been selected. - /// @return Returns true if the the user selected a + /// @return Returns true if the user selected a /// file, or false if the user pressed cancel. bool show(); @@ -148,6 +159,13 @@ public: virtual Inkscape::Extension::Extension* getSelectionType() { return FileDialogBaseWin32::getSelectionType(); } + + /// Add a custom file filter menu item + /// @param name - Name of the filter (such as "Javscript") + /// @param pattern - File filtering patter (such as "*.js") + /// Use the FileDialogType::CUSTOM_TYPE in constructor to not include other file types + virtual void addFilterMenu(Glib::ustring name, Glib::ustring pattern); + private: /// Create filter menu for this type of dialog @@ -218,7 +236,11 @@ private: /// This mutex is used to ensure that the worker thread /// that calls GetOpenFileName cannot collide with the /// main Inkscape thread +#if GLIB_CHECK_VERSION(2,32,0) + Glib::Threads::Mutex *_mutex; +#else Glib::Mutex *_mutex; +#endif /// The controller function for the thread which calls @@ -319,7 +341,7 @@ public: /// Shows the file dialog, and blocks until a file /// has been selected. - /// @return Returns true if the the user selected a + /// @return Returns true if the user selected a /// file, or false if the user pressed cancel. bool show(); @@ -335,6 +357,8 @@ public: virtual void setSelectionType( Inkscape::Extension::Extension *key ); + virtual void addFileType(Glib::ustring name, Glib::ustring pattern); + private: /// A handle to the title label and edit box HWND _title_label; diff --git a/src/ui/dialog/fill-and-stroke.cpp b/src/ui/dialog/fill-and-stroke.cpp index 91b88d3f0..19b873d54 100644 --- a/src/ui/dialog/fill-and-stroke.cpp +++ b/src/ui/dialog/fill-and-stroke.cpp @@ -15,6 +15,7 @@ * Released under GNU GPL. Read the file 'COPYING' for more information. */ +#include "ui/widget/notebook-page.h" #include "desktop-handles.h" #include "desktop-style.h" #include "document.h" @@ -22,6 +23,7 @@ #include "filter-chemistry.h" #include "inkscape.h" #include "selection.h" +#include "preferences.h" #include "style.h" #include "svg/css-ostringstream.h" #include "ui/icon-names.h" @@ -34,15 +36,17 @@ #include "ui/view/view-widget.h" +#include <gtkmm/table.h> + namespace Inkscape { namespace UI { namespace Dialog { FillAndStroke::FillAndStroke() : UI::Widget::Panel ("", "/dialogs/fillstroke", SP_VERB_DIALOG_FILL_STROKE), - _page_fill(1, 1, true, true), - _page_stroke_paint(1, 1, true, true), - _page_stroke_style(1, 1, true, true), + _page_fill(Gtk::manage(new UI::Widget::NotebookPage(1, 1, true, true))), + _page_stroke_paint(Gtk::manage(new UI::Widget::NotebookPage(1, 1, true, true))), + _page_stroke_style(Gtk::manage(new UI::Widget::NotebookPage(1, 1, true, true))), _composite_settings(SP_VERB_DIALOG_FILL_STROKE, "fillstroke", UI::Widget::SimpleFilterModifier::BLUR), deskTrack(), targetDesktop(0), @@ -51,19 +55,21 @@ FillAndStroke::FillAndStroke() desktopChangeConn() { Gtk::Box *contents = _getContents(); - contents->set_spacing(0); + contents->set_spacing(2); contents->pack_start(_notebook, true, true); - _notebook.append_page(_page_fill, _createPageTabLabel(_("_Fill"), INKSCAPE_ICON("object-fill"))); - _notebook.append_page(_page_stroke_paint, _createPageTabLabel(_("Stroke _paint"), INKSCAPE_ICON("object-stroke"))); - _notebook.append_page(_page_stroke_style, _createPageTabLabel(_("Stroke st_yle"), INKSCAPE_ICON("object-stroke-style"))); + _notebook.append_page(*_page_fill, _createPageTabLabel(_("_Fill"), INKSCAPE_ICON("object-fill"))); + _notebook.append_page(*_page_stroke_paint, _createPageTabLabel(_("Stroke _paint"), INKSCAPE_ICON("object-stroke"))); + _notebook.append_page(*_page_stroke_style, _createPageTabLabel(_("Stroke st_yle"), INKSCAPE_ICON("object-stroke-style"))); + + _notebook.signal_switch_page().connect(sigc::mem_fun(this, &FillAndStroke::_onSwitchPage)); _layoutPageFill(); _layoutPageStrokePaint(); _layoutPageStrokeStyle(); - contents->pack_start(_composite_settings, false, false, 0); + contents->pack_start(_composite_settings, true, true, 0); show_all_children(); @@ -96,32 +102,68 @@ void FillAndStroke::setTargetDesktop(SPDesktop *desktop) sp_fill_style_widget_set_desktop(fillWdgt, desktop); } if (strokeWdgt) { - sp_stroke_style_widget_set_desktop(strokeWdgt, desktop); + sp_fill_style_widget_set_desktop(strokeWdgt, desktop); } + if (strokeStyleWdgt) { + sp_stroke_style_widget_set_desktop(strokeStyleWdgt, desktop); + } + _composite_settings.setSubject(&_subject); } } +#if WITH_GTKMM_3_0 +void FillAndStroke::_onSwitchPage(Gtk::Widget * /*page*/, guint pagenum) +#else +void FillAndStroke::_onSwitchPage(GtkNotebookPage * /*page*/, guint pagenum) +#endif +{ + _savePagePref(pagenum); +} + +void +FillAndStroke::_savePagePref(guint page_num) +{ + // remember the current page + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + prefs->setInt("/dialogs/fillstroke/page", page_num); +} + void FillAndStroke::_layoutPageFill() { fillWdgt = manage(sp_fill_style_widget_new()); - _page_fill.table().attach(*fillWdgt, 0, 1, 0, 1); + +#if WITH_GTKMM_3_0 + _page_fill->table().attach(*fillWdgt, 0, 0, 1, 1); +#else + _page_fill->table().attach(*fillWdgt, 0, 1, 0, 1); +#endif } void FillAndStroke::_layoutPageStrokePaint() { strokeWdgt = manage(sp_stroke_style_paint_widget_new()); - _page_stroke_paint.table().attach(*strokeWdgt, 0, 1, 0, 1); + +#if WITH_GTKMM_3_0 + _page_stroke_paint->table().attach(*strokeWdgt, 0, 0, 1, 1); +#else + _page_stroke_paint->table().attach(*strokeWdgt, 0, 1, 0, 1); +#endif } void FillAndStroke::_layoutPageStrokeStyle() { - //Gtk::Widget *ssl = manage(Glib::wrap(sp_stroke_style_line_widget_new())); - //Gtk::Widget *ssl = static_cast<Gtk::Widget *>(sp_stroke_style_line_widget_new()); - Gtk::Widget *ssl = sp_stroke_style_line_widget_new(); - _page_stroke_style.table().attach(*ssl, 0, 1, 0, 1); + //Gtk::Widget *strokeStyleWdgt = manage(Glib::wrap(sp_stroke_style_line_widget_new())); + //Gtk::Widget *strokeStyleWdgt = static_cast<Gtk::Widget *>(sp_stroke_style_line_widget_new()); + strokeStyleWdgt = sp_stroke_style_line_widget_new(); + +#if WITH_GTKMM_3_0 + _page_stroke_style->table().attach(*strokeStyleWdgt, 0, 0, 1, 1); +#else + _page_stroke_style->table().attach(*strokeStyleWdgt, 0, 1, 0, 1); +#endif } void @@ -129,6 +171,8 @@ FillAndStroke::showPageFill() { present(); _notebook.set_current_page(0); + _savePagePref(0); + } void @@ -136,6 +180,7 @@ FillAndStroke::showPageStrokePaint() { present(); _notebook.set_current_page(1); + _savePagePref(1); } void @@ -143,12 +188,14 @@ FillAndStroke::showPageStrokeStyle() { present(); _notebook.set_current_page(2); + _savePagePref(2); + } Gtk::HBox& FillAndStroke::_createPageTabLabel(const Glib::ustring& label, const char *label_image) { - Gtk::HBox *_tab_label_box = manage(new Gtk::HBox(false, 0)); + Gtk::HBox *_tab_label_box = manage(new Gtk::HBox(false, 4)); _tab_label_box->pack_start(*Glib::wrap(sp_icon_new(Inkscape::ICON_SIZE_DECORATION, label_image))); diff --git a/src/ui/dialog/fill-and-stroke.h b/src/ui/dialog/fill-and-stroke.h index f388d2873..340cb860f 100644 --- a/src/ui/dialog/fill-and-stroke.h +++ b/src/ui/dialog/fill-and-stroke.h @@ -16,7 +16,6 @@ #define INKSCAPE_UI_DIALOG_FILL_AND_STROKE_H #include "ui/widget/panel.h" -#include "ui/widget/notebook-page.h" #include "ui/widget/object-composite-settings.h" #include "ui/dialog/desktop-tracker.h" @@ -25,6 +24,11 @@ namespace Inkscape { namespace UI { + +namespace Widget { +class NotebookPage; +} + namespace Dialog { class FillAndStroke : public UI::Widget::Panel { @@ -47,9 +51,9 @@ public: protected: Gtk::Notebook _notebook; - UI::Widget::NotebookPage _page_fill; - UI::Widget::NotebookPage _page_stroke_paint; - UI::Widget::NotebookPage _page_stroke_style; + UI::Widget::NotebookPage *_page_fill; + UI::Widget::NotebookPage *_page_stroke_paint; + UI::Widget::NotebookPage *_page_stroke_style; UI::Widget::StyleSubject::Selection _subject; UI::Widget::ObjectCompositeSettings _composite_settings; @@ -60,6 +64,12 @@ protected: void _layoutPageFill(); void _layoutPageStrokePaint(); void _layoutPageStrokeStyle(); + void _savePagePref(guint page_num); +#if WITH_GTKMM_3_0 + void _onSwitchPage(Gtk::Widget *page, guint pagenum); +#else + void _onSwitchPage(GtkNotebookPage *page, guint pagenum); +#endif private: FillAndStroke(FillAndStroke const &d); @@ -71,6 +81,7 @@ private: SPDesktop *targetDesktop; Gtk::Widget *fillWdgt; Gtk::Widget *strokeWdgt; + Gtk::Widget *strokeStyleWdgt; sigc::connection desktopChangeConn; }; diff --git a/src/ui/dialog/filter-effects-dialog.cpp b/src/ui/dialog/filter-effects-dialog.cpp index 4af328b49..c2367c2a2 100644 --- a/src/ui/dialog/filter-effects-dialog.cpp +++ b/src/ui/dialog/filter-effects-dialog.cpp @@ -19,8 +19,18 @@ #endif #include "dialog-manager.h" +#include <gtkmm/imagemenuitem.h> + +#if GTK_CHECK_VERSION(3,0,0) +# include <gdkmm/devicemanager.h> +#endif + #include "ui/widget/spinbutton.h" + +#include <glibmm/convert.h> #include <glibmm/i18n.h> +#include <glibmm/main.h> +#include <glibmm/stringutils.h> #include "desktop.h" #include "desktop-handles.h" @@ -37,6 +47,7 @@ #include "filters/blend.h" #include "filters/colormatrix.h" #include "filters/componenttransfer.h" +#include "filters/componenttransfer-funcnode.h" #include "filters/composite.h" #include "filters/convolvematrix.h" #include "filters/displacementmap.h" @@ -61,6 +72,7 @@ #include "io/sys.h" #include <iostream> +#include "selection-chemistry.h" #include <gtkmm/checkbutton.h> #include <gtkmm/colorbutton.h> @@ -77,12 +89,12 @@ namespace Dialog { using Inkscape::UI::Widget::AttrWidget; using Inkscape::UI::Widget::ComboBoxEnum; -using Inkscape::UI::Widget::DualSpinSlider; -using Inkscape::UI::Widget::SpinSlider; +using Inkscape::UI::Widget::DualSpinScale; +using Inkscape::UI::Widget::SpinScale; // Returns the number of inputs available for the filter primitive type -int input_count(const SPFilterPrimitive* prim) +static int input_count(const SPFilterPrimitive* prim) { if(!prim) return 0; @@ -306,9 +318,15 @@ public: set_tooltip_text(tip_text); } +#if WITH_GTKMM_3_0 + Gdk::RGBA col; + col.set_rgba_u(65535, 65535, 65535); + set_rgba(col); +#else Gdk::Color col; col.set_rgb(65535, 65535, 65535); set_color(col); +#endif } // Returns the color in 'rgb(r,g,b)' form. @@ -316,8 +334,14 @@ public: { // no doubles here, so we can use the standard string stream. std::ostringstream os; + +#if WITH_GTKMM_3_0 + const Gdk::RGBA c = get_rgba(); + const int r = c.get_red_u() / 257, g = c.get_green_u() / 257, b = c.get_blue_u() / 257;//TO-DO: verify this. This sounds a lot strange! shouldn't it be 256? +#else const Gdk::Color c = get_color(); const int r = c.get_red() / 257, g = c.get_green() / 257, b = c.get_blue() / 257;//TO-DO: verify this. This sounds a lot strange! shouldn't it be 256? +#endif os << "rgb(" << r << "," << g << "," << b << ")"; return os.str(); } @@ -333,9 +357,46 @@ public: i = (guint32) get_default()->as_uint(); } const int r = SP_RGBA32_R_U(i), g = SP_RGBA32_G_U(i), b = SP_RGBA32_B_U(i); + +#if WITH_GTKMM_3_0 + Gdk::RGBA col; + col.set_rgba_u(r * 256, g * 256, b * 256); + set_rgba(col); +#else Gdk::Color col; col.set_rgb(r * 256, g * 256, b * 256); set_color(col); +#endif + } +}; + +// Used for tableValue in feComponentTransfer +class EntryAttr : public Gtk::Entry, public AttrWidget +{ +public: + EntryAttr(const SPAttributeEnum a, char* tip_text) + : AttrWidget(a) + { + signal_changed().connect(signal_attr_changed().make_slot()); + if (tip_text) { + set_tooltip_text(tip_text); + } + } + + // No validity checking is done + Glib::ustring get_as_attribute() const + { + return get_text(); + } + + void set_from_attribute(SPObject* o) + { + const gchar* val = attribute_value(o); + if(val) { + set_text( val ); + } else { + set_text( "" ); + } } }; @@ -483,13 +544,9 @@ public: : AttrWidget(SP_ATTR_VALUES), // TRANSLATORS: this dialog is accessible via menu Filters - Filter editor _matrix(SP_ATTR_VALUES, _("This matrix determines a linear transform on color space. Each line affects one of the color components. Each column determines how much of each color component from the input is passed to the output. The last column does not depend on input colors, so can be used to adjust a constant component value.")), - _saturation(0, 0, 1, 0.1, 0.01, 2, SP_ATTR_VALUES), - _angle(0, 0, 360, 0.1, 0.01, 1, SP_ATTR_VALUES), -#if WITH_GTKMM_2_22 + _saturation("", 0, 0, 1, 0.1, 0.01, 2, SP_ATTR_VALUES), + _angle("", 0, 0, 360, 0.1, 0.01, 1, SP_ATTR_VALUES), _label(_("None"), Gtk::ALIGN_START), -#else - _label(_("None"), Gtk::ALIGN_LEFT), -#endif _use_stored(false), _saturation_store(0), _angle_store(0) @@ -570,8 +627,8 @@ private: } MatrixAttr _matrix; - SpinSlider _saturation; - SpinSlider _angle; + SpinScale _saturation; + SpinScale _angle; Gtk::Label _label; // Store separate values for the different color modes @@ -720,7 +777,7 @@ public: _groups[i] = new Gtk::VBox; b.pack_start(*_groups[i], false, false); } - _current_type = 0; + //_current_type = 0; If set to 0 then update_and_show() fails to update properly. } ~Settings() @@ -740,9 +797,9 @@ public: for(unsigned i = 0; i < _groups.size(); ++i) _groups[i]->hide(); } - if(t >= 0) - _groups[t]->show_all(); - + if(t >= 0) { + _groups[t]->show(); // Do not use show_all(), it shows children than should be hidden + } _dialog.set_attrs_locked(true); for(unsigned i = 0; i < _attrwidgets[_current_type].size(); ++i) _attrwidgets[_current_type][i]->set_from_attribute(ob); @@ -774,7 +831,10 @@ public: // LightSource LightSourceControl* add_lightsource(); - // CheckBox + // Component Transfer Values + ComponentTransferValues* add_componenttransfervalues(const Glib::ustring& label, SPFeFuncNode::Channel channel); + + // CheckButton CheckButtonAttr* add_checkbutton(bool def, const SPAttributeEnum attr, const Glib::ustring& label, const Glib::ustring& tv, const Glib::ustring& fv, char* tip_text = NULL) { @@ -811,22 +871,22 @@ public: return cmv; } - // SpinSlider - SpinSlider* add_spinslider(double def, const SPAttributeEnum attr, const Glib::ustring& label, + // SpinScale + SpinScale* add_spinscale(double def, const SPAttributeEnum attr, const Glib::ustring& label, const double lo, const double hi, const double step_inc, const double climb, const int digits, char* tip_text = NULL) { - SpinSlider* spinslider = new SpinSlider(def, lo, hi, step_inc, climb, digits, attr, tip_text); + SpinScale* spinslider = new SpinScale("", def, lo, hi, step_inc, climb, digits, attr, tip_text); add_widget(spinslider, label); add_attr_widget(spinslider); return spinslider; } - // DualSpinSlider - DualSpinSlider* add_dualspinslider(const SPAttributeEnum attr, const Glib::ustring& label, + // DualSpinScale + DualSpinScale* add_dualspinscale(const SPAttributeEnum attr, const Glib::ustring& label, const double lo, const double hi, const double step_inc, const double climb, const int digits, char* tip_text1 = NULL, char* tip_text2 = NULL) { - DualSpinSlider* dss = new DualSpinSlider(lo, lo, hi, step_inc, climb, digits, attr, tip_text1, tip_text2); + DualSpinScale* dss = new DualSpinScale("", "", lo, lo, hi, step_inc, climb, digits, attr, tip_text1, tip_text2); add_widget(dss, label); add_attr_widget(dss); return dss; @@ -912,6 +972,18 @@ public: add_attr_widget(combo->get_attrwidget()); return combo->get_attrwidget(); } + + // Entry + EntryAttr* add_entry(const SPAttributeEnum attr, + const Glib::ustring& label, + char* tip_text = NULL) + { + EntryAttr* entry = new EntryAttr(attr, tip_text); + add_widget(entry, label); + add_attr_widget(entry); + return entry; + } + private: void add_attr_widget(AttrWidget* a) { @@ -923,17 +995,11 @@ private: and all widgets within the setting group are aligned automatically. */ void add_widget(Gtk::Widget* w, const Glib::ustring& label) { - Gtk::Label *lbl = 0; Gtk::HBox *hb = Gtk::manage(new Gtk::HBox); hb->set_spacing(12); if(label != "") { - //lbl = Gtk::manage(new Gtk::Label(label + (label == "" ? "" : ":"), Gtk::ALIGN_LEFT)); colon now in label (LP #358921) -#if WITH_GTKMM_2_22 - lbl = Gtk::manage(new Gtk::Label(label, Gtk::ALIGN_START)); -#else - lbl = Gtk::manage(new Gtk::Label(label, Gtk::ALIGN_LEFT)); -#endif + Gtk::Label *lbl = Gtk::manage(new Gtk::Label(label, Gtk::ALIGN_START)); hb->pack_start(*lbl, false, false); _size_group->add_widget(*lbl); lbl->show(); @@ -953,6 +1019,154 @@ private: int _current_type, _max_types; }; +// Displays sliders and/or tables for feComponentTransfer +class FilterEffectsDialog::ComponentTransferValues : public Gtk::Frame, public AttrWidget +{ +public: + ComponentTransferValues(FilterEffectsDialog& d, SPFeFuncNode::Channel channel) + : AttrWidget(SP_ATTR_INVALID), + _dialog(d), + _settings(d, _box, sigc::mem_fun(*this, &ComponentTransferValues::set_func_attr), COMPONENTTRANSFER_TYPE_ERROR), + _type(ComponentTransferTypeConverter, SP_ATTR_TYPE, false), + _channel(channel), + _funcNode(NULL) + { + set_shadow_type(Gtk::SHADOW_IN); + add(_box); + _box.add(_type); + _box.reorder_child(_type, 0); + _type.signal_changed().connect(sigc::mem_fun(*this, &ComponentTransferValues::on_type_changed)); + + _settings.type(COMPONENTTRANSFER_TYPE_LINEAR); + _settings.add_spinscale(1, SP_ATTR_SLOPE, _("Slope"), -10, 10, 0.1, 0.01, 2); + _settings.add_spinscale(0, SP_ATTR_INTERCEPT, _("Intercept"), -10, 10, 0.1, 0.01, 2); + + _settings.type(COMPONENTTRANSFER_TYPE_GAMMA); + _settings.add_spinscale(1, SP_ATTR_AMPLITUDE, _("Amplitude"), 0, 10, 0.1, 0.01, 2); + _settings.add_spinscale(1, SP_ATTR_EXPONENT, _("Exponent"), 0, 10, 0.1, 0.01, 2); + _settings.add_spinscale(0, SP_ATTR_OFFSET, _("Offset"), -10, 10, 0.1, 0.01, 2); + + _settings.type(COMPONENTTRANSFER_TYPE_TABLE); + _settings.add_entry(SP_ATTR_TABLEVALUES, _("Table")); + + _settings.type(COMPONENTTRANSFER_TYPE_DISCRETE); + _settings.add_entry(SP_ATTR_TABLEVALUES, _("Discrete")); + + //_settings.type(COMPONENTTRANSFER_TYPE_IDENTITY); + _settings.type(-1); // Force update_and_show() to show/hide windows correctly + } + + // FuncNode can be in any order so we must search to find correct one. + SPFeFuncNode* find_node(SPFeComponentTransfer* ct) + { + SPObject* node = ct->children; + SPFeFuncNode* funcNode = NULL; + bool found = false; + for(;node;node=node->next){ + funcNode = SP_FEFUNCNODE(node); + if( funcNode->channel == _channel ) { + found = true; + break; + } + } + if( !found ) + funcNode = NULL; + + return funcNode; + } + + void set_func_attr(const AttrWidget* input) + { + _dialog.set_attr( _funcNode, input->get_attribute(), input->get_as_attribute().c_str()); + } + + // Set new type and update widget visibility + virtual void set_from_attribute(SPObject* o) + { + // See componenttransfer.cpp + if(SP_IS_FECOMPONENTTRANSFER(o)) { + SPFeComponentTransfer* ct = SP_FECOMPONENTTRANSFER(o); + + _funcNode = find_node(ct); + if( _funcNode ) { + _type.set_from_attribute( _funcNode ); + } else { + // Create <funcNode> + SPFilterPrimitive* prim = _dialog._primitive_list.get_selected(); + if(prim) { + Inkscape::XML::Document *xml_doc = prim->document->getReprDoc(); + Inkscape::XML::Node *repr = NULL; + switch(_channel) { + case SPFeFuncNode::R: + repr = xml_doc->createElement("svg:feFuncR"); + break; + case SPFeFuncNode::G: + repr = xml_doc->createElement("svg:feFuncG"); + break; + case SPFeFuncNode::B: + repr = xml_doc->createElement("svg:feFuncB"); + break; + case SPFeFuncNode::A: + repr = xml_doc->createElement("svg:feFuncA"); + break; + } + + //XML Tree being used directly here while it shouldn't be. + prim->getRepr()->appendChild(repr); + Inkscape::GC::release(repr); + + // Now we should find it! + _funcNode = find_node(ct); + if( _funcNode ) { + _funcNode->setAttribute( "type", "identity" ); + } else { + //std::cout << "ERROR ERROR: feFuncX not found!" << std::endl; + } + } + } + + update(); + } + } + +private: + void on_type_changed() + { + SPFilterPrimitive* prim = _dialog._primitive_list.get_selected(); + if(prim) { + + _funcNode->getRepr()->setAttribute( "type", _type.get_as_attribute().c_str() ); + + SPFilter* filter = _dialog._filter_modifier.get_selected_filter(); + filter->requestModified(SP_OBJECT_MODIFIED_FLAG); + + DocumentUndo::done(prim->document, SP_VERB_DIALOG_FILTER_EFFECTS, _("New transfer function type")); + update(); + } + } + + void update() + { + SPFilterPrimitive* prim = _dialog._primitive_list.get_selected(); + if(prim && _funcNode) { + _settings.show_and_update(_type.get_active_data()->id, _funcNode); + } + } + +public: + virtual Glib::ustring get_as_attribute() const + { + return ""; + } + + FilterEffectsDialog& _dialog; + Gtk::VBox _box; + Settings _settings; + ComboBoxEnum<FilterComponentTransferType> _type; + SPFeFuncNode::Channel _channel; // RGBA + SPFeFuncNode* _funcNode; +}; + // Settings for the three light source objects class FilterEffectsDialog::LightSourceControl : public AttrWidget { @@ -961,11 +1175,7 @@ public: : AttrWidget(SP_ATTR_INVALID), _dialog(d), _settings(d, _box, sigc::mem_fun(_dialog, &FilterEffectsDialog::set_child_attr_direct), LIGHT_ENDSOURCE), -#if WITH_GTKMM_2_22 _light_label(_("Light Source:"), Gtk::ALIGN_START), -#else - _light_label(_("Light Source:"), Gtk::ALIGN_LEFT), -#endif _light_source(LightSourceConverter), _locked(false) { @@ -982,8 +1192,8 @@ public: // FIXME: these range values are complete crap _settings.type(LIGHT_DISTANT); - _settings.add_spinslider(0, SP_ATTR_AZIMUTH, _("Azimuth"), 0, 360, 1, 1, 0, _("Direction angle for the light source on the XY plane, in degrees")); - _settings.add_spinslider(0, SP_ATTR_ELEVATION, _("Elevation"), 0, 360, 1, 1, 0, _("Direction angle for the light source on the YZ plane, in degrees")); + _settings.add_spinscale(0, SP_ATTR_AZIMUTH, _("Azimuth"), 0, 360, 1, 1, 0, _("Direction angle for the light source on the XY plane, in degrees")); + _settings.add_spinscale(0, SP_ATTR_ELEVATION, _("Elevation"), 0, 360, 1, 1, 0, _("Direction angle for the light source on the YZ plane, in degrees")); _settings.type(LIGHT_POINT); _settings.add_multispinbutton(/*default x:*/ (double) 0, /*default y:*/ (double) 0, /*default z:*/ (double) 0, SP_ATTR_X, SP_ATTR_Y, SP_ATTR_Z, _("Location:"), -99999, 99999, 1, 100, 0, _("X coordinate"), _("Y coordinate"), _("Z coordinate")); @@ -993,9 +1203,12 @@ public: _settings.add_multispinbutton(/*default x:*/ (double) 0, /*default y:*/ (double) 0, /*default z:*/ (double) 0, SP_ATTR_POINTSATX, SP_ATTR_POINTSATY, SP_ATTR_POINTSATZ, _("Points At"), -99999, 99999, 1, 100, 0, _("X coordinate"), _("Y coordinate"), _("Z coordinate")); - _settings.add_spinslider(1, SP_ATTR_SPECULAREXPONENT, _("Specular Exponent"), 1, 100, 1, 1, 0, _("Exponent value controlling the focus for the light source")); + _settings.add_spinscale(1, SP_ATTR_SPECULAREXPONENT, _("Specular Exponent"), 1, 100, 1, 1, 0, _("Exponent value controlling the focus for the light source")); //TODO: here I have used 100 degrees as default value. But spec says that if not specified, no limiting cone is applied. So, there should be a way for the user to set a "no limiting cone" option. - _settings.add_spinslider(100, SP_ATTR_LIMITINGCONEANGLE, _("Cone Angle"), 1, 100, 1, 1, 0, _("This is the angle between the spot light axis (i.e. the axis between the light source and the point to which it is pointing at) and the spot light cone. No light is projected outside this cone.")); + _settings.add_spinscale(100, SP_ATTR_LIMITINGCONEANGLE, _("Cone Angle"), 1, 100, 1, 1, 0, _("This is the angle between the spot light axis (i.e. the axis between the light source and the point to which it is pointing at) and the spot light cone. No light is projected outside this cone.")); + + _settings.type(-1); // Force update_and_show() to show/hide windows correctly + } Gtk::VBox& get_box() @@ -1068,11 +1281,7 @@ private: void update() { -#if WITH_GTKMM_2_24 - _box.hide(); -#else - _box.hide_all(); -#endif + _box.hide(); _box.show(); _light_box.show_all(); @@ -1090,6 +1299,16 @@ private: bool _locked; }; + // ComponentTransferValues +FilterEffectsDialog::ComponentTransferValues* FilterEffectsDialog::Settings::add_componenttransfervalues(const Glib::ustring& label, SPFeFuncNode::Channel channel) + { + ComponentTransferValues* ct = new ComponentTransferValues(_dialog, channel); + add_widget(ct, label); + add_attr_widget(ct); + return ct; + } + + FilterEffectsDialog::LightSourceControl* FilterEffectsDialog::Settings::add_lightsource() { LightSourceControl* ls = new LightSourceControl(_dialog); @@ -1098,13 +1317,17 @@ FilterEffectsDialog::LightSourceControl* FilterEffectsDialog::Settings::add_ligh return ls; } -Glib::RefPtr<Gtk::Menu> create_popup_menu(Gtk::Widget& parent, sigc::slot<void> dup, - sigc::slot<void> rem) +static Glib::RefPtr<Gtk::Menu> create_popup_menu(Gtk::Widget& parent, sigc::slot<void> dup, + sigc::slot<void> rem) { Glib::RefPtr<Gtk::Menu> menu(new Gtk::Menu); - menu->items().push_back(Gtk::Menu_Helpers::MenuElem(_("_Duplicate"), dup)); - Gtk::MenuItem* mi = Gtk::manage(new Gtk::ImageMenuItem(Gtk::Stock::REMOVE)); + Gtk::MenuItem* mi = Gtk::manage(new Gtk::MenuItem(_("_Duplicate"),true)); + mi->signal_activate().connect(dup); + mi->show(); + menu->append(*mi); + + mi = Gtk::manage(new Gtk::ImageMenuItem(Gtk::Stock::REMOVE)); menu->append(*mi); mi->signal_activate().connect(rem); mi->show(); @@ -1115,7 +1338,11 @@ Glib::RefPtr<Gtk::Menu> create_popup_menu(Gtk::Widget& parent, sigc::slot<void> /*** FilterModifier ***/ FilterEffectsDialog::FilterModifier::FilterModifier(FilterEffectsDialog& d) - : _dialog(d), _add(Gtk::Stock::NEW), _observer(new Inkscape::XML::SignalObserver) + : _desktop(NULL), + _deskTrack(), + _dialog(d), + _add(Gtk::Stock::NEW), + _observer(new Inkscape::XML::SignalObserver) { Gtk::ScrolledWindow* sw = Gtk::manage(new Gtk::ScrolledWindow); pack_start(*sw); @@ -1130,15 +1357,16 @@ FilterEffectsDialog::FilterModifier::FilterModifier(FilterEffectsDialog& d) if(col) col->add_attribute(_cell_toggle.property_active(), _columns.sel); _list.append_column_editable(_("_Filter"), _columns.label); -#if WITH_GTKMM_2_24 ((Gtk::CellRendererText*)_list.get_column(1)->get_first_cell())-> signal_edited().connect(sigc::mem_fun(*this, &FilterEffectsDialog::FilterModifier::on_name_edited)); -#else - ((Gtk::CellRendererText*)_list.get_column(1)->get_first_cell_renderer())-> - signal_edited().connect(sigc::mem_fun(*this, &FilterEffectsDialog::FilterModifier::on_name_edited)); -#endif - sw->set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); + sw->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); + _list.get_column(1)->set_resizable(true); + _list.set_reorderable(true); + _list.enable_model_drag_dest (Gdk::ACTION_MOVE); + + _list.signal_drag_drop().connect( sigc::mem_fun(*this, &FilterModifier::on_filter_move), false ); + sw->set_shadow_type(Gtk::SHADOW_IN); show_all_children(); _add.signal_clicked().connect(sigc::mem_fun(*this, &FilterModifier::add_filter)); @@ -1147,60 +1375,83 @@ FilterEffectsDialog::FilterModifier::FilterModifier(FilterEffectsDialog& d) sigc::mem_fun(*this, &FilterModifier::filter_list_button_release)); _menu = create_popup_menu(*this, sigc::mem_fun(*this, &FilterModifier::duplicate_filter), sigc::mem_fun(*this, &FilterModifier::remove_filter)); - _menu->items().push_back(Gtk::Menu_Helpers::MenuElem( - _("R_ename"), sigc::mem_fun(*this, &FilterModifier::rename_filter))); + + Gtk::MenuItem *item = Gtk::manage(new Gtk::MenuItem(_("R_ename"), true)); + item->signal_activate().connect(sigc::mem_fun(*this, &FilterModifier::rename_filter)); + item->show(); + _menu->append(*item); _menu->accelerate(*this); _list.get_selection()->signal_changed().connect(sigc::mem_fun(*this, &FilterModifier::on_filter_selection_changed)); _observer->signal_changed().connect(signal_filter_changed().make_slot()); - g_signal_connect(G_OBJECT(INKSCAPE), "change_selection", - G_CALLBACK(&FilterModifier::on_inkscape_change_selection), this); - g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop", - G_CALLBACK(&FilterModifier::on_activate_desktop), this); - g_signal_connect(G_OBJECT(INKSCAPE), "deactivate_desktop", - G_CALLBACK(&FilterModifier::on_deactivate_desktop), this); + desktopChangeConn = _deskTrack.connectDesktopChanged( sigc::mem_fun(*this, &FilterModifier::setTargetDesktop) ); + _deskTrack.connect(GTK_WIDGET(gobj())); - on_activate_desktop(INKSCAPE, d.getDesktop(), this); update_filters(); } FilterEffectsDialog::FilterModifier::~FilterModifier() { + _selectChangedConn.disconnect(); + _selectModifiedConn.disconnect(); _resource_changed.disconnect(); _doc_replaced.disconnect(); } -void FilterEffectsDialog::FilterModifier::on_activate_desktop(Application*, SPDesktop* desktop, FilterModifier* me) +void FilterEffectsDialog::FilterModifier::setTargetDesktop(SPDesktop *desktop) { - me->_doc_replaced.disconnect(); - me->_doc_replaced = desktop->connectDocumentReplaced( - sigc::mem_fun(me, &FilterModifier::on_document_replaced)); + if (_desktop != desktop) { + if (_desktop) { + _selectChangedConn.disconnect(); + _selectModifiedConn.disconnect(); + _doc_replaced.disconnect(); + _resource_changed.disconnect(); + _dialog.setDesktop(NULL); + } + _desktop = desktop; + if (desktop) { + if (desktop->selection) { + _selectChangedConn = desktop->selection->connectChanged(sigc::hide(sigc::mem_fun(*this, &FilterModifier::on_change_selection))); + _selectModifiedConn = desktop->selection->connectModified(sigc::hide<0>(sigc::mem_fun(*this, &FilterModifier::on_modified_selection))); + } + _doc_replaced = desktop->connectDocumentReplaced( sigc::mem_fun(*this, &FilterModifier::on_document_replaced)); + _resource_changed = sp_desktop_document(desktop)->connectResourcesChanged("filter",sigc::mem_fun(*this, &FilterModifier::update_filters)); + _dialog.setDesktop(desktop); - me->_resource_changed.disconnect(); - me->_resource_changed = - sp_desktop_document(desktop)->connectResourcesChanged("filter",sigc::mem_fun(me, &FilterModifier::update_filters)); + update_filters(); + } + } +} - me->_dialog.setDesktop(desktop); +// When the document changes, update connection to resources +void FilterEffectsDialog::FilterModifier::on_document_replaced(SPDesktop * /*desktop*/, SPDocument *document) +{ + if (_resource_changed) { + _resource_changed.disconnect(); + } + if (document) + { + _resource_changed = document->connectResourcesChanged("filter",sigc::mem_fun(*this, &FilterModifier::update_filters)); + } - me->update_filters(); + update_filters(); } -void FilterEffectsDialog::FilterModifier::on_deactivate_desktop(Application*, SPDesktop* /*desktop*/, FilterModifier* me) +// When the selection changes, show the active filter(s) in the dialog +void FilterEffectsDialog::FilterModifier::on_change_selection() { - me->_doc_replaced.disconnect(); - me->_resource_changed.disconnect(); - me->_dialog.setDesktop(NULL); + Inkscape::Selection *selection = sp_desktop_selection (SP_ACTIVE_DESKTOP); + update_selection(selection); } - -// When the selection changes, show the active filter(s) in the dialog -void FilterEffectsDialog::FilterModifier::on_inkscape_change_selection(Application */*inkscape*/, - Selection *sel, - FilterModifier* fm) +void FilterEffectsDialog::FilterModifier::on_modified_selection( guint flags ) { - if(fm && sel) - fm->update_selection(sel); + if (flags & ( SP_OBJECT_MODIFIED_FLAG | + SP_OBJECT_PARENT_MODIFIED_FLAG | + SP_OBJECT_STYLE_MODIFIED_FLAG) ) { + on_change_selection(); + } } // Update each filter's sel property based on the current object selection; @@ -1209,6 +1460,10 @@ void FilterEffectsDialog::FilterModifier::on_inkscape_change_selection(Applicati // If only one filter is in use, it is selected void FilterEffectsDialog::FilterModifier::update_selection(Selection *sel) { + if (!sel) { + return; + } + std::set<SPObject*> used; for (GSList const *i = sel->itemList(); i != NULL; i = i->next) { @@ -1219,6 +1474,7 @@ void FilterEffectsDialog::FilterModifier::update_selection(Selection *sel) } if (style->filter.set && style->getFilter()) { + SP_ITEM(obj)->bbox_valid = FALSE; used.insert(style->getFilter()); } else { used.insert(0); @@ -1259,6 +1515,22 @@ void FilterEffectsDialog::FilterModifier::on_name_edited(const Glib::ustring& pa } } +bool FilterEffectsDialog::FilterModifier::on_filter_move(const Glib::RefPtr<Gdk::DragContext>& /*context*/, int /*x*/, int /*y*/, guint /*time*/) { + +//const Gtk::TreeModel::Path& /*path*/) { +/* The code below is bugged. Use of "object->getRepr()->setPosition(0)" is dangerous! + Writing back the reordered list to XML (reordering XML nodes) should be implemented differently. + Note that the dialog does also not update its list of filters when the order is manually changed + using the XML dialog + for(Gtk::TreeModel::iterator i = _model->children().begin(); i != _model->children().end(); ++i) { + SPObject* object = (*i)[_columns.filter]; + if(object && object->getRepr()) ; + object->getRepr()->setPosition(0); + } +*/ + return false; +} + void FilterEffectsDialog::FilterModifier::on_selection_toggled(const Glib::ustring& path) { Gtk::TreeIter iter = _model->get_iter(path); @@ -1306,7 +1578,7 @@ void FilterEffectsDialog::FilterModifier::update_filters() for(const GSList *l = filters; l; l = l->next) { Gtk::TreeModel::Row row = *_model->append(); - SPFilter* f = (SPFilter*)l->data; + SPFilter* f = SP_FILTER(l->data); row[_columns.filter] = f; const gchar* lbl = f->label(); const gchar* id = f->getId(); @@ -1346,8 +1618,9 @@ void FilterEffectsDialog::FilterModifier::filter_list_button_release(GdkEventBut { if((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)) { const bool sensitive = get_selected_filter() != NULL; - _menu->items()[0].set_sensitive(sensitive); - _menu->items()[1].set_sensitive(sensitive); + std::vector<Gtk::Widget*> items = _menu->get_children(); + items[0]->set_sensitive(sensitive); + items[1]->set_sensitive(sensitive); _menu->popup(event->button, event->time); } } @@ -1376,6 +1649,29 @@ void FilterEffectsDialog::FilterModifier::remove_filter() if(filter) { SPDocument* doc = filter->document; + // Delete all references to this filter + GSList *all = get_all_items(NULL, _desktop->currentRoot(), _desktop, false, false, true, NULL); + for (GSList *i = all; i != NULL; i = i->next) { + if (!SP_IS_ITEM(i->data)) { + continue; + } + SPItem *item = SP_ITEM(i->data); + if (!item->style) { + continue; + } + + const SPIFilter *ifilter = &(item->style->filter); + if (ifilter && ifilter->href) { + const SPObject *obj = ifilter->href->getObject(); + if (obj && obj == (SPObject *)filter) { + ::remove_filter(item, false); + } + } + } + if (all) { + g_slist_free(all); + } + //XML Tree being used directly here while it shouldn't be. sp_repr_unparent(filter->getRepr()); @@ -1417,6 +1713,41 @@ Glib::PropertyProxy<void*> FilterEffectsDialog::CellRendererConnection::property return _primitive.get_proxy(); } +#if WITH_GTKMM_3_0 +void FilterEffectsDialog::CellRendererConnection::get_preferred_width_vfunc(Gtk::Widget& widget, + int& minimum_width, + int& natural_width) const +{ + PrimitiveList& primlist = dynamic_cast<PrimitiveList&>(widget); + minimum_width = natural_width = size * primlist.primitive_count() + primlist.get_input_type_width() * 6; +} + +void FilterEffectsDialog::CellRendererConnection::get_preferred_width_for_height_vfunc(Gtk::Widget& widget, + int /* height */, + int& minimum_width, + int& natural_width) const +{ + get_preferred_width(widget, minimum_width, natural_width); +} + +void FilterEffectsDialog::CellRendererConnection::get_preferred_height_vfunc(Gtk::Widget& widget, + int& minimum_height, + int& natural_height) const +{ + // Scale the height depending on the number of inputs, unless it's + // the first primitive, in which case there are no connections + SPFilterPrimitive* prim = SP_FILTER_PRIMITIVE(_primitive.get_value()); + minimum_height = natural_height = size * input_count(prim); +} + +void FilterEffectsDialog::CellRendererConnection::get_preferred_height_for_width_vfunc(Gtk::Widget& widget, + int /* width */, + int& minimum_height, + int& natural_height) const +{ + get_preferred_height(widget, minimum_height, natural_height); +} +#else void FilterEffectsDialog::CellRendererConnection::get_size_vfunc( Gtk::Widget& widget, const Gdk::Rectangle* /*cell_area*/, int* x_offset, int* y_offset, int* width, int* height) const @@ -1432,10 +1763,11 @@ void FilterEffectsDialog::CellRendererConnection::get_size_vfunc( if(height) { // Scale the height depending on the number of inputs, unless it's // the first primitive, in which case there are no connections - SPFilterPrimitive* prim = (SPFilterPrimitive*)_primitive.get_value(); + SPFilterPrimitive* prim = SP_FILTER_PRIMITIVE(_primitive.get_value()); (*height) = size * input_count(prim); } } +#endif /*** PrimitiveList ***/ FilterEffectsDialog::PrimitiveList::PrimitiveList(FilterEffectsDialog& d) @@ -1443,10 +1775,15 @@ FilterEffectsDialog::PrimitiveList::PrimitiveList(FilterEffectsDialog& d) _in_drag(0), _observer(new Inkscape::XML::SignalObserver) { +#if WITH_GTKMM_3_0 + d.signal_draw().connect(sigc::mem_fun(*this, &PrimitiveList::on_draw_signal)); + signal_draw().connect(sigc::mem_fun(*this, &PrimitiveList::on_draw_signal)); +#else d.signal_expose_event().connect(sigc::mem_fun(*this, &PrimitiveList::on_expose_signal)); + signal_expose_event().connect(sigc::mem_fun(*this, &PrimitiveList::on_expose_signal)); +#endif add_events(Gdk::POINTER_MOTION_MASK | Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK); - signal_expose_event().connect(sigc::mem_fun(*this, &PrimitiveList::on_expose_signal)); _model = Gtk::ListStore::create(_columns); @@ -1454,6 +1791,8 @@ FilterEffectsDialog::PrimitiveList::PrimitiveList(FilterEffectsDialog& d) set_model(_model); append_column(_("_Effect"), _columns.type); + get_column(0)->set_resizable(true); + set_headers_visible(); _observer->signal_changed().connect(signal_primitive_changed().make_slot()); get_selection()->signal_changed().connect(sigc::mem_fun(*this, &PrimitiveList::on_primitive_selection_changed)); @@ -1509,11 +1848,10 @@ void FilterEffectsDialog::PrimitiveList::update() { SPFilter* f = _dialog._filter_modifier.get_selected_filter(); const SPFilterPrimitive* active_prim = get_selected(); - bool active_found = false; - _model->clear(); if(f) { + bool active_found = false; _dialog._primitive_box.set_sensitive(true); _dialog.update_filter_general_settings_view(); for(SPObject *prim_obj = f->children; @@ -1527,8 +1865,11 @@ void FilterEffectsDialog::PrimitiveList::update() //XML Tree being used directly here while it shouldn't be. row[_columns.type_id] = FPConverter.get_id_from_key(prim->getRepr()->name()); row[_columns.type] = _(FPConverter.get_label(row[_columns.type_id]).c_str()); - row[_columns.id] = prim->getId(); - + + if (prim->getId()) { + row[_columns.id] = Glib::ustring(prim->getId()); + } + if(prim == active_prim) { get_selection()->select(row); active_found = true; @@ -1603,12 +1944,53 @@ void FilterEffectsDialog::PrimitiveList::remove_selected() } } -bool FilterEffectsDialog::PrimitiveList::on_expose_signal(GdkEventExpose* e) +#if !WITH_GTKMM_3_0 +bool FilterEffectsDialog::PrimitiveList::on_expose_signal(GdkEventExpose * /*evt*/) { - Gdk::Rectangle clip(e->area.x, e->area.y, e->area.width, e->area.height); - Glib::RefPtr<Gdk::Window> win = get_bin_window(); - Glib::RefPtr<Gdk::GC> darkgc = get_style()->get_dark_gc(Gtk::STATE_NORMAL); - Cairo::RefPtr<Cairo::Context> cr = get_bin_window()->create_cairo_context(); + bool result = false; + + if (get_is_drawable()) + { + Cairo::RefPtr<Cairo::Context> cr = get_bin_window()->create_cairo_context(); + result = on_draw_signal(cr); + } + + return result; +} +#endif + +bool FilterEffectsDialog::PrimitiveList::on_draw_signal(const Cairo::RefPtr<Cairo::Context> & cr) +{ + cr->set_line_width(1.0); +#if GTK_CHECK_VERSION(3,0,0) + // In GTK+ 3, the draw function receives the widget window, not the + // bin_window (i.e., just the area under the column headers). We + // therefore translate the origin of our coordinate system to account for this + int x_origin, y_origin; + convert_bin_window_to_widget_coords(0,0,x_origin,y_origin); + cr->translate(x_origin, y_origin); + + GtkStyleContext *sc = gtk_widget_get_style_context(GTK_WIDGET(gobj())); + GdkRGBA bg_color, fg_color; + gtk_style_context_get_background_color(sc, GTK_STATE_FLAG_NORMAL, &bg_color); + gtk_style_context_get_color(sc, GTK_STATE_FLAG_NORMAL, &fg_color); + + GdkRGBA mid_color = {(bg_color.red + fg_color.red)/2.0, + (bg_color.green + fg_color.green)/2.0, + (bg_color.blue + fg_color.blue)/2.0, + (bg_color.alpha + fg_color.alpha)/2.0}; + + GdkRGBA bg_color_active, fg_color_active; + gtk_style_context_get_background_color(sc, GTK_STATE_FLAG_ACTIVE, &bg_color_active); + gtk_style_context_get_color(sc, GTK_STATE_FLAG_ACTIVE, &fg_color_active); + + GdkRGBA mid_color_active = {(bg_color_active.red + fg_color_active.red)/2.0, + (bg_color_active.green + fg_color_active.green)/2.0, + (bg_color_active.blue + fg_color_active.blue)/2.0, + (bg_color_active.alpha + fg_color_active.alpha)/2.0}; +#else + GtkStyle *style = gtk_widget_get_style(GTK_WIDGET(gobj())); +#endif SPFilterPrimitive* prim = get_selected(); int row_count = get_model()->children().size(); @@ -1627,14 +2009,25 @@ bool FilterEffectsDialog::PrimitiveList::on_expose_signal(GdkEventExpose* e) const int x = text_start_x + get_input_type_width() * i; cr->save(); cr->rectangle(x, 0, get_input_type_width(), vis.get_height()); - Gdk::Cairo::set_source_color(cr, get_style()->get_bg(Gtk::STATE_NORMAL)); +#if GTK_CHECK_VERSION(3,0,0) + gdk_cairo_set_source_rgba(cr->cobj(), &bg_color); cr->fill_preserve(); - Gdk::Cairo::set_source_color(cr, get_style()->get_text(Gtk::STATE_NORMAL)); + + gdk_cairo_set_source_rgba(cr->cobj(), &fg_color); +#else + gdk_cairo_set_source_color(cr->cobj(), &(style->bg[GTK_STATE_NORMAL])); + cr->fill_preserve(); + gdk_cairo_set_source_color(cr->cobj(), &(style->text[GTK_STATE_NORMAL])); +#endif cr->move_to(x+get_input_type_width(), 0); cr->rotate_degrees(90); _vertical_layout->show_in_cairo_context(cr); - Gdk::Cairo::set_source_color(cr, get_style()->get_dark(Gtk::STATE_NORMAL)); - cr->set_line_width(1.0); + +#if GTK_CHECK_VERSION(3,0,0) + gdk_cairo_set_source_rgba(cr->cobj(), &mid_color); +#else + gdk_cairo_set_source_color(cr->cobj(), &(style->dark[GTK_STATE_NORMAL])); +#endif cr->move_to(x, 0); cr->line_to(x, vis.get_height()); cr->stroke(); @@ -1650,13 +2043,26 @@ bool FilterEffectsDialog::PrimitiveList::on_expose_signal(GdkEventExpose* e) // Check mouse state int mx, my; Gdk::ModifierType mask; + +#if GTK_CHECK_VERSION(3,0,0) + Glib::RefPtr<Gdk::Display> display = get_bin_window()->get_display(); + Glib::RefPtr<Gdk::DeviceManager> dm = display->get_device_manager(); + Glib::RefPtr<const Gdk::Device> device = dm->get_client_pointer(); + get_bin_window()->get_device_position(device, mx, my, mask); +#else get_bin_window()->get_pointer(mx, my, mask); +#endif // Outline the bottom of the connection area const int outline_x = x + fheight * (row_count - row_index); cr->save(); - Gdk::Cairo::set_source_color(cr, get_style()->get_dark(Gtk::STATE_NORMAL)); - cr->set_line_width(1.0); + +#if GTK_CHECK_VERSION(3,0,0) + gdk_cairo_set_source_rgba(cr->cobj(), &mid_color); +#else + gdk_cairo_set_source_color(cr->cobj(), &(style->dark[GTK_STATE_NORMAL])); +#endif + cr->move_to(x, y + h); cr->line_to(outline_x, y + h); // Side outline @@ -1667,6 +2073,7 @@ bool FilterEffectsDialog::PrimitiveList::on_expose_signal(GdkEventExpose* e) std::vector<Gdk::Point> con_poly; int con_drag_y = 0; + int con_drag_x = 0; bool inside; const SPFilterPrimitive* row_prim = (*row)[_columns.primitive]; const int inputs = input_count(row_prim); @@ -1674,50 +2081,108 @@ bool FilterEffectsDialog::PrimitiveList::on_expose_signal(GdkEventExpose* e) if(SP_IS_FEMERGE(row_prim)) { for(int i = 0; i < inputs; ++i) { inside = do_connection_node(row, i, con_poly, mx, my); - get_bin_window()->draw_polygon(inside && mask & GDK_BUTTON1_MASK ? - darkgc : get_style()->get_dark_gc(Gtk::STATE_ACTIVE), - inside, con_poly); + + cr->save(); + +#if GTK_CHECK_VERSION(3,0,0) + gdk_cairo_set_source_rgba(cr->cobj(), + inside && mask & GDK_BUTTON1_MASK ? + &mid_color : + &mid_color_active); +#else + gdk_cairo_set_source_color(cr->cobj(), + inside && mask & GDK_BUTTON1_MASK ? + &(style->dark[GTK_STATE_NORMAL]) : + &(style->dark[GTK_STATE_ACTIVE])); +#endif + + draw_connection_node(cr, con_poly, inside); + + cr->restore(); if(_in_drag == (i + 1)) + { con_drag_y = con_poly[2].get_y(); + con_drag_x = con_poly[2].get_x(); + } if(_in_drag != (i + 1) || row_prim != prim) - draw_connection(row, i, text_start_x, outline_x, con_poly[2].get_y(), row_count); + { + draw_connection(cr, row, i, text_start_x, outline_x, con_poly[2].get_y(), row_count); + } } } else { // Draw "in" shape inside = do_connection_node(row, 0, con_poly, mx, my); con_drag_y = con_poly[2].get_y(); - get_bin_window()->draw_polygon(inside && mask & GDK_BUTTON1_MASK ? - darkgc : get_style()->get_dark_gc(Gtk::STATE_ACTIVE), - inside, con_poly); + con_drag_x = con_poly[2].get_x(); + + cr->save(); + +#if GTK_CHECK_VERSION(3,0,0) + gdk_cairo_set_source_rgba(cr->cobj(), + inside && mask & GDK_BUTTON1_MASK ? + &mid_color : + &mid_color_active); +#else + gdk_cairo_set_source_color(cr->cobj(), + inside && mask & GDK_BUTTON1_MASK ? + &(style->dark[GTK_STATE_NORMAL]) : + &(style->dark[GTK_STATE_ACTIVE])); +#endif + + draw_connection_node(cr, con_poly, inside); + + cr->restore(); // Draw "in" connection if(_in_drag != 1 || row_prim != prim) - draw_connection(row, SP_ATTR_IN, text_start_x, outline_x, con_poly[2].get_y(), row_count); + { + draw_connection(cr, row, SP_ATTR_IN, text_start_x, outline_x, con_poly[2].get_y(), row_count); + } if(inputs == 2) { // Draw "in2" shape inside = do_connection_node(row, 1, con_poly, mx, my); if(_in_drag == 2) + { con_drag_y = con_poly[2].get_y(); - get_bin_window()->draw_polygon(inside && mask & GDK_BUTTON1_MASK ? - darkgc : get_style()->get_dark_gc(Gtk::STATE_ACTIVE), - inside, con_poly); + con_drag_x = con_poly[2].get_x(); + } + + cr->save(); + +#if GTK_CHECK_VERSION(3,0,0) + gdk_cairo_set_source_rgba(cr->cobj(), + inside && mask & GDK_BUTTON1_MASK ? + &mid_color : + &mid_color_active); +#else + gdk_cairo_set_source_color(cr->cobj(), + inside && mask & GDK_BUTTON1_MASK ? + &(style->dark[GTK_STATE_NORMAL]) : + &(style->dark[GTK_STATE_ACTIVE])); +#endif + + draw_connection_node(cr, con_poly, inside); + + cr->restore(); + // Draw "in2" connection if(_in_drag != 2 || row_prim != prim) - draw_connection(row, SP_ATTR_IN2, text_start_x, outline_x, con_poly[2].get_y(), row_count); + { + draw_connection(cr, row, SP_ATTR_IN2, text_start_x, outline_x, con_poly[2].get_y(), row_count); + } } } // Draw drag connection if(row_prim == prim && _in_drag) { cr->save(); - Gdk::Cairo::set_source_color(cr, get_style()->get_black()); - cr->set_line_width(1.0); - cr->move_to(outline_x, con_drag_y); - cr->line_to(mx, con_drag_y); + cr->set_source_rgb(0.0, 0.0, 0.0); + cr->move_to(con_drag_x, con_drag_y); + cr->line_to(mx, con_drag_y); cr->line_to(mx, my); cr->stroke(); cr->restore(); @@ -1727,19 +2192,35 @@ bool FilterEffectsDialog::PrimitiveList::on_expose_signal(GdkEventExpose* e) return true; } -void FilterEffectsDialog::PrimitiveList::draw_connection(const Gtk::TreeIter& input, const int attr, +void FilterEffectsDialog::PrimitiveList::draw_connection(const Cairo::RefPtr<Cairo::Context>& cr, + const Gtk::TreeIter& input, const int attr, const int text_start_x, const int x1, const int y1, const int row_count) { + cr->save(); + +#if GTK_CHECK_VERSION(3,0,0) + GtkStyleContext *sc = gtk_widget_get_style_context(GTK_WIDGET(gobj())); + + GdkRGBA bg_color, fg_color; + gtk_style_context_get_background_color(sc, GTK_STATE_FLAG_NORMAL, &bg_color); + gtk_style_context_get_color(sc, GTK_STATE_FLAG_NORMAL, &fg_color); + + GdkRGBA mid_color = {(bg_color.red + fg_color.red)/2.0, + (bg_color.green + fg_color.green)/2.0, + (bg_color.blue + fg_color.blue)/2.0, + (bg_color.alpha + fg_color.alpha)/2.0}; +#else + GtkStyle *style = gtk_widget_get_style(GTK_WIDGET(gobj())); +#endif + int src_id = 0; Gtk::TreeIter res = find_result(input, attr, src_id); - Cairo::RefPtr<Cairo::Context> cr = get_bin_window()->create_cairo_context(); const bool is_first = input == get_model()->children().begin(); const bool is_merge = SP_IS_FEMERGE((SPFilterPrimitive*)(*input)[_columns.primitive]); const bool use_default = !res && !is_merge; - cr->set_line_width(1); if(res == input || (use_default && is_first)) { // Draw straight connection to a standard input // Draw a lighter line for an implicit connection to a standard input @@ -1747,9 +2228,13 @@ void FilterEffectsDialog::PrimitiveList::draw_connection(const Gtk::TreeIter& in gint end_x = text_start_x + tw * src_id + (int)(tw * 0.5f) + 1; if(use_default && is_first) - Gdk::Cairo::set_source_color(cr, get_style()->get_dark(Gtk::STATE_NORMAL)); +#if GTK_CHECK_VERSION(3,0,0) + gdk_cairo_set_source_rgba(cr->cobj(), &mid_color); +#else + gdk_cairo_set_source_color(cr->cobj(), &(style->dark[GTK_STATE_NORMAL])); +#endif else - Gdk::Cairo::set_source_color(cr, get_style()->get_black()); + cr->set_source_rgb(0.0, 0.0, 0.0); cr->rectangle(end_x-2, y1-2, 5, 5); cr->fill_preserve(); @@ -1777,7 +2262,7 @@ void FilterEffectsDialog::PrimitiveList::draw_connection(const Gtk::TreeIter& in const int y2 = rct.get_y() + rct.get_height(); // Draw a bevelled 'L'-shaped connection - Gdk::Cairo::set_source_color(cr, get_style()->get_black()); + cr->set_source_rgb(0.0, 0.0, 0.0); cr->move_to(x1, y1); cr->line_to(x2-fheight/4, y1); cr->line_to(x2, y1-fheight/4); @@ -1785,6 +2270,25 @@ void FilterEffectsDialog::PrimitiveList::draw_connection(const Gtk::TreeIter& in cr->stroke(); } } + cr->restore(); +} + +// Draw the triangular outline of the connection node, and fill it +// if desired +void FilterEffectsDialog::PrimitiveList::draw_connection_node(const Cairo::RefPtr<Cairo::Context>& cr, + const std::vector<Gdk::Point>& points, + const bool fill) +{ + cr->save(); + cr->move_to(points[0].get_x()+0.5, points[0].get_y()+0.5); + cr->line_to(points[1].get_x()+0.5, points[1].get_y()+0.5); + cr->line_to(points[2].get_x()+0.5, points[2].get_y()+0.5); + cr->line_to(points[0].get_x()+0.5, points[0].get_y()+0.5); + + if(fill) cr->fill(); + else cr->stroke(); + + cr->restore(); } // Creates a triangle outline of the connection node and returns true if (x,y) is inside the node @@ -1900,7 +2404,8 @@ bool FilterEffectsDialog::PrimitiveList::on_button_press_event(GdkEventButton* e if(_in_drag) { _scroll_connection = Glib::signal_timeout().connect(sigc::mem_fun(*this, &PrimitiveList::on_scroll_timeout), 150); - _autoscroll = 0; + _autoscroll_x = 0; + _autoscroll_y = 0; get_selection()->select(path); return true; } @@ -1916,22 +2421,43 @@ bool FilterEffectsDialog::PrimitiveList::on_motion_notify_event(GdkEventMotion* Gdk::Rectangle vis; get_visible_rect(vis); int vis_x, vis_y; + + int vis_x2, vis_y2; // NOTE: insaner added -- necessary to get the scrolling while dragging to work + convert_widget_to_tree_coords(vis.get_x(), vis.get_y(), vis_x2, vis_y2); + convert_tree_to_widget_coords(vis.get_x(), vis.get_y(), vis_x, vis_y); const int top = vis_y + vis.get_height(); + const int right_edge = vis_x + vis.get_width(); // When autoscrolling during a connection drag, set the speed based on // where the mouse is in relation to the edges. if(e->y < vis_y) - _autoscroll = -(int)(speed + (vis_y - e->y) / 5); + _autoscroll_y = -(int)(speed + (vis_y - e->y) / 5); else if(e->y < vis_y + limit) - _autoscroll = -speed; + _autoscroll_y = -speed; else if(e->y > top) - _autoscroll = (int)(speed + (e->y - top) / 5); + _autoscroll_y = (int)(speed + (e->y - top) / 5); else if(e->y > top - limit) - _autoscroll = speed; + _autoscroll_y = speed; else - _autoscroll = 0; - + _autoscroll_y = 0; + + // NOTE: insaner added -- necessary to get the scrolling while dragging to work + double e2 = ( e->x - vis_x2/2); + // horizontal scrolling + if(e2 < vis_x) + _autoscroll_x = -(int)(speed + (vis_x - e2) / 5); + else if(e2 < vis_x + limit) + _autoscroll_x = -speed; + else if(e2 > right_edge) + _autoscroll_x = (int)(speed + (e2 - right_edge) / 5); + else if(e2 > right_edge - limit) + _autoscroll_x = speed; + else + _autoscroll_x = 0; + + + queue_draw(); return Gtk::TreeView::on_motion_notify_event(e); @@ -2038,8 +2564,9 @@ bool FilterEffectsDialog::PrimitiveList::on_button_release_event(GdkEventButton* if((e->type == GDK_BUTTON_RELEASE) && (e->button == 3)) { const bool sensitive = get_selected() != NULL; - _primitive_menu->items()[0].set_sensitive(sensitive); - _primitive_menu->items()[1].set_sensitive(sensitive); + std::vector<Gtk::Widget*> items = _primitive_menu->get_children(); + items[0]->set_sensitive(sensitive); + items[1]->set_sensitive(sensitive); _primitive_menu->popup(e->button, e->time); return true; @@ -2049,7 +2576,7 @@ bool FilterEffectsDialog::PrimitiveList::on_button_release_event(GdkEventButton* } // Checks all of prim's inputs, removes any that use result -void check_single_connection(SPFilterPrimitive* prim, const int result) +static void check_single_connection(SPFilterPrimitive* prim, const int result) { if (prim && (result >= 0)) { if (prim->image_in == result) { @@ -2125,10 +2652,10 @@ void FilterEffectsDialog::PrimitiveList::on_drag_end(const Glib::RefPtr<Gdk::Dra // If a connection is dragged towards the top or bottom of the list, the list should scroll to follow. bool FilterEffectsDialog::PrimitiveList::on_scroll_timeout() { - if(_autoscroll) { + if(_autoscroll_y) { #if WITH_GTKMM_3_0 Glib::RefPtr<Gtk::Adjustment> a = dynamic_cast<Gtk::ScrolledWindow*>(get_parent())->get_vadjustment(); - double v = a->get_value() + _autoscroll; + double v = a->get_value() + _autoscroll_y; if(v < 0) v = 0; @@ -2138,7 +2665,7 @@ bool FilterEffectsDialog::PrimitiveList::on_scroll_timeout() a->set_value(v); #else Gtk::Adjustment& a = *dynamic_cast<Gtk::ScrolledWindow*>(get_parent())->get_vadjustment(); - double v = a.get_value() + _autoscroll; + double v = a.get_value() + _autoscroll_y; if(v < 0) v = 0; @@ -2151,6 +2678,34 @@ bool FilterEffectsDialog::PrimitiveList::on_scroll_timeout() queue_draw(); } + + if(_autoscroll_x) { +#if WITH_GTKMM_3_0 + Glib::RefPtr<Gtk::Adjustment> a_h = dynamic_cast<Gtk::ScrolledWindow*>(get_parent())->get_hadjustment(); + double h = a_h->get_value() + _autoscroll_x; + + if(h < 0) + h = 0; + if(h > a_h->get_upper() - a_h->get_page_size()) + h = a_h->get_upper() - a_h->get_page_size(); + + a_h->set_value(h); +#else + Gtk::Adjustment& a_h = *dynamic_cast<Gtk::ScrolledWindow*>(get_parent())->get_hadjustment(); + double h = a_h.get_value() + _autoscroll_x; + + if(h < 0) + h = 0; + if(h > a_h.get_upper() - a_h.get_page_size()) + h = a_h.get_upper() - a_h.get_page_size(); + + a_h.set_value(h); + +#endif + + queue_draw(); + } + return true; } @@ -2172,13 +2727,8 @@ FilterEffectsDialog::FilterEffectsDialog() : UI::Widget::Panel("", "/dialogs/filtereffects", SP_VERB_DIALOG_FILTER_EFFECTS), _add_primitive_type(FPConverter), _add_primitive(_("Add Effect:")), -#if WITH_GTKMM_2_22 - _empty_settings(_("No effect selected"), Gtk::ALIGN_START), - _no_filter_selected(_("No filter selected"), Gtk::ALIGN_START), -#else - _empty_settings(_("No effect selected"), Gtk::ALIGN_LEFT), - _no_filter_selected(_("No filter selected"), Gtk::ALIGN_LEFT), -#endif + _empty_settings(_("No effect selected"), Gtk::ALIGN_START), + _no_filter_selected(_("No filter selected"), Gtk::ALIGN_START), _settings_initialized(false), _locked(false), _attr_lock(false), @@ -2193,11 +2743,16 @@ FilterEffectsDialog::FilterEffectsDialog() _sizegroup->set_ignore_hidden(); _add_primitive_type.remove_row(NR_FILTER_TILE); - _add_primitive_type.remove_row(NR_FILTER_COMPONENTTRANSFER); // Initialize widget hierarchy +#if WITH_GTKMM_3_0 + Gtk::Paned* hpaned = Gtk::manage(new Gtk::Paned); +#else Gtk::HPaned* hpaned = Gtk::manage(new Gtk::HPaned); +#endif + Gtk::ScrolledWindow* sw_prims = Gtk::manage(new Gtk::ScrolledWindow); + Gtk::ScrolledWindow* sw_infobox = Gtk::manage(new Gtk::ScrolledWindow); Gtk::HBox* infobox = Gtk::manage(new Gtk::HBox(/*homogeneous:*/false, /*spacing:*/4)); Gtk::HBox* hb_prims = Gtk::manage(new Gtk::HBox); @@ -2206,13 +2761,15 @@ FilterEffectsDialog::FilterEffectsDialog() hpaned->pack2(_primitive_box); _primitive_box.pack_start(*sw_prims); _primitive_box.pack_start(*hb_prims, false, false); - _primitive_box.pack_start(*infobox,false, false); + _primitive_box.pack_start(*sw_infobox, false, false); sw_prims->add(_primitive_list); + sw_infobox->add(*infobox); infobox->pack_start(_infobox_icon, false, false); infobox->pack_start(_infobox_desc, false, false); _infobox_desc.set_line_wrap(true); _infobox_desc.set_size_request(200, -1); + hb_prims->pack_start(_add_primitive, false, false); hb_prims->pack_start(_add_primitive_type, false, false); _getContents()->pack_start(_settings_tabs, false, false); @@ -2227,8 +2784,10 @@ FilterEffectsDialog::FilterEffectsDialog() _add_primitive_type.signal_changed().connect( sigc::mem_fun(*this, &FilterEffectsDialog::update_primitive_infobox)); - sw_prims->set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); + sw_prims->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); /* NOTE: insaner -- SCROLL the connections panel thing!!! */ sw_prims->set_shadow_type(Gtk::SHADOW_IN); + sw_infobox->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_NEVER); + // al_settings->set_padding(0, 0, 12, 0); // fr_settings->set_shadow_type(Gtk::SHADOW_NONE); // ((Gtk::Label*)fr_settings->get_label_widget())->set_use_markup(); @@ -2262,7 +2821,7 @@ void FilterEffectsDialog::show_all_vfunc() void FilterEffectsDialog::init_settings_widgets() { - // TODO: Find better range/climb-rate/digits values for the SpinSliders, + // TODO: Find better range/climb-rate/digits values for the SpinScales, // most of the current values are complete guesses! _empty_settings.set_sensitive(false); @@ -2285,22 +2844,17 @@ void FilterEffectsDialog::init_settings_widgets() colmat->signal_attr_changed().connect(sigc::mem_fun(*this, &FilterEffectsDialog::update_color_matrix)); _settings->type(NR_FILTER_COMPONENTTRANSFER); - _settings->add_notimplemented(); - /* - //TRANSLATORS: for info on "Slope" and "Intercept", see http://id.mind.net/~zona/mmts/functionInstitute/linearFunctions/lsif.html - _settings->add_combo(COMPONENTTRANSFER_TYPE_IDENTITY, SP_ATTR_TYPE, _("Type"), ComponentTransferTypeConverter); - _ct_slope = _settings->add_spinslider(1, SP_ATTR_SLOPE, _("Slope"), -10, 10, 0.1, 0.01, 2); - _ct_intercept = _settings->add_spinslider(0, SP_ATTR_INTERCEPT, _("Intercept"), -10, 10, 0.1, 0.01, 2); - _ct_amplitude = _settings->add_spinslider(1, SP_ATTR_AMPLITUDE, _("Amplitude"), 0, 10, 0.1, 0.01, 2); - _ct_exponent = _settings->add_spinslider(1, SP_ATTR_EXPONENT, _("Exponent"), 0, 10, 0.1, 0.01, 2); - _ct_offset = _settings->add_spinslider(0, SP_ATTR_OFFSET, _("Offset"), -10, 10, 0.1, 0.01, 2);*/ + _settings->add_componenttransfervalues(_("R:"), SPFeFuncNode::R); + _settings->add_componenttransfervalues(_("G:"), SPFeFuncNode::G); + _settings->add_componenttransfervalues(_("B:"), SPFeFuncNode::B); + _settings->add_componenttransfervalues(_("A:"), SPFeFuncNode::A); _settings->type(NR_FILTER_COMPOSITE); _settings->add_combo(COMPOSITE_OVER, SP_ATTR_OPERATOR, _("Operator:"), CompositeOperatorConverter); - _k1 = _settings->add_spinslider(0, SP_ATTR_K1, _("K1:"), -10, 10, 0.1, 0.01, 2, _("If the arithmetic operation is chosen, each result pixel is computed using the formula k1*i1*i2 + k2*i1 + k3*i2 + k4 where i1 and i2 are the pixel values of the first and second inputs respectively.")); - _k2 = _settings->add_spinslider(0, SP_ATTR_K2, _("K2:"), -10, 10, 0.1, 0.01, 2, _("If the arithmetic operation is chosen, each result pixel is computed using the formula k1*i1*i2 + k2*i1 + k3*i2 + k4 where i1 and i2 are the pixel values of the first and second inputs respectively.")); - _k3 = _settings->add_spinslider(0, SP_ATTR_K3, _("K3:"), -10, 10, 0.1, 0.01, 2, _("If the arithmetic operation is chosen, each result pixel is computed using the formula k1*i1*i2 + k2*i1 + k3*i2 + k4 where i1 and i2 are the pixel values of the first and second inputs respectively.")); - _k4 = _settings->add_spinslider(0, SP_ATTR_K4, _("K4:"), -10, 10, 0.1, 0.01, 2, _("If the arithmetic operation is chosen, each result pixel is computed using the formula k1*i1*i2 + k2*i1 + k3*i2 + k4 where i1 and i2 are the pixel values of the first and second inputs respectively.")); + _k1 = _settings->add_spinscale(0, SP_ATTR_K1, _("K1:"), -10, 10, 0.1, 0.01, 2, _("If the arithmetic operation is chosen, each result pixel is computed using the formula k1*i1*i2 + k2*i1 + k3*i2 + k4 where i1 and i2 are the pixel values of the first and second inputs respectively.")); + _k2 = _settings->add_spinscale(0, SP_ATTR_K2, _("K2:"), -10, 10, 0.1, 0.01, 2, _("If the arithmetic operation is chosen, each result pixel is computed using the formula k1*i1*i2 + k2*i1 + k3*i2 + k4 where i1 and i2 are the pixel values of the first and second inputs respectively.")); + _k3 = _settings->add_spinscale(0, SP_ATTR_K3, _("K3:"), -10, 10, 0.1, 0.01, 2, _("If the arithmetic operation is chosen, each result pixel is computed using the formula k1*i1*i2 + k2*i1 + k3*i2 + k4 where i1 and i2 are the pixel values of the first and second inputs respectively.")); + _k4 = _settings->add_spinscale(0, SP_ATTR_K4, _("K4:"), -10, 10, 0.1, 0.01, 2, _("If the arithmetic operation is chosen, each result pixel is computed using the formula k1*i1*i2 + k2*i1 + k3*i2 + k4 where i1 and i2 are the pixel values of the first and second inputs respectively.")); _settings->type(NR_FILTER_CONVOLVEMATRIX); _convolve_order = _settings->add_dualspinbutton((char*)"3", SP_ATTR_ORDER, _("Size:"), 1, 5, 1, 1, 0, _("width of the convolve matrix"), _("height of the convolve matrix")); @@ -2308,50 +2862,50 @@ void FilterEffectsDialog::init_settings_widgets() //TRANSLATORS: for info on "Kernel", see http://en.wikipedia.org/wiki/Kernel_(matrix) _convolve_matrix = _settings->add_matrix(SP_ATTR_KERNELMATRIX, _("Kernel:"), _("This matrix describes the convolve operation that is applied to the input image in order to calculate the pixel colors at the output. Different arrangements of values in this matrix result in various possible visual effects. An identity matrix would lead to a motion blur effect (parallel to the matrix diagonal) while a matrix filled with a constant non-zero value would lead to a common blur effect.")); _convolve_order->signal_attr_changed().connect(sigc::mem_fun(*this, &FilterEffectsDialog::convolve_order_changed)); - _settings->add_spinslider(0, SP_ATTR_DIVISOR, _("Divisor:"), 0, 1000, 1, 0.1, 2, _("After applying the kernelMatrix to the input image to yield a number, that number is divided by divisor to yield the final destination color value. A divisor that is the sum of all the matrix values tends to have an evening effect on the overall color intensity of the result.")); - _settings->add_spinslider(0, SP_ATTR_BIAS, _("Bias:"), -10, 10, 1, 0.01, 1, _("This value is added to each component. This is useful to define a constant value as the zero response of the filter.")); + _settings->add_spinscale(0, SP_ATTR_DIVISOR, _("Divisor:"), 0, 1000, 1, 0.1, 2, _("After applying the kernelMatrix to the input image to yield a number, that number is divided by divisor to yield the final destination color value. A divisor that is the sum of all the matrix values tends to have an evening effect on the overall color intensity of the result.")); + _settings->add_spinscale(0, SP_ATTR_BIAS, _("Bias:"), -10, 10, 1, 0.01, 1, _("This value is added to each component. This is useful to define a constant value as the zero response of the filter.")); _settings->add_combo(CONVOLVEMATRIX_EDGEMODE_DUPLICATE, SP_ATTR_EDGEMODE, _("Edge Mode:"), ConvolveMatrixEdgeModeConverter, _("Determines how to extend the input image as necessary with color values so that the matrix operations can be applied when the kernel is positioned at or near the edge of the input image.")); _settings->add_checkbutton(false, SP_ATTR_PRESERVEALPHA, _("Preserve Alpha"), "true", "false", _("If set, the alpha channel won't be altered by this filter primitive.")); _settings->type(NR_FILTER_DIFFUSELIGHTING); _settings->add_color(/*default: white*/ 0xffffffff, SP_PROP_LIGHTING_COLOR, _("Diffuse Color:"), _("Defines the color of the light source")); - _settings->add_spinslider(1, SP_ATTR_SURFACESCALE, _("Surface Scale:"), -5, 5, 0.01, 0.001, 3, _("This value amplifies the heights of the bump map defined by the input alpha channel")); - _settings->add_spinslider(1, SP_ATTR_DIFFUSECONSTANT, _("Constant:"), 0, 5, 0.1, 0.01, 2, _("This constant affects the Phong lighting model.")); - _settings->add_dualspinslider(SP_ATTR_KERNELUNITLENGTH, _("Kernel Unit Length:"), 0.01, 10, 1, 0.01, 1); + _settings->add_spinscale(1, SP_ATTR_SURFACESCALE, _("Surface Scale:"), -5, 5, 0.01, 0.001, 3, _("This value amplifies the heights of the bump map defined by the input alpha channel")); + _settings->add_spinscale(1, SP_ATTR_DIFFUSECONSTANT, _("Constant:"), 0, 5, 0.1, 0.01, 2, _("This constant affects the Phong lighting model.")); + _settings->add_dualspinscale(SP_ATTR_KERNELUNITLENGTH, _("Kernel Unit Length:"), 0.01, 10, 1, 0.01, 1); _settings->add_lightsource(); _settings->type(NR_FILTER_DISPLACEMENTMAP); - _settings->add_spinslider(0, SP_ATTR_SCALE, _("Scale:"), 0, 100, 1, 0.01, 1, _("This defines the intensity of the displacement effect.")); + _settings->add_spinscale(0, SP_ATTR_SCALE, _("Scale:"), 0, 100, 1, 0.01, 1, _("This defines the intensity of the displacement effect.")); _settings->add_combo(DISPLACEMENTMAP_CHANNEL_ALPHA, SP_ATTR_XCHANNELSELECTOR, _("X displacement:"), DisplacementMapChannelConverter, _("Color component that controls the displacement in the X direction")); _settings->add_combo(DISPLACEMENTMAP_CHANNEL_ALPHA, SP_ATTR_YCHANNELSELECTOR, _("Y displacement:"), DisplacementMapChannelConverter, _("Color component that controls the displacement in the Y direction")); _settings->type(NR_FILTER_FLOOD); _settings->add_color(/*default: black*/ 0, SP_PROP_FLOOD_COLOR, _("Flood Color:"), _("The whole filter region will be filled with this color.")); - _settings->add_spinslider(1, SP_PROP_FLOOD_OPACITY, _("Opacity:"), 0, 1, 0.1, 0.01, 2); + _settings->add_spinscale(1, SP_PROP_FLOOD_OPACITY, _("Opacity:"), 0, 1, 0.1, 0.01, 2); _settings->type(NR_FILTER_GAUSSIANBLUR); - _settings->add_dualspinslider(SP_ATTR_STDDEVIATION, _("Standard Deviation:"), 0.01, 100, 1, 0.01, 1, _("The standard deviation for the blur operation.")); + _settings->add_dualspinscale(SP_ATTR_STDDEVIATION, _("Standard Deviation:"), 0.01, 100, 1, 0.01, 1, _("The standard deviation for the blur operation.")); _settings->type(NR_FILTER_MERGE); _settings->add_no_params(); _settings->type(NR_FILTER_MORPHOLOGY); _settings->add_combo(MORPHOLOGY_OPERATOR_ERODE, SP_ATTR_OPERATOR, _("Operator:"), MorphologyOperatorConverter, _("Erode: performs \"thinning\" of input image.\nDilate: performs \"fattenning\" of input image.")); - _settings->add_dualspinslider(SP_ATTR_RADIUS, _("Radius:"), 0, 100, 1, 0.01, 1); + _settings->add_dualspinscale(SP_ATTR_RADIUS, _("Radius:"), 0, 100, 1, 0.01, 1); _settings->type(NR_FILTER_IMAGE); _settings->add_fileorelement(SP_ATTR_XLINK_HREF, _("Source of Image:")); _settings->type(NR_FILTER_OFFSET); - _settings->add_spinslider(0, SP_ATTR_DX, _("Delta X:"), -100, 100, 1, 0.01, 1, _("This is how far the input image gets shifted to the right")); - _settings->add_spinslider(0, SP_ATTR_DY, _("Delta Y:"), -100, 100, 1, 0.01, 1, _("This is how far the input image gets shifted downwards")); + _settings->add_spinscale(0, SP_ATTR_DX, _("Delta X:"), -100, 100, 1, 0.01, 1, _("This is how far the input image gets shifted to the right")); + _settings->add_spinscale(0, SP_ATTR_DY, _("Delta Y:"), -100, 100, 1, 0.01, 1, _("This is how far the input image gets shifted downwards")); _settings->type(NR_FILTER_SPECULARLIGHTING); _settings->add_color(/*default: white*/ 0xffffffff, SP_PROP_LIGHTING_COLOR, _("Specular Color:"), _("Defines the color of the light source")); - _settings->add_spinslider(1, SP_ATTR_SURFACESCALE, _("Surface Scale:"), -5, 5, 0.1, 0.01, 2, _("This value amplifies the heights of the bump map defined by the input alpha channel")); - _settings->add_spinslider(1, SP_ATTR_SPECULARCONSTANT, _("Constant:"), 0, 5, 0.1, 0.01, 2, _("This constant affects the Phong lighting model.")); - _settings->add_spinslider(1, SP_ATTR_SPECULAREXPONENT, _("Exponent:"), 1, 50, 1, 0.01, 1, _("Exponent for specular term, larger is more \"shiny\".")); - _settings->add_dualspinslider(SP_ATTR_KERNELUNITLENGTH, _("Kernel Unit Length:"), 0.01, 10, 1, 0.01, 1); + _settings->add_spinscale(1, SP_ATTR_SURFACESCALE, _("Surface Scale:"), -5, 5, 0.1, 0.01, 2, _("This value amplifies the heights of the bump map defined by the input alpha channel")); + _settings->add_spinscale(1, SP_ATTR_SPECULARCONSTANT, _("Constant:"), 0, 5, 0.1, 0.01, 2, _("This constant affects the Phong lighting model.")); + _settings->add_spinscale(1, SP_ATTR_SPECULAREXPONENT, _("Exponent:"), 1, 50, 1, 0.01, 1, _("Exponent for specular term, larger is more \"shiny\".")); + _settings->add_dualspinscale(SP_ATTR_KERNELUNITLENGTH, _("Kernel Unit Length:"), 0.01, 10, 1, 0.01, 1); _settings->add_lightsource(); _settings->type(NR_FILTER_TILE); @@ -2360,9 +2914,9 @@ void FilterEffectsDialog::init_settings_widgets() _settings->type(NR_FILTER_TURBULENCE); // _settings->add_checkbutton(false, SP_ATTR_STITCHTILES, _("Stitch Tiles"), "stitch", "noStitch"); _settings->add_combo(TURBULENCE_TURBULENCE, SP_ATTR_TYPE, _("Type:"), TurbulenceTypeConverter, _("Indicates whether the filter primitive should perform a noise or turbulence function.")); - _settings->add_dualspinslider(SP_ATTR_BASEFREQUENCY, _("Base Frequency:"), 0, 1, 0.001, 0.01, 3); - _settings->add_spinslider(1, SP_ATTR_NUMOCTAVES, _("Octaves:"), 1, 10, 1, 1, 0); - _settings->add_spinslider(0, SP_ATTR_SEED, _("Seed:"), 0, 1000, 1, 1, 0, _("The starting number for the pseudo random number generator.")); + _settings->add_dualspinscale(SP_ATTR_BASEFREQUENCY, _("Base Frequency:"), 0, 1, 0.001, 0.01, 3); + _settings->add_spinscale(1, SP_ATTR_NUMOCTAVES, _("Octaves:"), 1, 10, 1, 1, 0); + _settings->add_spinscale(0, SP_ATTR_SEED, _("Seed:"), 0, 1000, 1, 1, 0, _("The starting number for the pseudo random number generator.")); } void FilterEffectsDialog::add_primitive() @@ -2443,7 +2997,7 @@ void FilterEffectsDialog::update_primitive_infobox() break; case(NR_FILTER_SPECULARLIGHTING): _infobox_icon.set_from_icon_name("feSpecularLighting-icon", Gtk::ICON_SIZE_DIALOG); - _infobox_desc.set_markup(_("The feDiffuseLighting and <b>feSpecularLighting</b> filter primitives create \"embossed\" shadings. The input's alpha channel is used to provide depth information: higher opacity areas are raised toward the viewer and lower opacity areas recede away from the viewer.")); + _infobox_desc.set_markup(_("The <b>feDiffuseLighting</b> and <b>feSpecularLighting</b> filter primitives create \"embossed\" shadings. The input's alpha channel is used to provide depth information: higher opacity areas are raised toward the viewer and lower opacity areas recede away from the viewer.")); break; case(NR_FILTER_TILE): _infobox_icon.set_from_icon_name("feTile-icon", Gtk::ICON_SIZE_DIALOG); @@ -2545,11 +3099,7 @@ void FilterEffectsDialog::update_filter_general_settings_view() } else { std::vector<Gtk::Widget*> vect = _settings_tab2.get_children(); -#if WITH_GTKMM_2_24 vect[0]->hide(); -#else - vect[0]->hide_all(); -#endif _no_filter_selected.show(); } @@ -2568,11 +3118,7 @@ void FilterEffectsDialog::update_settings_view() std::vector<Gtk::Widget*> vect1 = _settings_tab1.get_children(); for(unsigned int i=0; i<vect1.size(); i++) -#if WITH_GTKMM_2_24 vect1[i]->hide(); -#else - vect1[i]->hide_all(); -#endif _empty_settings.show(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -2596,11 +3142,7 @@ void FilterEffectsDialog::update_settings_view() //Second Tab std::vector<Gtk::Widget*> vect2 = _settings_tab2.get_children(); -#if WITH_GTKMM_2_24 vect2[0]->hide(); -#else - vect2[0]->hide_all(); -#endif _no_filter_selected.show(); SPFilter* filter = _filter_modifier.get_selected_filter(); @@ -2621,21 +3163,6 @@ void FilterEffectsDialog::update_settings_sensitivity() _k3->set_sensitive(use_k); _k4->set_sensitive(use_k); -// Component transfer not yet implemented -/* - if(SP_IS_FECOMPONENTTRANSFER(prim)) { - SPFeComponentTransfer* ct = SP_FECOMPONENTTRANSFER(prim); - const bool linear = ct->type == COMPONENTTRANSFER_TYPE_LINEAR; - const bool gamma = ct->type == COMPONENTTRANSFER_TYPE_GAMMA; - - _ct_table->set_sensitive(ct->type == COMPONENTTRANSFER_TYPE_TABLE || ct->type == COMPONENTTRANSFER_TYPE_DISCRETE); - _ct_slope->set_sensitive(linear); - _ct_intercept->set_sensitive(linear); - _ct_amplitude->set_sensitive(gamma); - _ct_exponent->set_sensitive(gamma); - _ct_offset->set_sensitive(gamma); - } -*/ } void FilterEffectsDialog::update_color_matrix() diff --git a/src/ui/dialog/filter-effects-dialog.h b/src/ui/dialog/filter-effects-dialog.h index 73bab25a7..3fc19e7de 100644 --- a/src/ui/dialog/filter-effects-dialog.h +++ b/src/ui/dialog/filter-effects-dialog.h @@ -20,7 +20,9 @@ #include "sp-filter.h" #include "ui/widget/combo-enums.h" #include "ui/widget/spin-slider.h" +#include "ui/widget/spin-scale.h" #include "xml/helper-observer.h" +#include "ui/dialog/desktop-tracker.h" #include <gtkmm/notebook.h> #include <gtkmm/sizegroup.h> @@ -74,19 +76,17 @@ private: Gtk::TreeModelColumn<int> sel; }; - static void on_activate_desktop(Application*, SPDesktop*, FilterModifier*); - static void on_deactivate_desktop(Application*, SPDesktop*, FilterModifier*); - void on_document_replaced(SPDesktop*, SPDocument*) - { - update_filters(); - } + void setTargetDesktop(SPDesktop *desktop); - static void on_inkscape_change_selection(Application *, Selection *, FilterModifier*); + void on_document_replaced(SPDesktop *desktop, SPDocument *document); + void on_change_selection(); + void on_modified_selection( guint flags ); void update_selection(Selection *); void on_filter_selection_changed(); void on_name_edited(const Glib::ustring&, const Glib::ustring&); + bool on_filter_move(const Glib::RefPtr<Gdk::DragContext>& /*context*/, int x, int y, guint /*time*/); void on_selection_toggled(const Glib::ustring&); void update_filters(); @@ -96,6 +96,22 @@ private: void duplicate_filter(); void rename_filter(); + /** + * Stores the current desktop. + */ + SPDesktop *_desktop; + + /** + * Auxiliary widget to keep track of desktop changes for the floating dialog. + */ + DesktopTracker _deskTrack; + + /** + * Link to callback function for a change in desktop (window). + */ + sigc::connection desktopChangeConn; + sigc::connection _selectChangedConn; + sigc::connection _selectModifiedConn; sigc::connection _doc_replaced; sigc::connection _resource_changed; @@ -136,8 +152,28 @@ private: static const int size = 24; protected: +#if WITH_GTKMM_3_0 + virtual void get_preferred_width_vfunc(Gtk::Widget& widget, + int& minimum_width, + int& natural_width) const; + + virtual void get_preferred_width_for_height_vfunc(Gtk::Widget& widget, + int height, + int& minimum_width, + int& natural_width) const; + + virtual void get_preferred_height_vfunc(Gtk::Widget& widget, + int& minimum_height, + int& natural_height) const; + + virtual void get_preferred_height_for_width_vfunc(Gtk::Widget& widget, + int width, + int& minimum_height, + int& natural_height) const; +#else virtual void get_size_vfunc(Gtk::Widget& widget, const Gdk::Rectangle* cell_area, int* x_offset, int* y_offset, int* width, int* height) const; +#endif private: // void* should be SPFilterPrimitive*, some weirdness with properties prevents this Glib::Property<void*> _primitive; @@ -162,7 +198,12 @@ private: int get_input_type_width() const; protected: + bool on_draw_signal(const Cairo::RefPtr<Cairo::Context> &cr); + +#if !WITH_GTKMM_3_0 bool on_expose_signal(GdkEventExpose*); +#endif + bool on_button_press_event(GdkEventButton*); bool on_motion_notify_event(GdkEventMotion*); bool on_button_release_event(GdkEventButton*); @@ -170,11 +211,17 @@ private: private: void init_text(); - bool do_connection_node(const Gtk::TreeIter& row, const int input, std::vector<Gdk::Point>& points, + void draw_connection_node(const Cairo::RefPtr<Cairo::Context>& cr, + const std::vector<Gdk::Point>& points, + const bool fill); + + bool do_connection_node(const Gtk::TreeIter& row, const int input, std::vector<Gdk::Point>& points, const int ix, const int iy); + const Gtk::TreeIter find_result(const Gtk::TreeIter& start, const int attr, int& src_id); int find_index(const Gtk::TreeIter& target); - void draw_connection(const Gtk::TreeIter&, const int attr, const int text_start_x, + void draw_connection(const Cairo::RefPtr<Cairo::Context>& cr, + const Gtk::TreeIter&, const int attr, const int text_start_x, const int x1, const int y1, const int row_count); void sanitize_connections(const Gtk::TreeIter& prim_iter); void on_primitive_selection_changed(); @@ -190,7 +237,8 @@ private: SPFilterPrimitive* _drag_prim; sigc::signal<void> _signal_primitive_changed; sigc::connection _scroll_connection; - int _autoscroll; + int _autoscroll_y; + int _autoscroll_x; std::auto_ptr<Inkscape::XML::SignalObserver> _observer; int _input_type_width; int _input_type_height; @@ -234,6 +282,7 @@ private: class Settings; class MatrixAttr; class ColorMatrixValues; + class ComponentTransferValues; class LightSourceControl; Settings* _settings; Settings* _filter_general_settings; @@ -242,6 +291,9 @@ private: // Color Matrix ColorMatrixValues* _color_matrix_values; + // Component Transfer + ComponentTransferValues* _component_transfer_values; + // Convolve Matrix MatrixAttr* _convolve_matrix; DualSpinButton* _convolve_order; @@ -249,7 +301,6 @@ private: // For controlling setting sensitivity Gtk::Widget* _k1, *_k2, *_k3, *_k4; - Gtk::Widget* _ct_table, *_ct_slope, *_ct_intercept, *_ct_amplitude, *_ct_exponent, *_ct_offset; // To prevent unwanted signals bool _locked; diff --git a/src/ui/dialog/find.cpp b/src/ui/dialog/find.cpp index 03a440d5c..37f2761df 100644 --- a/src/ui/dialog/find.cpp +++ b/src/ui/dialog/find.cpp @@ -15,7 +15,10 @@ #endif #include "find.h" + +#include <gtkmm/entry.h> #include <gtkmm/widget.h> + #include "verbs.h" #include "message-stack.h" @@ -56,6 +59,7 @@ #include "xml/attribute-record.h" #include <glibmm/i18n.h> +#include <glibmm/regex.h> namespace Inkscape { namespace UI { @@ -65,12 +69,12 @@ Find::Find() : UI::Widget::Panel("", "/dialogs/find", SP_VERB_DIALOG_FIND), entry_find(_("F_ind:"), _("Find objects by their content or properties (exact or partial match)")), - entry_replace(_("Re_place:"), _("Replace match with this value")), + entry_replace(_("R_eplace:"), _("Replace match with this value")), check_scope_all(_("_All"), _("Search in all layers")), check_scope_layer(_("Current _layer"), _("Limit search to the current layer")), - check_scope_selection(_("S_election"), _("Limit search to the current selection")), - check_searchin_text(_("Te_xt"), _("Search in text objects")), + check_scope_selection(_("Sele_ction"), _("Limit search to the current selection")), + check_searchin_text(_("_Text"), _("Search in text objects")), check_searchin_property(_("_Properties"), _("Search in object properties, styles, attributes and IDs")), vbox_searchin(0, false), frame_searchin(_("Search in")), @@ -85,9 +89,9 @@ Find::Find() check_ids(_("_ID"), _("Search id name"), true), check_attributename(_("Attribute _name"), _("Search attribute name"), false), - check_attributevalue(_("Attribute _value"), _("Search attribute value"), true), + check_attributevalue(_("Attri_bute value"), _("Search attribute value"), true), check_style(_("_Style"), _("Search style"), true), - check_font(_("_Font"), _("Search fonts"), false), + check_font(_("F_ont"), _("Search fonts"), false), frame_properties(_("Properties")), check_alltypes(_("All types"), _("Search all object types"), true), @@ -333,8 +337,7 @@ bool Find::find_strcmp(const gchar *str, const gchar *find, bool exact, bool cas return (std::string::npos != find_strcmp_pos(str, find, exact, casematch)); } -bool -Find::item_text_match (SPItem *item, const gchar *find, bool exact, bool casematch, bool replace/*=false*/) +bool Find::item_text_match (SPItem *item, const gchar *find, bool exact, bool casematch, bool replace/*=false*/) { if (item->getRepr() == NULL) { return false; @@ -379,8 +382,7 @@ Find::item_text_match (SPItem *item, const gchar *find, bool exact, bool casemat } -bool -Find::item_id_match (SPItem *item, const gchar *id, bool exact, bool casematch, bool replace/*=false*/) +bool Find::item_id_match (SPItem *item, const gchar *id, bool exact, bool casematch, bool replace/*=false*/) { if (item->getRepr() == NULL) { return false; @@ -409,8 +411,7 @@ Find::item_id_match (SPItem *item, const gchar *id, bool exact, bool casematch, return found; } -bool -Find::item_style_match (SPItem *item, const gchar *text, bool exact, bool casematch, bool replace/*=false*/) +bool Find::item_style_match (SPItem *item, const gchar *text, bool exact, bool casematch, bool replace/*=false*/) { if (item->getRepr() == NULL) { return false; @@ -547,8 +548,7 @@ bool Find::item_font_match(SPItem *item, const gchar *text, bool exact, bool cas } -GSList * -Find::filter_fields (GSList *l, bool exact, bool casematch) +GSList *Find::filter_fields (GSList *l, bool exact, bool casematch) { Glib::ustring tmp = entry_find.getEntry()->get_text(); if (tmp.empty()) { @@ -657,15 +657,14 @@ Find::filter_fields (GSList *l, bool exact, bool casematch) } -bool -Find::item_type_match (SPItem *item) +bool Find::item_type_match (SPItem *item) { bool all =check_alltypes.get_active(); if ( SP_IS_RECT(item)) { return ( all ||check_rects.get_active()); - } else if (SP_IS_GENERICELLIPSE(item) || SP_IS_ELLIPSE(item) || SP_IS_ARC(item) || SP_IS_CIRCLE(item)) { + } else if (SP_IS_GENERICELLIPSE(item)) { return ( all || check_ellipses.get_active()); } else if (SP_IS_STAR(item) || SP_IS_POLYGON(item)) { @@ -696,8 +695,7 @@ Find::item_type_match (SPItem *item) return false; } -GSList * -Find::filter_types (GSList *l) +GSList *Find::filter_types (GSList *l) { GSList *n = NULL; for (GSList *i = l; i != NULL; i = i->next) { @@ -709,16 +707,14 @@ Find::filter_types (GSList *l) } -GSList * -Find::filter_list (GSList *l, bool exact, bool casematch) +GSList *Find::filter_list (GSList *l, bool exact, bool casematch) { l = filter_types (l); l = filter_fields (l, exact, casematch); return l; } -GSList * -Find::all_items (SPObject *r, GSList *l, bool hidden, bool locked) +GSList *Find::all_items (SPObject *r, GSList *l, bool hidden, bool locked) { if (SP_IS_DEFS(r)) { return l; // we're not interested in items in defs @@ -740,8 +736,7 @@ Find::all_items (SPObject *r, GSList *l, bool hidden, bool locked) return l; } -GSList * -Find::all_selection_items (Inkscape::Selection *s, GSList *l, SPObject *ancestor, bool hidden, bool locked) +GSList *Find::all_selection_items (Inkscape::Selection *s, GSList *l, SPObject *ancestor, bool hidden, bool locked) { for (GSList *i = (GSList *) s->itemList(); i != NULL; i = i->next) { if (SP_IS_ITEM (i->data) && !reinterpret_cast<SPItem *>(i->data)->cloned && !desktop->isLayer(SP_ITEM(i->data))) { @@ -765,8 +760,7 @@ Find::all_selection_items (Inkscape::Selection *s, GSList *l, SPObject *ancestor # BUTTON CLICK HANDLERS (callbacks) ########################################################################*/ -void -Find::onFind() +void Find::onFind() { _action_replace = false; onAction(); @@ -775,8 +769,7 @@ Find::onFind() entry_find.getEntry()->grab_focus(); } -void -Find::onReplace() +void Find::onReplace() { if (entry_find.getEntry()->get_text().length() < 1) { status.set_text(_("Nothing to replace")); @@ -789,8 +782,7 @@ Find::onReplace() entry_find.getEntry()->grab_focus(); } -void -Find::onAction() +void Find::onAction() { bool hidden = check_include_hidden.get_active(); @@ -827,11 +819,13 @@ Find::onAction() count, all, exact? _("exact") : _("partial")); if (_action_replace){ // TRANSLATORS: "%1" is replaced with the number of matches - status.set_text(Glib::ustring::compose(_("%1 objects replaced"), count)); + status.set_text(Glib::ustring::compose(ngettext("%1 match replaced","%1 matches replaced",count), count)); } else { // TRANSLATORS: "%1" is replaced with the number of matches - status.set_text(Glib::ustring::compose(_("%1 objects found"), count)); + status.set_text(Glib::ustring::compose(ngettext("%1 object found","%1 objects found",count), count)); + bool attributenameyok = !check_attributename.get_active(); + button_replace.set_sensitive(attributenameyok); } Inkscape::Selection *selection = sp_desktop_selection (desktop); @@ -840,7 +834,7 @@ Find::onAction() scroll_to_show_item (desktop, SP_ITEM(n->data)); if (_action_replace) { - DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT, _("Text Replace")); + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT, _("Replace text or property")); } } else { @@ -854,8 +848,8 @@ Find::onAction() blocked = false; } -void -Find::onToggleCheck () + +void Find::onToggleCheck () { bool objectok = false; status.set_text(""); @@ -892,15 +886,14 @@ Find::onToggleCheck () } // Can't replace attribute names - bool attributenameyok = !check_attributename.get_active(); + // bool attributenameyok = !check_attributename.get_active(); button_find.set_sensitive(objectok && propertyok); - button_replace.set_sensitive(objectok && propertyok && attributenameyok); - + // button_replace.set_sensitive(objectok && propertyok && attributenameyok); + button_replace.set_sensitive(false); } -void -Find::onToggleAlltypes () +void Find::onToggleAlltypes () { bool all =check_alltypes.get_active(); for(size_t i = 0; i < checkTypes.size(); i++) { @@ -910,30 +903,26 @@ Find::onToggleAlltypes () onToggleCheck(); } -void -Find::onSearchinText () +void Find::onSearchinText () { searchinToggle(false); onToggleCheck(); } -void -Find::onSearchinProperty () +void Find::onSearchinProperty () { searchinToggle(true); onToggleCheck(); } -void -Find::searchinToggle(bool on) +void Find::searchinToggle(bool on) { for(size_t i = 0; i < checkProperties.size(); i++) { checkProperties[i]->set_sensitive(on); } } -void -Find::onExpander () +void Find::onExpander () { if (!expander_options.get_expanded()) squeeze_window(); @@ -943,8 +932,7 @@ Find::onExpander () # UTILITY ########################################################################*/ -void -Find::squeeze_window() +void Find::squeeze_window() { // TODO: resize dialog window when the expander is closed // set_size_request(-1, -1); diff --git a/src/ui/dialog/find.h b/src/ui/dialog/find.h index 64fb4cc3d..c0c635f94 100644 --- a/src/ui/dialog/find.h +++ b/src/ui/dialog/find.h @@ -12,14 +12,20 @@ #ifndef INKSCAPE_UI_DIALOG_FIND_H #define INKSCAPE_UI_DIALOG_FIND_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + #include "ui/widget/panel.h" #include "ui/widget/button.h" #include "ui/widget/entry.h" #include "ui/widget/frame.h" -#include <glib.h> -#include <gtkmm.h> -#include "desktop.h" +#include <gtkmm/box.h> +#include <gtkmm/buttonbox.h> +#include <gtkmm/expander.h> +#include <gtkmm/label.h> + #include "ui/dialog/desktop-tracker.h" class SPItem; @@ -280,7 +286,13 @@ private: Gtk::Label status; UI::Widget::Button button_find; UI::Widget::Button button_replace; + +#if WITH_GTKMM_3_0 + Gtk::ButtonBox box_buttons; +#else Gtk::HButtonBox box_buttons; +#endif + Gtk::HBox hboxbutton_row; /** diff --git a/src/ui/dialog/floating-behavior.cpp b/src/ui/dialog/floating-behavior.cpp index ba81c6d47..dd07f009a 100644 --- a/src/ui/dialog/floating-behavior.cpp +++ b/src/ui/dialog/floating-behavior.cpp @@ -10,8 +10,17 @@ * Released under GNU GPL. Read the file 'COPYING' for more information. */ +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/dialog.h> #include <gtkmm/stock.h> +#include <glibmm/main.h> #include <gtk/gtk.h> #include "floating-behavior.h" @@ -134,7 +143,13 @@ FloatingBehavior::create(Dialog &dialog) inline FloatingBehavior::operator Gtk::Widget &() { return *_d; } inline GtkWidget *FloatingBehavior::gobj() { return GTK_WIDGET(_d->gobj()); } -inline Gtk::Box* FloatingBehavior::get_vbox() { return _d->get_vbox(); } +inline Gtk::Box* FloatingBehavior::get_vbox() { +#if WITH_GTKMM_3_0 + return _d->get_content_area(); +#else + return _d->get_vbox(); +#endif +} inline void FloatingBehavior::present() { _d->present(); } inline void FloatingBehavior::hide() { _d->hide(); } inline void FloatingBehavior::show() { _d->show(); } diff --git a/src/ui/dialog/font-substitution.cpp b/src/ui/dialog/font-substitution.cpp new file mode 100644 index 000000000..bf9133086 --- /dev/null +++ b/src/ui/dialog/font-substitution.cpp @@ -0,0 +1,303 @@ +/* + * Authors: + * + * Copyright (C) 2012 Authors + * + * Released under GNU GPL. Read the file 'COPYING' for more information. + */ + +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + +#include <gtkmm/messagedialog.h> +#include <gtkmm/checkbutton.h> +#include <gtkmm/scrolledwindow.h> +#include <gtkmm/textview.h> + +#include <set> +#include "font-substitution.h" + +#include "inkscape.h" +#include "desktop.h" +#include "document.h" +#include "selection.h" + +#include "dialogs/dialog-events.h" +#include "desktop-handles.h" +#include "selection-chemistry.h" +#include "preferences.h" + +#include "xml/repr.h" + +#include "sp-defs.h" +#include "sp-root.h" +#include "sp-text.h" +#include "sp-textpath.h" +#include "sp-flowtext.h" +#include "sp-flowdiv.h" +#include "sp-tspan.h" +#include "sp-tref.h" +#include "style.h" +#include "text-editing.h" + +#include "libnrtype/FontFactory.h" +#include "libnrtype/font-instance.h" + +#include <glibmm/i18n.h> +#include <glibmm/regex.h> + +namespace Inkscape { +namespace UI { +namespace Dialog { + +FontSubstitution::FontSubstitution() +{ +} + +FontSubstitution::~FontSubstitution() +{ +} + +void +FontSubstitution::checkFontSubstitutions(SPDocument* doc) +{ + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int show_dlg = prefs->getInt("/options/font/substitutedlg", 0); + if (show_dlg) { + Glib::ustring out; + GSList *l = getFontReplacedItems(doc, &out); + if (out.length() > 0) { + show(out, l); + } + if (l) { + g_slist_free(l); + l = NULL; + } + } +} + +void +FontSubstitution::show(Glib::ustring out, GSList *l) +{ + Gtk::MessageDialog warning(_("\nSome fonts are not available and have been substituted."), + false, Gtk::MESSAGE_INFO, Gtk::BUTTONS_OK, true); + warning.set_resizable(true); + warning.set_title(_("Font substitution")); + + GtkWidget *dlg = GTK_WIDGET(warning.gobj()); + sp_transientize(dlg); + + Gtk::TextView * textview = new Gtk::TextView(); + textview->set_editable(false); + textview->set_wrap_mode(Gtk::WRAP_WORD); + textview->show(); + textview->get_buffer()->set_text(_(out.c_str())); + + Gtk::ScrolledWindow * scrollwindow = new Gtk::ScrolledWindow(); + scrollwindow->add(*textview); + scrollwindow->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); + scrollwindow->set_shadow_type(Gtk::SHADOW_IN); + scrollwindow->set_size_request(0, 100); + scrollwindow->show(); + + Gtk::CheckButton *cbSelect = new Gtk::CheckButton(); + cbSelect->set_label(_("Select all the affected items")); + cbSelect->set_active(true); + cbSelect->show(); + + Gtk::CheckButton *cbWarning = new Gtk::CheckButton(); + cbWarning->set_label(_("Don't show this warning again")); + cbWarning->show(); + +#if GTK_CHECK_VERSION(3,0,0) + Gtk::Box * box = warning.get_content_area(); +#else + Gtk::Box * box = warning.get_vbox(); +#endif + box->set_spacing(2); + box->pack_start(*scrollwindow, true, true, 4); + box->pack_start(*cbSelect, false, false, 0); + box->pack_start(*cbWarning, false, false, 0); + + warning.run(); + + if (cbWarning->get_active()) { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + prefs->setInt("/options/font/substitutedlg", 0); + } + + if (cbSelect->get_active()) { + + SPDesktop *desktop = SP_ACTIVE_DESKTOP; + Inkscape::Selection *selection = sp_desktop_selection (desktop); + selection->clear(); + selection->setList(l); + } + +} + +/* + * Find all the fonts that are in the document but not available on the users system + * and have been substituted for other fonts + * + * Return a list of SPItems where fonts have been substituted. + * + * Walk thru all the objects ... + * a. Build up a list of the objects with fonts defined in the style attribute + * b. Build up a list of the objects rendered fonts - taken for the objects layout/spans + * If there are fonts in a. that are not in b. then those fonts have been substituted. + */ +GSList * FontSubstitution::getFontReplacedItems(SPDocument* doc, Glib::ustring *out) +{ + SPDesktop *desktop = SP_ACTIVE_DESKTOP; + GSList *allList = NULL; + GSList *outList = NULL; + std::set<Glib::ustring> setErrors; + std::set<Glib::ustring> setFontSpans; + std::map<SPItem *, Glib::ustring> mapFontStyles; + + allList = get_all_items(NULL, doc->getRoot(), desktop, false, false, true, NULL); + + for (GSList *i = allList; i != NULL; i = i->next) { + + SPItem *item = SP_ITEM(i->data); + SPStyle *style = item->style; + Glib::ustring family = ""; + + if (is_top_level_text_object (item)) { + // Should only need to check the first span, since the others should be covered by TSPAN's etc + family = te_get_layout(item)->getFontFamily(0); + setFontSpans.insert(family); + } + else if (SP_IS_TEXTPATH(item)) { + SPTextPath const *textpath = SP_TEXTPATH(item); + if (textpath->originalPath != NULL) { + family = SP_TEXT(item->parent)->layout.getFontFamily(0); + setFontSpans.insert(family); + } + } + else if (SP_IS_TSPAN(item) || SP_IS_FLOWTSPAN(item)) { + // is_part_of_text_subtree (item) + // TSPAN layout comes from the parent->layout->_spans + SPObject *parent_text = item; + while (parent_text && !SP_IS_TEXT(parent_text)) { + parent_text = parent_text->parent; + } + if (parent_text != NULL) { + family = SP_TEXT(parent_text)->layout.getFontFamily(0); + // Add all the spans fonts to the set + gint ii = 0; + for (SPObject *child = parent_text->firstChild() ; child ; child = child->getNext() ) { + family = SP_TEXT(parent_text)->layout.getFontFamily(ii); + setFontSpans.insert(family); + ii++; + } + } + } + + if (style && style->text) { + gchar const *style_font = NULL; + if (style->text->font_family.set) + style_font = style->text->font_family.value; + else if (style->text->font_specification.set) + style_font = style->text->font_specification.value; + else if (style->text->font_family.value) + style_font = style->text->font_family.value; + else if (style->text->font_specification.value) + style_font = style->text->font_specification.value; + + if (style_font) { + if (has_visible_text(item)) { + mapFontStyles.insert(std::make_pair (item, style_font)); + } + } + } + } + + // Check if any document styles are not in the actual layout + std::map<SPItem *, Glib::ustring>::const_iterator mapIter; + for (mapIter = mapFontStyles.begin(); mapIter != mapFontStyles.end(); ++mapIter) { + SPItem *item = mapIter->first; + Glib::ustring fonts = mapIter->second; + + // CSS font fallbacks can have more that one font listed, split the font list + std::vector<Glib::ustring> vFonts = Glib::Regex::split_simple("," , fonts); + bool fontFound = false; + for(size_t i=0; i<vFonts.size(); i++) { + Glib::ustring font = vFonts[i]; + // trim whitespace + size_t startpos = font.find_first_not_of(" \n\r\t"); + size_t endpos = font.find_last_not_of(" \n\r\t"); + if(( std::string::npos == startpos ) || ( std::string::npos == endpos)) { + continue; // empty font name + } + font = font.substr( startpos, endpos-startpos+1 ); + std::set<Glib::ustring>::const_iterator iter = setFontSpans.find(font); + if (iter != setFontSpans.end() || + font == Glib::ustring("sans-serif") || + font == Glib::ustring("Sans") || + font == Glib::ustring("serif") || + font == Glib::ustring("Serif") || + font == Glib::ustring("monospace") || + font == Glib::ustring("Monospace")) { + fontFound = true; + break; + } + } + if (fontFound == false) { + Glib::ustring subName = getSubstituteFontName(fonts); + Glib::ustring err = Glib::ustring::compose( + _("Font '%1' substituted with '%2'"), fonts.c_str(), subName.c_str()); + setErrors.insert(err); + outList = g_slist_prepend (outList, item); + } + } + + std::set<Glib::ustring>::const_iterator setIter; + for (setIter = setErrors.begin(); setIter != setErrors.end(); ++setIter) { + Glib::ustring err = (*setIter); + out->append(err + "\n"); + g_warning("%s", err.c_str()); + } + + return outList; +} + + +Glib::ustring FontSubstitution::getSubstituteFontName (Glib::ustring font) +{ + Glib::ustring out = font; + + PangoFontDescription *descr = pango_font_description_new(); + pango_font_description_set_family(descr,font.c_str()); + font_instance *res = (font_factory::Default())->Face(descr); + if (res->pFont) { + PangoFontDescription *nFaceDesc = pango_font_describe(res->pFont); + out = sp_font_description_get_family(nFaceDesc); + } + pango_font_description_free(descr); + + return out; +} + + +} // namespace Dialog +} // namespace UI +} // namespace Inkscape + + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/dialog/font-substitution.h b/src/ui/dialog/font-substitution.h new file mode 100644 index 000000000..1c445081b --- /dev/null +++ b/src/ui/dialog/font-substitution.h @@ -0,0 +1,56 @@ +/** @file + * @brief FontSubstitution dialog + */ +/* Authors: + * + * + * Copyright (C) 2012 Authors + * + * Released under GNU GPL. Read the file 'COPYING' for more information. + */ + +#ifndef INKSCAPE_UI_FONT_SUBSTITUTION_H +#define INKSCAPE_UI_FONT_SUBSTITUTION_H + +#include <glibmm/ustring.h> + +class SPDocument; + +namespace Inkscape { +namespace UI { +namespace Dialog { + +class FontSubstitution { +public: + FontSubstitution(); + virtual ~FontSubstitution(); + void checkFontSubstitutions(SPDocument* doc); + void show(Glib::ustring out, GSList *l); + + static FontSubstitution &getInstance() { return *new FontSubstitution(); } + Glib::ustring getSubstituteFontName (Glib::ustring font); + +protected: + GSList *getFontReplacedItems(SPDocument* doc, Glib::ustring *out); + +private: + FontSubstitution(FontSubstitution const &d); + FontSubstitution& operator=(FontSubstitution const &d); +}; + +} // namespace Dialog +} // namespace UI +} // namespace Inkscape + +#endif // INKSCAPE_UI_FONT_SUBSTITUTION_H + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/dialog/glyphs.cpp b/src/ui/dialog/glyphs.cpp index b2ded6495..9bad90e7c 100644 --- a/src/ui/dialog/glyphs.cpp +++ b/src/ui/dialog/glyphs.cpp @@ -1,6 +1,7 @@ /* Authors: * Jon A. Cruz * Abhishek Sharma + * Tavmjong Bah * * Copyright (C) 2010 Jon A. Cruz * Released under GNU GPL, read the file 'COPYING' for more information @@ -18,7 +19,13 @@ #include <gtkmm/label.h> #include <gtkmm/liststore.h> #include <gtkmm/scrolledwindow.h> -#include <gtkmm/table.h> + +#if WITH_GTKMM_3_0 +# include <gtkmm/grid.h> +#else +# include <gtkmm/table.h> +#endif + #include <gtkmm/treemodelcolumn.h> #include <gtkmm/widget.h> @@ -335,7 +342,12 @@ GlyphsPanel::GlyphsPanel(gchar const *prefsPath) : instanceConns(), desktopConns() { +#if WITH_GTKMM_3_0 + Gtk::Grid *table = new Gtk::Grid(); +#else Gtk::Table *table = new Gtk::Table(3, 1, false); +#endif + _getContents()->pack_start(*Gtk::manage(table), Gtk::PACK_EXPAND_WIDGET); guint row = 0; @@ -343,13 +355,19 @@ GlyphsPanel::GlyphsPanel(gchar const *prefsPath) : GtkWidget *fontsel = sp_font_selector_new(); fsel = SP_FONT_SELECTOR(fontsel); - sp_font_selector_set_font(fsel, sp_font_selector_get_font(fsel), 12.0); + sp_font_selector_set_fontspec( fsel, sp_font_selector_get_fontspec(fsel), 12.0 ); + gtk_widget_set_size_request (fontsel, 0, 150); g_signal_connect( G_OBJECT(fontsel), "font_set", G_CALLBACK(fontChangeCB), this ); +#if WITH_GTKMM_3_0 + table->attach(*Gtk::manage(Glib::wrap(fontsel)), 0, row, 3, 1); +#else table->attach(*Gtk::manage(Glib::wrap(fontsel)), 0, 3, row, row + 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL); +#endif + row++; @@ -357,33 +375,35 @@ GlyphsPanel::GlyphsPanel(gchar const *prefsPath) : { Gtk::Label *label = new Gtk::Label(_("Script: ")); + +#if WITH_GTKMM_3_0 + table->attach( *Gtk::manage(label), 0, row, 1, 1); +#else table->attach( *Gtk::manage(label), 0, 1, row, row + 1, Gtk::SHRINK, Gtk::SHRINK); +#endif scriptCombo = new Gtk::ComboBoxText(); for (std::map<GUnicodeScript, Glib::ustring>::iterator it = getScriptToName().begin(); it != getScriptToName().end(); ++it) { -#if WITH_GTKMM_2_24 scriptCombo->append(it->second); -#else - scriptCombo->append_text(it->second); -#endif } scriptCombo->set_active_text(getScriptToName()[G_UNICODE_SCRIPT_INVALID_CODE]); sigc::connection conn = scriptCombo->signal_changed().connect(sigc::mem_fun(*this, &GlyphsPanel::rebuild)); instanceConns.push_back(conn); + Gtk::Alignment *align = Gtk::manage(new Gtk::Alignment(Gtk::ALIGN_START, Gtk::ALIGN_START, 0.0, 0.0)); + align->add(*Gtk::manage(scriptCombo)); -#if WITH_GTKMM_2_22 - Gtk::Alignment *align = new Gtk::Alignment(Gtk::ALIGN_START, Gtk::ALIGN_START, 0.0, 0.0); +#if WITH_GTKMM_3_0 + align->set_hexpand(); + table->attach( *align, 1, row, 1, 1); #else - Gtk::Alignment *align = new Gtk::Alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_TOP, 0.0, 0.0); -#endif - align->add(*Gtk::manage(scriptCombo)); - table->attach( *Gtk::manage(align), + table->attach( *align, 1, 2, row, row + 1, Gtk::FILL|Gtk::EXPAND, Gtk::SHRINK); +#endif } row++; @@ -392,32 +412,34 @@ GlyphsPanel::GlyphsPanel(gchar const *prefsPath) : { Gtk::Label *label = new Gtk::Label(_("Range: ")); + +#if WITH_GTKMM_3_0 + table->attach( *Gtk::manage(label), 0, row, 1, 1); +#else table->attach( *Gtk::manage(label), 0, 1, row, row + 1, Gtk::SHRINK, Gtk::SHRINK); +#endif rangeCombo = new Gtk::ComboBoxText(); for ( std::vector<NamedRange>::iterator it = getRanges().begin(); it != getRanges().end(); ++it ) { -#if WITH_GTKMM_2_24 rangeCombo->append(it->second); -#else - rangeCombo->append_text(it->second); -#endif } rangeCombo->set_active_text(getRanges()[1].second); sigc::connection conn = rangeCombo->signal_changed().connect(sigc::mem_fun(*this, &GlyphsPanel::rebuild)); instanceConns.push_back(conn); - -#if WITH_GTKMM_2_22 Gtk::Alignment *align = new Gtk::Alignment(Gtk::ALIGN_START, Gtk::ALIGN_START, 0.0, 0.0); -#else - Gtk::Alignment *align = new Gtk::Alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_TOP, 0.0, 0.0); -#endif align->add(*Gtk::manage(rangeCombo)); + +#if WITH_GTKMM_3_0 + align->set_hexpand(); + table->attach( *Gtk::manage(align), 1, row, 1, 1); +#else table->attach( *Gtk::manage(align), 1, 2, row, row + 1, Gtk::FILL|Gtk::EXPAND, Gtk::SHRINK); +#endif } row++; @@ -426,7 +448,7 @@ GlyphsPanel::GlyphsPanel(gchar const *prefsPath) : GlyphColumns *columns = getColumns(); - iconView = new Gtk::IconView(store); + iconView = new Gtk::IconView(static_cast<Glib::RefPtr<Gtk::TreeModel> >(store)); iconView->set_text_column(columns->name); //iconView->set_columns(16); @@ -440,9 +462,17 @@ GlyphsPanel::GlyphsPanel(gchar const *prefsPath) : Gtk::ScrolledWindow *scroller = new Gtk::ScrolledWindow(); scroller->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_ALWAYS); scroller->add(*Gtk::manage(iconView)); + +#if WITH_GTKMM_3_0 + scroller->set_hexpand(); + scroller->set_vexpand(); + table->attach(*Gtk::manage(scroller), 0, row, 3, 1); +#else table->attach(*Gtk::manage(scroller), 0, 3, row, row + 1, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL); +#endif + row++; // ------------------------------- @@ -472,9 +502,15 @@ GlyphsPanel::GlyphsPanel(gchar const *prefsPath) : box->pack_end(*Gtk::manage(insertBtn), Gtk::PACK_SHRINK); +#if WITH_GTKMM_3_0 + box->set_hexpand(); + table->attach( *Gtk::manage(box), 0, row, 3, 1); +#else table->attach( *Gtk::manage(box), 0, 3, row, row + 1, Gtk::EXPAND|Gtk::FILL, Gtk::SHRINK); +#endif + row++; // ------------------------------- @@ -538,6 +574,7 @@ void GlyphsPanel::setTargetDesktop(SPDesktop *desktop) } } +// Append selected glyphs to selected text void GlyphsPanel::insertText() { SPItem *textItem = 0; @@ -553,7 +590,13 @@ void GlyphsPanel::insertText() if (entry->get_text_length() > 0) { glyphs = entry->get_text(); } else { + +#if WITH_GTKMM_3_0 + std::vector<Gtk::TreePath> itemArray = iconView->get_selected_items(); +#else Gtk::IconView::ArrayHandle_TreePaths itemArray = iconView->get_selected_items(); +#endif + if (!itemArray.empty()) { Gtk::TreeModel::Path const & path = *itemArray.begin(); Gtk::ListStore::iterator row = store->get_iter(path); @@ -597,7 +640,12 @@ void GlyphsPanel::glyphActivated(Gtk::TreeModel::Path const & path) void GlyphsPanel::glyphSelectionChanged() { +#if WITH_GTKMM_3_0 + std::vector<Gtk::TreePath> itemArray = iconView->get_selected_items(); +#else Gtk::IconView::ArrayHandle_TreePaths itemArray = iconView->get_selected_items(); +#endif + if (itemArray.empty()) { label->set_text(" "); } else { @@ -618,7 +666,7 @@ void GlyphsPanel::glyphSelectionChanged() calcCanInsert(); } -void GlyphsPanel::fontChangeCB(SPFontSelector * /*fontsel*/, font_instance * /*font*/, GlyphsPanel *self) +void GlyphsPanel::fontChangeCB(SPFontSelector * /*fontsel*/, Glib::ustring /*fontspec*/, GlyphsPanel *self) { if (self) { self->rebuild(); @@ -674,7 +722,13 @@ void GlyphsPanel::readSelection( bool updateStyle, bool /*updateContent*/ ) void GlyphsPanel::rebuild() { - font_instance *font = fsel ? sp_font_selector_get_font(fsel) : 0; + Glib::ustring fontspec = fsel ? sp_font_selector_get_fontspec(fsel) : ""; + + font_instance* font = 0; + if( !fontspec.empty() ) { + font = font_factory::Default()->FaceFromFontSpecification( fontspec.c_str() ); + } + if (font) { //double sp_font_selector_get_size (SPFontSelector *fsel); diff --git a/src/ui/dialog/glyphs.h b/src/ui/dialog/glyphs.h index 162c7b296..3d0571244 100644 --- a/src/ui/dialog/glyphs.h +++ b/src/ui/dialog/glyphs.h @@ -20,7 +20,7 @@ class Label; class ListStore; } -class SPFontSelector; +struct SPFontSelector; class font_instance; @@ -54,7 +54,7 @@ private: static GlyphColumns *getColumns(); - static void fontChangeCB(SPFontSelector *fontsel, font_instance *font, GlyphsPanel *self); + static void fontChangeCB(SPFontSelector *fontsel, Glib::ustring fontspec, GlyphsPanel *self); void rebuild(); diff --git a/src/ui/dialog/grid-arrange-tab.cpp b/src/ui/dialog/grid-arrange-tab.cpp index 54b667ed9..7ff915265 100644 --- a/src/ui/dialog/grid-arrange-tab.cpp +++ b/src/ui/dialog/grid-arrange-tab.cpp @@ -15,14 +15,17 @@ */ //#define DEBUG_GRID_ARRANGE 1 -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - #include "ui/dialog/grid-arrange-tab.h" #include <gtk/gtk.h> //for GTK_RESPONSE* types #include <glibmm/i18n.h> #include <gtkmm/stock.h> + +#if WITH_GTKMM_3_0 +# include <gtkmm/grid.h> +#else +# include <gtkmm/table.h> +#endif + #include <2geom/transforms.h> #include "verbs.h" @@ -45,7 +48,7 @@ * 0 *elem1 == *elem2 * >0 *elem1 goes after *elem2 */ -int sp_compare_x_position(SPItem *first, SPItem *second) +static int sp_compare_x_position(SPItem *first, SPItem *second) { using Geom::X; using Geom::Y; @@ -87,7 +90,7 @@ int sp_compare_x_position(SPItem *first, SPItem *second) /* * Sort items by their y co-ordinates. */ -int sp_compare_y_position(SPItem *first, SPItem *second) +static int sp_compare_y_position(SPItem *first, SPItem *second) { Geom::OptRect a = first->documentVisualBounds(); Geom::OptRect b = second->documentVisualBounds(); @@ -126,7 +129,7 @@ void GridArrangeTab::arrange() { int cnt,row_cnt,col_cnt,a,row,col; - double grid_left,grid_top,col_width,row_height,paddingx,paddingy,width, height, new_x, new_y,cx,cy; + double grid_left,grid_top,col_width,row_height,paddingx,paddingy,width, height, new_x, new_y; double total_col_width,total_row_height; col_width = 0; row_height = 0; @@ -177,9 +180,6 @@ void GridArrangeTab::arrange() width = b->dimensions()[Geom::X]; height = b->dimensions()[Geom::Y]; - cx = b->midpoint()[Geom::X]; - cy = b->midpoint()[Geom::Y]; - if (b->min()[Geom::X] < grid_left) { grid_left = b->min()[Geom::X]; } @@ -199,7 +199,7 @@ void GridArrangeTab::arrange() g_return_if_fail(selection); const GSList *items2 = selection->itemList(); - GSList *rev = g_slist_copy((GSList *) items2); + GSList *rev = g_slist_copy(const_cast<GSList *>(items2)); GSList *sorted = NULL; rev = g_slist_sort(rev, (GCompareFunc) sp_compare_y_position); sorted = g_slist_sort(rev, (GCompareFunc) sp_compare_x_position); @@ -586,8 +586,8 @@ static void updateSelectionCallback(Inkscape::Application */*inkscape*/, Inkscap */ GridArrangeTab::GridArrangeTab(ArrangeDialog *parent) : Parent(parent), - XPadding(_("X:"), _("Horizontal spacing between columns."), UNIT_TYPE_LINEAR, "", "object-columns"), - YPadding(_("Y:"), _("Vertical spacing between rows."), XPadding, "", "object-rows") + XPadding(_("X:"), _("Horizontal spacing between columns."), UNIT_TYPE_LINEAR, "", "object-columns", &PaddingUnitMenu), + YPadding(_("Y:"), _("Vertical spacing between rows."), XPadding, "", "object-rows", &PaddingUnitMenu) { // bool used by spin button callbacks to stop loops where they change each other. updating = false; @@ -665,7 +665,7 @@ GridArrangeTab::GridArrangeTab(ArrangeDialog *parent) XByYLabel.set_markup(" × "); XByYLabelVBox.pack_start(XByYLabel, false, false, MARGIN); SpinsHBox.pack_start(XByYLabelVBox, false, false, MARGIN); - gtk_size_group_add_widget(_col2, (GtkWidget *) XByYLabelVBox.gobj()); + gtk_size_group_add_widget(_col2, GTK_WIDGET(XByYLabelVBox.gobj())); /*#### Number of columns ####*/ @@ -680,7 +680,7 @@ GridArrangeTab::GridArrangeTab(ArrangeDialog *parent) NoOfColsSpinner.signal_changed().connect(sigc::mem_fun(*this, &GridArrangeTab::on_row_spinbutton_changed)); NoOfColsSpinner.set_tooltip_text(_("Number of columns")); NoOfColsBox.pack_start(NoOfColsSpinner, false, false, MARGIN); - gtk_size_group_add_widget(_col3, (GtkWidget *) NoOfColsBox.gobj()); + gtk_size_group_add_widget(_col3, GTK_WIDGET(NoOfColsBox.gobj())); ColumnWidthButton.set_label(_("Equal _width")); ColumnWidthButton.set_use_underline(true); @@ -730,6 +730,8 @@ GridArrangeTab::GridArrangeTab(ArrangeDialog *parent) { /*#### Padding ####*/ + PaddingUnitMenu.setUnitType(UNIT_TYPE_LINEAR); + PaddingUnitMenu.setUnit("px"); YPadding.setDigits(5); YPadding.setIncrements(0.2, 0); @@ -746,8 +748,24 @@ GridArrangeTab::GridArrangeTab(ArrangeDialog *parent) XPadding.signal_value_changed().connect(sigc::mem_fun(*this, &GridArrangeTab::on_xpad_spinbutton_changed)); } - TileBox.pack_start(XPadding, false, false, MARGIN); - TileBox.pack_start(YPadding, false, false, MARGIN); + + PaddingTable->set_border_width(MARGIN); + +#if WITH_GTKMM_3_0 + PaddingTable->set_row_spacing(MARGIN); + PaddingTable->set_column_spacing(MARGIN); + PaddingTable->attach(XPadding, 0, 0, 1, 1); + PaddingTable->attach(PaddingUnitMenu, 1, 0, 1, 1); + PaddingTable->attach(YPadding, 0, 1, 1, 1); +#else + PaddingTable->set_row_spacings(MARGIN); + PaddingTable->set_col_spacings(MARGIN); + PaddingTable->attach(XPadding, 0, 1, 0, 1, Gtk::SHRINK, Gtk::SHRINK); + PaddingTable->attach(PaddingUnitMenu, 1, 2, 0, 1, Gtk::SHRINK, Gtk::SHRINK); + PaddingTable->attach(YPadding, 0, 1, 1, 2, Gtk::SHRINK, Gtk::SHRINK); +#endif + + TileBox.pack_start(*PaddingTable, false, false, MARGIN); contents->pack_start(TileBox); diff --git a/src/ui/dialog/grid-arrange-tab.h b/src/ui/dialog/grid-arrange-tab.h index 2744ca87f..9d6700b39 100644 --- a/src/ui/dialog/grid-arrange-tab.h +++ b/src/ui/dialog/grid-arrange-tab.h @@ -106,9 +106,16 @@ private: double VertAlign; double HorizAlign; + Inkscape::UI::Widget::UnitMenu PaddingUnitMenu; Inkscape::UI::Widget::ScalarUnit XPadding; Inkscape::UI::Widget::ScalarUnit YPadding; +#if WITH_GTKMM_3_0 + Gtk::Grid *PaddingTable; +#else + Gtk::Table *PaddingTable; +#endif + // BBox or manual spacing Gtk::VBox SpacingVBox; Gtk::RadioButtonGroup SpacingGroup; diff --git a/src/ui/dialog/guides.cpp b/src/ui/dialog/guides.cpp index d20f2a220..e84f25733 100644 --- a/src/ui/dialog/guides.cpp +++ b/src/ui/dialog/guides.cpp @@ -25,7 +25,7 @@ #include "sp-guide.h" #include "sp-namedview.h" #include "desktop-handles.h" -#include "event-context.h" +#include "ui/tools/tool-base.h" #include "widgets/desktop-widget.h" #include <glibmm/i18n.h> #include "dialogs/dialog-events.h" @@ -45,8 +45,8 @@ namespace Dialogs { GuidelinePropertiesDialog::GuidelinePropertiesDialog(SPGuide *guide, SPDesktop *desktop) : _desktop(desktop), _guide(guide), _relative_toggle(_("Rela_tive change"), _("Move and/or rotate the guide relative to current settings")), - _spin_button_x(_("_X:"), "", UNIT_TYPE_LINEAR, "", "", &_unit_menu), - _spin_button_y(_("_Y:"), "", UNIT_TYPE_LINEAR, "", "", &_unit_menu), + _spin_button_x(C_("Guides", "_X:"), "", UNIT_TYPE_LINEAR, "", "", &_unit_menu), + _spin_button_y(C_("Guides", "_Y:"), "", UNIT_TYPE_LINEAR, "", "", &_unit_menu), _label_entry(_("_Label:"), _("Optionally give this guideline a name")), _spin_angle(_("_Angle:"), "", UNIT_TYPE_RADIAL), _mode(true), _oldpos(0.,0.), _oldangle(0.0) @@ -59,7 +59,7 @@ Glib::ustring GuidelinePropertiesDialog::_angle_unit_status = DEG; // initialize GuidelinePropertiesDialog::~GuidelinePropertiesDialog() { // save current status _relative_toggle_status = _relative_toggle.get_active(); - _angle_unit_status = _spin_angle.getUnit().abbr; + _angle_unit_status = _spin_angle.getUnit()->abbr; } void GuidelinePropertiesDialog::showDialog(SPGuide *guide, SPDesktop *desktop) { @@ -70,9 +70,15 @@ void GuidelinePropertiesDialog::showDialog(SPGuide *guide, SPDesktop *desktop) { void GuidelinePropertiesDialog::_colorChanged() { +#if WITH_GTKMM_3_0 + const Gdk::RGBA c = _color.get_rgba(); + unsigned r = c.get_red_u()/257, g = c.get_green_u()/257, b = c.get_blue_u()/257; +#else const Gdk::Color c = _color.get_color(); unsigned r = c.get_red()/257, g = c.get_green()/257, b = c.get_blue()/257; +#endif //TODO: why 257? verify this! + sp_guide_set_color(*_guide, r, g, b, true); } @@ -166,32 +172,56 @@ void GuidelinePropertiesDialog::_setup() { add_button(Gtk::Stock::DELETE, -12); add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL); +#if WITH_GTKMM_3_0 + Gtk::Box *mainVBox = get_content_area(); + _layout_table.set_row_spacing(4); + _layout_table.set_column_spacing(4); +#else Gtk::Box *mainVBox = get_vbox(); - _layout_table.set_spacings(4); _layout_table.resize (3, 4); +#endif mainVBox->pack_start(_layout_table, false, false, 0); _label_name.set_label("foo0"); - _layout_table.attach(_label_name, - 0, 3, 0, 1, Gtk::FILL, Gtk::FILL); _label_name.set_alignment(0, 0.5); _label_descr.set_label("foo1"); - _layout_table.attach(_label_descr, - 0, 3, 1, 2, Gtk::FILL, Gtk::FILL); _label_descr.set_alignment(0, 0.5); + +#if WITH_GTKMM_3_0 + _label_name.set_halign(Gtk::ALIGN_FILL); + _label_name.set_valign(Gtk::ALIGN_FILL); + _layout_table.attach(_label_name, 0, 0, 3, 1); + + _label_descr.set_halign(Gtk::ALIGN_FILL); + _label_descr.set_valign(Gtk::ALIGN_FILL); + _layout_table.attach(_label_descr, 0, 1, 3, 1); + + _label_entry.set_halign(Gtk::ALIGN_FILL); + _label_entry.set_valign(Gtk::ALIGN_FILL); + _label_entry.set_hexpand(); + _layout_table.attach(_label_entry, 1, 2, 2, 1); + + _color.set_halign(Gtk::ALIGN_FILL); + _color.set_valign(Gtk::ALIGN_FILL); + _color.set_hexpand(); + _layout_table.attach(_color, 1, 3, 2, 1); +#else + _layout_table.attach(_label_name, + 0, 3, 0, 1, Gtk::FILL, Gtk::FILL); - // indent -// _layout_table.attach(*manage(new Gtk::Label(" ")), -// 0, 1, 2, 3, Gtk::FILL, Gtk::FILL, 10); + _layout_table.attach(_label_descr, + 0, 3, 1, 2, Gtk::FILL, Gtk::FILL); _layout_table.attach(_label_entry, 1, 3, 2, 3, Gtk::EXPAND | Gtk::FILL, Gtk::FILL); _layout_table.attach(_color, 1, 3, 3, 4, Gtk::EXPAND | Gtk::FILL, Gtk::FILL); +#endif + _color.signal_color_set().connect(sigc::mem_fun(*this, &GuidelinePropertiesDialog::_colorChanged)); @@ -200,7 +230,7 @@ void GuidelinePropertiesDialog::_setup() { _unit_menu.setUnitType(UNIT_TYPE_LINEAR); _unit_menu.setUnit("px"); if (_desktop->namedview->doc_units) { - _unit_menu.setUnit( sp_unit_get_abbreviation(_desktop->namedview->doc_units) ); + _unit_menu.setUnit( _desktop->namedview->doc_units->abbr ); } _spin_angle.setUnit(_angle_unit_status); @@ -211,6 +241,22 @@ void GuidelinePropertiesDialog::_setup() { _spin_button_y.setDigits(3); _spin_button_y.setIncrements(1.0, 10.0); _spin_button_y.setRange(-1e6, 1e6); + +#if WITH_GTKMM_3_0 + _spin_button_x.set_halign(Gtk::ALIGN_FILL); + _spin_button_x.set_valign(Gtk::ALIGN_FILL); + _spin_button_x.set_hexpand(); + _layout_table.attach(_spin_button_x, 1, 4, 1, 1); + + _spin_button_y.set_halign(Gtk::ALIGN_FILL); + _spin_button_y.set_valign(Gtk::ALIGN_FILL); + _spin_button_y.set_hexpand(); + _layout_table.attach(_spin_button_y, 1, 5, 1, 1); + + _unit_menu.set_halign(Gtk::ALIGN_FILL); + _unit_menu.set_valign(Gtk::ALIGN_FILL); + _layout_table.attach(_unit_menu, 2, 4, 1, 1); +#else _layout_table.attach(_spin_button_x, 1, 2, 4, 5, Gtk::EXPAND | Gtk::FILL, Gtk::FILL); _layout_table.attach(_spin_button_y, @@ -218,17 +264,33 @@ void GuidelinePropertiesDialog::_setup() { _layout_table.attach(_unit_menu, 2, 3, 4, 5, Gtk::FILL, Gtk::FILL); +#endif // angle spinbutton _spin_angle.setDigits(3); _spin_angle.setIncrements(1.0, 10.0); _spin_angle.setRange(-3600., 3600.); + +#if WITH_GTKMM_3_0 + _spin_angle.set_halign(Gtk::ALIGN_FILL); + _spin_angle.set_valign(Gtk::ALIGN_FILL); + _spin_angle.set_hexpand(); + _layout_table.attach(_spin_angle, 1, 6, 2, 1); + + // mode radio button + _relative_toggle.set_halign(Gtk::ALIGN_FILL); + _relative_toggle.set_valign(Gtk::ALIGN_FILL); + _relative_toggle.set_hexpand(); + _layout_table.attach(_relative_toggle, 1, 7, 2, 1); +#else _layout_table.attach(_spin_angle, 1, 3, 6, 7, Gtk::EXPAND | Gtk::FILL, Gtk::FILL); // mode radio button _layout_table.attach(_relative_toggle, 1, 3, 7, 8, Gtk::EXPAND | Gtk::FILL, Gtk::FILL); +#endif + _relative_toggle.signal_toggled().connect(sigc::mem_fun(*this, &GuidelinePropertiesDialog::_modeChanged)); _relative_toggle.set_active(_relative_toggle_status); @@ -272,9 +334,16 @@ void GuidelinePropertiesDialog::_setup() { // init name entry _label_entry.getEntry()->set_text(_guide->label ? _guide->label : ""); + +#if WITH_GTKMM_3_0 + Gdk::RGBA c; + c.set_rgba(((_guide->color>>24)&0xff) / 255.0, ((_guide->color>>16)&0xff) / 255.0, ((_guide->color>>8)&0xff) / 255.0); + _color.set_rgba(c); +#else Gdk::Color c; c.set_rgb_p(((_guide->color>>24)&0xff) / 255.0, ((_guide->color>>16)&0xff) / 255.0, ((_guide->color>>8)&0xff) / 255.0); _color.set_color(c); +#endif _modeChanged(); // sets values of spinboxes. diff --git a/src/ui/dialog/guides.h b/src/ui/dialog/guides.h index d06c3afc8..422fed7fe 100644 --- a/src/ui/dialog/guides.h +++ b/src/ui/dialog/guides.h @@ -11,8 +11,22 @@ #ifndef INKSCAPE_DIALOG_GUIDELINE_H #define INKSCAPE_DIALOG_GUIDELINE_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/dialog.h> + +#if WITH_GTKMM_3_0 +#include <gtkmm/grid.h> +#else #include <gtkmm/table.h> +#endif + #include <gtkmm/label.h> #include <gtkmm/colorbutton.h> #include "ui/widget/button.h" @@ -62,7 +76,13 @@ private: SPDesktop *_desktop; SPGuide *_guide; + +#if WITH_GTKMM_3_0 + Gtk::Grid _layout_table; +#else Gtk::Table _layout_table; +#endif + Gtk::Label _label_name; Gtk::Label _label_descr; Inkscape::UI::Widget::CheckButton _relative_toggle; diff --git a/src/ui/dialog/icon-preview.cpp b/src/ui/dialog/icon-preview.cpp index de213ca85..468e85d36 100644 --- a/src/ui/dialog/icon-preview.cpp +++ b/src/ui/dialog/icon-preview.cpp @@ -17,10 +17,17 @@ # include <config.h> #endif +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/buttonbox.h> #include <boost/scoped_ptr.hpp> -#include <glib.h> + #include <glibmm/i18n.h> +#include <glibmm/main.h> +#include <glibmm/timer.h> + #include <gtkmm/alignment.h> #include <gtkmm/checkbutton.h> #include <gtkmm/frame.h> diff --git a/src/ui/dialog/icon-preview.h b/src/ui/dialog/icon-preview.h index 42f9176b0..8a6e19a25 100644 --- a/src/ui/dialog/icon-preview.h +++ b/src/ui/dialog/icon-preview.h @@ -66,7 +66,12 @@ private: gdouble minDelay; Gtk::VBox iconBox; + +#if WITH_GTKMM_3_0 + Gtk::Paned splitter; +#else Gtk::HPaned splitter; +#endif Glib::ustring targetId; int hot; diff --git a/src/ui/dialog/inkscape-preferences.cpp b/src/ui/dialog/inkscape-preferences.cpp index 685ea70e1..03108b403 100644 --- a/src/ui/dialog/inkscape-preferences.cpp +++ b/src/ui/dialog/inkscape-preferences.cpp @@ -8,7 +8,7 @@ * Johan Engelen <j.b.c.engelen@ewi.utwente.nl> * Bruno Dilly <bruno.dilly@gmail.com> * - * Copyright (C) 2004-2011 Authors + * Copyright (C) 2004-2013 Authors * * Released under GNU GPL. Read the file 'COPYING' for more information. */ @@ -18,6 +18,8 @@ #endif #include "inkscape-preferences.h" +#include <glibmm/i18n.h> +#include <glibmm/miscutils.h> #include <gtkmm/main.h> #include <gtkmm/frame.h> #include <gtkmm/scrolledwindow.h> @@ -26,7 +28,7 @@ #include "preferences.h" #include "verbs.h" #include "selcue.h" -#include "unit-constants.h" +#include "util/units.h" #include <iostream> #include "enums.h" #include "desktop-handles.h" @@ -45,7 +47,11 @@ #include "display/canvas-grid.h" #include "path-prefix.h" #include "io/resource.h" +#include "io/sys.h" #include "inkscape.h" +#include "shortcuts.h" +#include "document.h" + #ifdef HAVE_ASPELL # include <aspell.h> @@ -77,7 +83,13 @@ InkscapePreferences::InkscapePreferences() sb->set_width_chars(6); _getContents()->add(*sb); show_all_children(); - Gtk::Requisition sreq = sb->size_request(); + Gtk::Requisition sreq; +#if WITH_GTKMM_3_0 + Gtk::Requisition sreq_natural; + sb->get_preferred_size(sreq_natural, sreq); +#else + sreq = sb->size_request(); +#endif _sb_width = sreq.width; _getContents()->remove(*sb); delete sb; @@ -129,6 +141,7 @@ InkscapePreferences::InkscapePreferences() initPageRendering(); initPageSpellcheck(); + signalPresent().connect(sigc::mem_fun(*this, &InkscapePreferences::_presentPages)); //calculate the size request for this dialog @@ -186,13 +199,13 @@ void InkscapePreferences::AddDotSizeSpinbutton(DialogPage &p, Glib::ustring cons { PrefSpinButton* sb = Gtk::manage( new PrefSpinButton); sb->init ( prefs_path + "/dot-size", 0.0, 1000.0, 0.1, 10.0, def_value, false, false); - p.add_line( false, _("Ctrl+click dot size:"), *sb, _("times current stroke width"), + p.add_line( false, _("Ctrl+click _dot size:"), *sb, _("times current stroke width"), _("Size of dots created with Ctrl+click (relative to current stroke width)"), false ); } -void StyleFromSelectionToTool(Glib::ustring const &prefs_path, StyleSwatch *swatch) +static void StyleFromSelectionToTool(Glib::ustring const &prefs_path, StyleSwatch *swatch) { SPDesktop *desktop = SP_ACTIVE_DESKTOP; if (desktop == NULL) @@ -305,7 +318,9 @@ void InkscapePreferences::initPageTools() //Selector this->AddPage(_page_selector, _("Selector"), iter_tools, PREFS_PAGE_TOOLS_SELECTOR); + AddSelcueCheckbox(_page_selector, "/tools/select", false); + AddGradientCheckbox(_page_selector, "/tools/select", false); _page_selector.add_group_header( _("When transforming, show")); _t_sel_trans_obj.init ( _("Objects"), "/tools/select/show", "content", true, 0); _page_selector.add_line( true, "", _t_sel_trans_obj, "", @@ -344,7 +359,7 @@ void InkscapePreferences::initPageTools() _t_node_pathflash_selected.init ( _("Show temporary outline for selected paths"), "/tools/nodes/pathflash_selected", false); _page_node.add_line( true, "", _t_node_pathflash_selected, "", _("Show temporary outline even when a path is selected for editing")); _t_node_pathflash_timeout.init("/tools/nodes/pathflash_timeout", 0, 10000.0, 100.0, 100.0, 1000.0, true, false); - _page_node.add_line( false, _("Flash time:"), _t_node_pathflash_timeout, "ms", _("Specifies how long the path outline will be visible after a mouse-over (in milliseconds); specify 0 to have the outline shown until mouse leaves the path"), false); + _page_node.add_line( false, _("_Flash time:"), _t_node_pathflash_timeout, "ms", _("Specifies how long the path outline will be visible after a mouse-over (in milliseconds); specify 0 to have the outline shown until mouse leaves the path"), false); _page_node.add_group_header(_("Editing preferences")); _t_node_single_node_transform_handles.init(_("Show transform handles for single nodes"), "/tools/nodes/single_node_transform_handles", false); _page_node.add_line( true, "", _t_node_single_node_transform_handles, "", _("Show transform handles even when only a single node is selected")); @@ -363,7 +378,7 @@ void InkscapePreferences::initPageTools() AddGradientCheckbox(_page_zoom, "/tools/zoom", false); //Measure - this->AddPage(_page_measure, C_("Measurement tool", "Measure"), iter_tools, PREFS_PAGE_TOOLS_MEASURE); + this->AddPage(_page_measure, C_("ContextVerb", "Measure"), iter_tools, PREFS_PAGE_TOOLS_MEASURE); PrefCheckButton* cb = Gtk::manage( new PrefCheckButton); cb->init ( _("Ignore first and last points"), "/tools/measure/ignore_1st_and_last", true); _page_measure.add_line( false, "", *cb, "", _("The start and end of the measurement tool's control line will not be considered for calculating lengths. Only lengths between actual curve intersections will be displayed.")); @@ -421,14 +436,28 @@ void InkscapePreferences::initPageTools() _("If on, each newly created object will be selected (deselecting previous selection)")); //Text - this->AddPage(_page_text, _("Text"), iter_tools, PREFS_PAGE_TOOLS_TEXT); + this->AddPage(_page_text, C_("ContextVerb", "Text"), iter_tools, PREFS_PAGE_TOOLS_TEXT); this->AddSelcueCheckbox(_page_text, "/tools/text", true); this->AddGradientCheckbox(_page_text, "/tools/text", true); { - PrefCheckButton* cb = Gtk::manage( new PrefCheckButton); - cb->init ( _("Show font samples in the drop-down list"), "/tools/text/show_sample_in_list", 1); - _page_text.add_line( false, "", *cb, "", _("Show font samples alongside font names in the drop-down list in Text bar")); + PrefCheckButton* cb = Gtk::manage( new PrefCheckButton); + cb->init ( _("Show font samples in the drop-down list"), "/tools/text/show_sample_in_list", 1); + _page_text.add_line( false, "", *cb, "", _("Show font samples alongside font names in the drop-down list in Text bar")); + + _font_dialog.init ( _("Show font substitution warning dialog"), "/options/font/substitutedlg", false); + _page_text.add_line( false, "", _font_dialog, "", _("Show font substitution warning dialog when requested fonts are not available on the system")); } + + Glib::ustring sizeLabels[] = {_("Pixel"), _("Point"), _("Pica"), _("Millimeter"), _("Centimeter"), _("Inch"), _("Em square")/*, _("Ex square"), _("Percent")*/}; + int sizeValues[] = {SP_CSS_UNIT_PX, SP_CSS_UNIT_PT, SP_CSS_UNIT_PC, SP_CSS_UNIT_MM, SP_CSS_UNIT_CM, SP_CSS_UNIT_IN, SP_CSS_UNIT_EM/*, SP_CSS_UNIT_EX, SP_CSS_UNIT_PERCENT*/}; + + _page_text.add_group_header( _("Text units")); + _font_unit_type.init( "/options/font/unitType", sizeLabels, sizeValues, G_N_ELEMENTS(sizeLabels), SP_CSS_UNIT_PT ); + _page_text.add_line( false, _("Text size unit type:"), _font_unit_type, "", + _("Set the type of unit used in the text toolbar and text dialogs"), false); + _font_output_px.init ( _("Always output text size in pixels (px)"), "/options/font/textOutputPx", true); + _page_text.add_line( false, "", _font_output_px, "", _("Always convert the text size units above into pixels (px) before saving to file")); + this->AddNewObjectsStyle(_page_text, "/tools/text"); //Spray @@ -451,6 +480,14 @@ void InkscapePreferences::initPageTools() _misc_forkvectors.init( _("Prevent sharing of gradient definitions"), "/options/forkgradientvectors/value", true); _page_gradient.add_line( false, "", _misc_forkvectors, "", _("When on, shared gradient definitions are automatically forked on change; uncheck to allow sharing of gradient definitions so that editing one object may affect other objects using the same gradient"), true); + _misc_gradienteditor.init( _("Use legacy Gradient Editor"), "/dialogs/gradienteditor/showlegacy", false); + _page_gradient.add_line( false, "", _misc_gradienteditor, "", + _("When on, the Gradient Edit button in the Fill & Stroke dialog will show the legacy Gradient Editor dialog, when off the Gradient Tool will be used"), true); + + _misc_gradientangle.init("/dialogs/gradienteditor/angle", -359, 359, 1, 90, 0, false, false); + _page_gradient.add_line( false, _("Linear gradient _angle:"), _misc_gradientangle, "", + _("Default angle of new linear gradients in degrees (clockwise from horizontal)"), false); + //Dropper this->AddPage(_page_dropper, _("Dropper"), iter_tools, PREFS_PAGE_TOOLS_DROPPER); @@ -475,8 +512,8 @@ void InkscapePreferences::initPageUI() _path_ui = _page_list.get_model()->get_path(iter_ui); Glib::ustring languages[] = {_("System default"), _("Albanian (sq)"), _("Amharic (am)"), _("Arabic (ar)"), _("Armenian (hy)"),_("Azerbaijani (az)"), _("Basque (eu)"), _("Belarusian (be)"), - _("Bulgarian (bg)"), _("Bengali (bn)"), _("Breton (br)"), _("Catalan (ca)"), _("Valencian Catalan (ca@valencia)"), _("Chinese/China (zh_CN)"), - _("Chinese/Taiwan (zh_TW)"), _("Croatian (hr)"), _("Czech (cs)"), + _("Bulgarian (bg)"), _("Bengali (bn)"), _("Bengali/Bangladesh (bn_BD)"), _("Breton (br)"), _("Catalan (ca)"), _("Valencian Catalan (ca@valencia)"), _("Chinese/China (zh_CN)"), + _("Chinese/Taiwan (zh_TW)"), _("Croatian (hr)"), _("Czech (cs)"), _("Danish (da)"), _("Dutch (nl)"), _("Dzongkha (dz)"), _("German (de)"), _("Greek (el)"), _("English (en)"), _("English/Australia (en_AU)"), _("English/Canada (en_CA)"), _("English/Great Britain (en_GB)"), _("Pig Latin (en_US@piglatin)"), _("Esperanto (eo)"), _("Estonian (et)"), _("Farsi (fa)"), _("Finnish (fi)"), @@ -486,7 +523,7 @@ void InkscapePreferences::initPageUI() _("Polish (pl)"), _("Portuguese (pt)"), _("Portuguese/Brazil (pt_BR)"), _("Romanian (ro)"), _("Russian (ru)"), _("Serbian (sr)"), _("Serbian in Latin script (sr@latin)"), _("Slovak (sk)"), _("Slovenian (sl)"), _("Spanish (es)"), _("Spanish/Mexico (es_MX)"), _("Swedish (sv)"),_("Telugu (te_IN)"), _("Thai (th)"), _("Turkish (tr)"), _("Ukrainian (uk)"), _("Vietnamese (vi)")}; - Glib::ustring langValues[] = {"", "sq", "am", "ar", "hy", "az", "eu", "be", "bg", "bn", "br", "ca", "ca@valencia", "zh_CN", "zh_TW", "hr", "cs", "da", "nl", + Glib::ustring langValues[] = {"", "sq", "am", "ar", "hy", "az", "eu", "be", "bg", "bn", "bn_BD", "br", "ca", "ca@valencia", "zh_CN", "zh_TW", "hr", "cs", "da", "nl", "dz", "de", "el", "en", "en_AU", "en_CA", "en_GB", "en_US@piglatin", "eo", "et", "fa", "fi", "fr", "ga", "gl", "he", "hu", "id", "it", "ja", "km", "rw", "ko", "lt", "lv", "mk", "mn", "ne", "nb", "nn", "pa", "pl", "pt", "pt_BR", "ro", "ru", "sr", "sr@latin", "sk", "sl", "es", "es_MX", "sv", "te_IN", "th", "tr", "uk", "vi" }; @@ -544,17 +581,14 @@ void InkscapePreferences::initPageUI() _misc_recent.init("/options/maxrecentdocuments/value", 0.0, 1000.0, 1.0, 1.0, 1.0, true, false); - Gtk::HBox* recent_hbox = Gtk::manage(new Gtk::HBox()); Gtk::Button* reset_recent = Gtk::manage(new Gtk::Button(_("Clear list"))); reset_recent->signal_clicked().connect(sigc::mem_fun(*this, &InkscapePreferences::on_reset_open_recent_clicked)); - recent_hbox->pack_start(_misc_recent, false, false); - recent_hbox->pack_start(*reset_recent, false, false); - _page_ui.add_line( false, _("Maximum documents in Open Recent:"), *recent_hbox, "", - _("Set the maximum length of the Open Recent list in the File menu, or clear the list"), false); + _page_ui.add_line( false, _("Maximum documents in Open _Recent:"), _misc_recent, "", + _("Set the maximum length of the Open Recent list in the File menu, or clear the list"), false, reset_recent); _ui_zoom_correction.init(300, 30, 1.00, 200.0, 1.0, 10.0, 1.0); - _page_ui.add_line( false, _("Zoom correction factor (in %):"), _ui_zoom_correction, "", + _page_ui.add_line( false, _("_Zoom correction factor (in %):"), _ui_zoom_correction, "", _("Adjust the slider until the length of the ruler on your screen matches its real length. This information is used when zooming to 1:1, 1:2, etc., to display objects in their true sizes"), true); @@ -563,10 +597,28 @@ void InkscapePreferences::initPageUI() _("When on, will allow dynamic layout of components that are not completely finished being refactored"), true); /* show infobox */ - _show_filters_info_box.init( _("Show filter primitives infobox"), "/options/showfiltersinfobox/value", true); + _show_filters_info_box.init( _("Show filter primitives infobox (requires restart)"), "/options/showfiltersinfobox/value", true); _page_ui.add_line(false, "", _show_filters_info_box, "", _("Show icons and descriptions for the filter primitives available at the filter effects dialog")); + { + Glib::ustring dockbarstyleLabels[] = {_("Icons only"), _("Text only"), _("Icons and text")}; + int dockbarstyleValues[] = {0, 1, 2}; + + /* dockbar style */ + _dockbar_style.init( "/options/dock/dockbarstyle", dockbarstyleLabels, dockbarstyleValues, G_N_ELEMENTS(dockbarstyleLabels), 0); + _page_ui.add_line(false, _("Dockbar style (requires restart):"), _dockbar_style, "", + _("Selects whether the vertical bars on the dockbar will show text labels, icons, or both"), false); + + Glib::ustring switcherstyleLabels[] = {_("Text only"), _("Icons only"), _("Icons and text")}; /* see bug #1098437 */ + int switcherstyleValues[] = {0, 1, 2}; + + /* switcher style */ + _switcher_style.init( "/options/dock/switcherstyle", switcherstyleLabels, switcherstyleValues, G_N_ELEMENTS(switcherstyleLabels), 0); + _page_ui.add_line(false, _("Switcher style (requires restart):"), _switcher_style, "", + _("Selects whether the dockbar switcher will show text labels, icons, or both"), false); + } + // Windows _win_save_geom.init ( _("Save and restore window geometry for each document"), "/options/savewindowgeometry/value", 1, true, 0); _win_save_geom_prefs.init ( _("Remember and use last window's geometry"), "/options/savewindowgeometry/value", 2, false, &_win_save_geom); @@ -578,16 +630,27 @@ void InkscapePreferences::initPageUI() _win_dockable.init ( _("Dockable"), "/options/dialogtype/value", 1, true, 0); _win_floating.init ( _("Floating"), "/options/dialogtype/value", 0, false, &_win_dockable); + _win_native.init ( _("Native open/save dialogs"), "/options/desktopintegration/value", 1, true, 0); _win_gtk.init ( _("GTK open/save dialogs"), "/options/desktopintegration/value", 0, false, &_win_native); _win_hide_task.init ( _("Dialogs are hidden in taskbar"), "/options/dialogsskiptaskbar/value", true); + _win_save_viewport.init ( _("Save and restore documents viewport"), "/options/savedocviewport/value", true); _win_zoom_resize.init ( _("Zoom when window is resized"), "/options/stickyzoom/value", false); _win_show_close.init ( _("Show close button on dialogs"), "/dialogs/showclose", false); _win_ontop_none.init ( _("None"), "/options/transientpolicy/value", 0, false, 0); _win_ontop_normal.init ( _("Normal"), "/options/transientpolicy/value", 1, true, &_win_ontop_none); _win_ontop_agressive.init ( _("Aggressive"), "/options/transientpolicy/value", 2, false, &_win_ontop_none); + { + Glib::ustring defaultSizeLabels[] = {_("Small"), _("Large"), _("Maximized")}; + int defaultSizeValues[] = {0, 1, 2}; + + _win_default_size.init( "/options/defaultwindowsize/value", defaultSizeLabels, defaultSizeValues, G_N_ELEMENTS(defaultSizeLabels), 1 ); + _page_windows.add_line( false, _("Default window size:"), _win_default_size, "", + _("Set the default window size"), false); + } + _page_windows.add_group_header( _("Saving window geometry (size and position)")); _page_windows.add_line( true, "", _win_save_geom_off, "", _("Let the window manager determine placement of all windows")); @@ -602,6 +665,8 @@ void InkscapePreferences::initPageUI() _page_windows.add_line( true, "", _win_save_dialog_pos_on, "", _("Save and restore dialogs status (the last open windows dialogs are saved when it closes)")); + + _page_windows.add_group_header( _("Dialog behavior (requires restart)")); _page_windows.add_line( true, "", _win_dockable, "", _("Dockable")); @@ -628,11 +693,12 @@ void InkscapePreferences::initPageUI() _page_windows.add_group_header( _("Dialog Transparency")); _win_trans_focus.init("/dialogs/transparency/on-focus", 0.5, 1.0, 0.01, 0.1, 1.0, false, false); - _page_windows.add_line( true, _("Opacity when focused:"), _win_trans_focus, "", ""); + _page_windows.add_line( true, _("_Opacity when focused:"), _win_trans_focus, "", "", false); _win_trans_blur.init("/dialogs/transparency/on-blur", 0.0, 1.0, 0.01, 0.1, 0.5, false, false); - _page_windows.add_line( true, _("Opacity when unfocused:"), _win_trans_blur, "", ""); + _page_windows.add_line( true, _("Opacity when _unfocused:"), _win_trans_blur, "", "", false); _win_trans_time.init("/dialogs/transparency/animate-time", 0, 1000, 10, 100, 100, true, false); - _page_windows.add_line( true, _("Time of opacity change animation:"), _win_trans_time, "ms", ""); + _page_windows.add_line( true, _("_Time of opacity change animation:"), _win_trans_time, "ms", "", false); + _page_windows.add_group_header( _("Miscellaneous")); #ifndef WIN32 // FIXME: Temporary Win32 special code to enable transient dialogs @@ -641,15 +707,19 @@ void InkscapePreferences::initPageUI() #endif _page_windows.add_line( true, "", _win_zoom_resize, "", _("Zoom drawing when document window is resized, to keep the same area visible (this is the default which can be changed in any window using the button above the right scrollbar)")); + _page_windows.add_line( true, "", _win_save_viewport, "", + _("Save documents viewport (zoom and panning position). Useful to turn off when sharing version controlled files.")); _page_windows.add_line( true, "", _win_show_close, "", _("Whether dialog windows have a close button (requires restart)")); this->AddPage(_page_windows, _("Windows"), iter_ui, PREFS_PAGE_UI_WINDOWS); // Grids - _page_grids.add_group_header( _("Major grid line emphasizing")); + _page_grids.add_group_header( _("Line color when zooming out")); - _grids_no_emphasize_on_zoom.init( _("Don't emphasize gridlines when zoomed out"), "/options/grids/no_emphasize_when_zoomedout", false); - _page_grids.add_line( true, "", _grids_no_emphasize_on_zoom, "", _("If set and zoomed out, the gridlines will be shown in normal color instead of major grid line color"), false); + _grids_no_emphasize_on_zoom.init( _("Minor grid line color"), "/options/grids/no_emphasize_when_zoomedout", 1, true, 0); + _page_grids.add_line( true, "", _grids_no_emphasize_on_zoom, "", _("The gridlines will be shown in minor grid line color"), false); + _grids_emphasize_on_zoom.init( _("Major grid line color"), "/options/grids/no_emphasize_when_zoomedout", 0, false, &_grids_no_emphasize_on_zoom); + _page_grids.add_line( true, "", _grids_emphasize_on_zoom, "", _("The gridlines will be shown in major grid line color"), false); _page_grids.add_group_header( _("Default grid settings")); @@ -671,8 +741,8 @@ void InkscapePreferences::initPageUI() _grids_xy.add_line( false, _("Spacing X:"), _grids_xy_spacing_x, "", _("Distance between vertical grid lines"), false); _grids_xy.add_line( false, _("Spacing Y:"), _grids_xy_spacing_y, "", _("Distance between horizontal grid lines"), false); - _grids_xy_color.init(_("Grid line color:"), "/options/grids/xy/color", 0x0000ff20); - _grids_xy.add_line( false, _("Grid line color:"), _grids_xy_color, "", _("Color used for normal grid lines"), false); + _grids_xy_color.init(_("Minor grid line color:"), "/options/grids/xy/color", 0x0000ff20); + _grids_xy.add_line( false, _("Minor grid line color:"), _grids_xy_color, "", _("Color used for normal grid lines"), false); _grids_xy_empcolor.init(_("Major grid line color:"), "/options/grids/xy/empcolor", 0x0000ff40); _grids_xy.add_line( false, _("Major grid line color:"), _grids_xy_empcolor, "", _("Color used for major (highlighted) grid lines"), false); _grids_xy_empspacing.init("/options/grids/xy/empspacing", 1.0, 1000.0, 1.0, 5.0, 5.0, true, false); @@ -696,14 +766,16 @@ void InkscapePreferences::initPageUI() _grids_axonom_angle_z.init("/options/grids/axonom/angle_z", -360.0, 360.0, 1.0, 10.0, 30.0, false, false); _grids_axonom.add_line( false, _("Angle X:"), _grids_axonom_angle_x, "", _("Angle of x-axis"), false); _grids_axonom.add_line( false, _("Angle Z:"), _grids_axonom_angle_z, "", _("Angle of z-axis"), false); - _grids_axonom_color.init(_("Grid line color:"), "/options/grids/axonom/color", 0x0000ff20); - _grids_axonom.add_line( false, _("Grid line color:"), _grids_axonom_color, "", _("Color used for normal grid lines"), false); + _grids_axonom_color.init(_("Minor grid line color:"), "/options/grids/axonom/color", 0x0000ff20); + _grids_axonom.add_line( false, _("Minor grid line color:"), _grids_axonom_color, "", _("Color used for normal grid lines"), false); _grids_axonom_empcolor.init(_("Major grid line color:"), "/options/grids/axonom/empcolor", 0x0000ff40); _grids_axonom.add_line( false, _("Major grid line color:"), _grids_axonom_empcolor, "", _("Color used for major (highlighted) grid lines"), false); _grids_axonom_empspacing.init("/options/grids/axonom/empspacing", 1.0, 1000.0, 1.0, 5.0, 5.0, true, false); _grids_axonom.add_line( false, _("Major grid line every:"), _grids_axonom_empspacing, "", "", false); this->AddPage(_page_grids, _("Grids"), iter_ui, PREFS_PAGE_UI_GRIDS); + + initKeyboardShortcuts(iter_ui); } #if defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2) @@ -735,10 +807,17 @@ static void proofComboChanged( Gtk::ComboBoxText* combo ) } static void gamutColorChanged( Gtk::ColorButton* btn ) { +#if WITH_GTKMM_3_0 + Gdk::RGBA rgba = btn->get_rgba(); + gushort r = rgba.get_red_u(); + gushort g = rgba.get_green_u(); + gushort b = rgba.get_blue_u(); +#else Gdk::Color color = btn->get_color(); gushort r = color.get_red(); gushort g = color.get_green(); gushort b = color.get_blue(); +#endif gchar* tmp = g_strdup_printf("#%02x%02x%02x", (r >> 8), (g >> 8), (b >> 8) ); @@ -761,17 +840,21 @@ void InkscapePreferences::initPageIO() _page_io.add_line( false, "", _misc_comment, "", _("When on, a comment will be added to the raw print output, marking the rendered output for an object with its label"), true); + _misc_default_metadata.init( _("Add default metadata to new documents"), "/metadata/addToNewFile", false); + _page_io.add_line( false, "", _misc_default_metadata, "", + _("Add default metadata to new documents. Default metadata can be set from Document Properties->Metadata."), true); + // Input devices options _mouse_sens.init ( "/options/cursortolerance/value", 0.0, 30.0, 1.0, 1.0, 8.0, true, false); - _page_mouse.add_line( false, _("Grab sensitivity:"), _mouse_sens, _("pixels"), + _page_mouse.add_line( false, _("_Grab sensitivity:"), _mouse_sens, _("pixels (requires restart)"), _("How close on the screen you need to be to an object to be able to grab it with mouse (in screen pixels)"), false); _mouse_thres.init ( "/options/dragtolerance/value", 0.0, 20.0, 1.0, 1.0, 4.0, true, false); - _page_mouse.add_line( false, _("Click/drag threshold:"), _mouse_thres, _("pixels"), + _page_mouse.add_line( false, _("_Click/drag threshold:"), _mouse_thres, _("pixels"), _("Maximum mouse drag (in screen pixels) which is considered a click, not a drag"), false); _mouse_grabsize.init("/options/grabsize/value", 1, 7, 1, 2, 3, 0); - _page_mouse.add_line(false, _("Handle size"), _mouse_grabsize, "", - _("Set the relative size of node handles."), true); + _page_mouse.add_line(false, _("_Handle size:"), _mouse_grabsize, "", + _("Set the relative size of node handles"), true); _mouse_use_ext_input.init( _("Use pressure-sensitive tablet (requires restart)"), "/options/useextinput/value", true); _page_mouse.add_line(false, "",_mouse_use_ext_input, "", @@ -792,12 +875,16 @@ void InkscapePreferences::initPageIO() _page_svgoutput.add_line( true, "", _svgoutput_inlineattrs, "", _("Put attributes on the same line as the element tag"), false); _svgoutput_indent.init("/options/svgoutput/indent", 0.0, 1000.0, 1.0, 2.0, 2.0, true, false); - _page_svgoutput.add_line( true, _("Indent, spaces:"), _svgoutput_indent, "", _("The number of spaces to use for indenting nested elements; set to 0 for no indentation"), false); + _page_svgoutput.add_line( true, _("_Indent, spaces:"), _svgoutput_indent, "", _("The number of spaces to use for indenting nested elements; set to 0 for no indentation"), false); _page_svgoutput.add_group_header( _("Path data")); - _svgoutput_allowrelativecoordinates.init( _("Allow relative coordinates"), "/options/svgoutput/allowrelativecoordinates", true); - _page_svgoutput.add_line( true, "", _svgoutput_allowrelativecoordinates, "", _("If set, relative coordinates may be used in path data"), false); + int const numPathstringFormat = 3; + Glib::ustring pathstringFormatLabels[numPathstringFormat] = {_("Absolute"), _("Relative"), _("Optimized")}; + int pathstringFormatValues[numPathstringFormat] = {0, 1, 2}; + + _svgoutput_pathformat.init("/options/svgoutput/pathstring_format", pathstringFormatLabels, pathstringFormatValues, numPathstringFormat, 2); + _page_svgoutput.add_line( true, _("Path string format:"), _svgoutput_pathformat, "", _("Path data should be written: only with absolute coordinates, only with relative coordinates, or optimized for string length (mixed absolute and relative coordinates)"), false); _svgoutput_forcerepeatcommands.init( _("Force repeat commands"), "/options/svgoutput/forcerepeatcommands", false); _page_svgoutput.add_line( true, "", _svgoutput_forcerepeatcommands, "", _("Force repeating of the same path command (for example, 'L 1,2 L 3,4' instead of 'L 1,2 3,4')"), false); @@ -805,10 +892,10 @@ void InkscapePreferences::initPageIO() _page_svgoutput.add_group_header( _("Numbers")); _svgoutput_numericprecision.init("/options/svgoutput/numericprecision", 1.0, 16.0, 1.0, 2.0, 8.0, true, false); - _page_svgoutput.add_line( true, _("Numeric precision:"), _svgoutput_numericprecision, "", _("Significant figures of the values written to the SVG file"), false); + _page_svgoutput.add_line( true, _("_Numeric precision:"), _svgoutput_numericprecision, "", _("Significant figures of the values written to the SVG file"), false); _svgoutput_minimumexponent.init("/options/svgoutput/minimumexponent", -32.0, -1, 1.0, 2.0, -8.0, true, false); - _page_svgoutput.add_line( true, _("Minimum exponent:"), _svgoutput_minimumexponent, "", _("The smallest number written to SVG is 10 to the power of this exponent; anything smaller is written as zero"), false); + _page_svgoutput.add_line( true, _("Minimum _exponent:"), _svgoutput_minimumexponent, "", _("The smallest number written to SVG is 10 to the power of this exponent; anything smaller is written as zero"), false); /* Code to add controls for attribute checking options */ @@ -899,8 +986,15 @@ void InkscapePreferences::initPageIO() _("Highlights colors that are out of gamut for the target device"), false); Glib::ustring colorStr = prefs->getString("/options/softproof/gamutcolor"); + +#if WITH_GTKMM_3_0 + Gdk::RGBA tmpColor( colorStr.empty() ? "#00ff00" : colorStr); + _cms_gamutcolor.set_rgba( tmpColor ); +#else Gdk::Color tmpColor( colorStr.empty() ? "#00ff00" : colorStr); _cms_gamutcolor.set_color( tmpColor ); +#endif + _page_cms.add_line( true, _("Out of gamut warning color:"), _cms_gamutcolor, "", _("Selects the color used for out of gamut warning"), false); @@ -938,18 +1032,10 @@ void InkscapePreferences::initPageIO() Glib::ustring current = prefs->getString( "/options/displayprofile/uri" ); gint index = 0; -#if WITH_GTKMM_2_24 _cms_display_profile.append(_("<none>")); -#else - _cms_display_profile.append_text(_("<none>")); -#endif index++; for ( std::vector<Glib::ustring>::iterator it = names.begin(); it != names.end(); ++it ) { -#if WITH_GTKMM_2_24 _cms_display_profile.append( *it ); -#else - _cms_display_profile.append_text( *it ); -#endif Glib::ustring path = CMSSystem::getPathForProfile(*it); if ( !path.empty() && path == current ) { _cms_display_profile.set_active(index); @@ -964,11 +1050,7 @@ void InkscapePreferences::initPageIO() current = prefs->getString("/options/softproof/uri"); index = 0; for ( std::vector<Glib::ustring>::iterator it = names.begin(); it != names.end(); ++it ) { -#if WITH_GTKMM_2_24 _cms_proof_profile.append( *it ); -#else - _cms_proof_profile.append_text( *it ); -#endif Glib::ustring path = CMSSystem::getPathForProfile(*it); if ( !path.empty() && path == current ) { _cms_proof_profile.set_active(index); @@ -1000,12 +1082,16 @@ void InkscapePreferences::initPageIO() // Autosave options _save_autosave_enable.init( _("Enable autosave (requires restart)"), "/options/autosave/enable", false); _page_autosave.add_line(false, "", _save_autosave_enable, "", _("Automatically save the current document(s) at a given interval, thus minimizing loss in case of a crash"), false); - _save_autosave_interval.init("/options/autosave/interval", 1.0, 10800.0, 1.0, 10.0, 10.0, true, false); - _page_autosave.add_line(false, _("Interval (in minutes):"), _save_autosave_interval, "", _("Interval (in minutes) at which document will be autosaved"), false); _save_autosave_path.init("/options/autosave/path", true); - _page_autosave.add_line(false, C_("Filesystem", "Path:"), _save_autosave_path, "", _("The directory where autosaves will be written"), false); + if (prefs->getString("/options/autosave/path").empty()) { + // Show the default fallback "tmp dir" if autosave path is not set. + _save_autosave_path.set_text(Glib::get_tmp_dir()); + } + _page_autosave.add_line(false, C_("Filesystem", "Autosave _directory:"), _save_autosave_path, "", _("The directory where autosaves will be written. This should be an absolute path (starts with / on UNIX or a drive letter such as C: on Windows). "), false); + _save_autosave_interval.init("/options/autosave/interval", 1.0, 10800.0, 1.0, 10.0, 10.0, true, false); + _page_autosave.add_line(false, _("_Interval (in minutes):"), _save_autosave_interval, "", _("Interval (in minutes) at which document will be autosaved"), false); _save_autosave_max.init("/options/autosave/max", 1.0, 100.0, 1.0, 10.0, 10.0, true, false); - _page_autosave.add_line(false, _("Maximum number of autosaves:"), _save_autosave_max, "", _("Maximum number of autosaved files; use this to limit the storage space used"), false); + _page_autosave.add_line(false, _("_Maximum number of autosaves:"), _save_autosave_max, "", _("Maximum number of autosaved files; use this to limit the storage space used"), false); /* When changing the interval or enabling/disabling the autosave function, * update our running configuration @@ -1024,13 +1110,13 @@ void InkscapePreferences::initPageIO() // Open Clip Art options _importexport_ocal_url.init("/options/ocalurl/str", true, g_strdup_printf("openclipart.org")); - _page_openclipart.add_line( false, _("Open Clip Art Library Server Name:"), _importexport_ocal_url, "", + _page_openclipart.add_line( false, _("Open Clip Art Library _Server Name:"), _importexport_ocal_url, "", _("The server name of the Open Clip Art Library webdav server; it's used by the Import and Export to OCAL function"), true); _importexport_ocal_username.init("/options/ocalusername/str", true); - _page_openclipart.add_line( false, _("Open Clip Art Library Username:"), _importexport_ocal_username, "", + _page_openclipart.add_line( false, _("Open Clip Art Library _Username:"), _importexport_ocal_username, "", _("The username used to log into Open Clip Art Library"), true); _importexport_ocal_password.init("/options/ocalpassword/str", false); - _page_openclipart.add_line( false, _("Open Clip Art Library Password:"), _importexport_ocal_password, "", + _page_openclipart.add_line( false, _("Open Clip Art Library _Password:"), _importexport_ocal_password, "", _("The password used to log into Open Clip Art Library"), true); this->AddPage(_page_openclipart, _("Open Clip Art"), iter_io, PREFS_PAGE_IO_OPENCLIPART); } @@ -1041,9 +1127,13 @@ void InkscapePreferences::initPageBehavior() _path_behavior = _page_list.get_model()->get_path(iter_behavior); _misc_simpl.init("/options/simplifythreshold/value", 0.0001, 1.0, 0.0001, 0.0010, 0.0010, false, false); - _page_behavior.add_line( false, _("Simplification threshold:"), _misc_simpl, "", + _page_behavior.add_line( false, _("_Simplification threshold:"), _misc_simpl, "", _("How strong is the Node tool's Simplify command by default. If you invoke this command several times in quick succession, it will act more and more aggressively; invoking it again after a pause restores the default threshold."), false); - + + _markers_color_stock.init ( _("Color stock markers the same color as object"), "/options/markers/colorStockMarkers", true); + _markers_color_custom.init ( _("Color custom markers the same color as object"), "/options/markers/colorCustomMarkers", false); + _markers_color_update.init ( _("Update marker color when object color changes"), "/options/markers/colorUpdateMarkers", true); + // Selecting options _sel_all.init ( _("Select in all layers"), "/options/kbselection/inlayer", PREFS_SELECTION_ALL, false, 0); _sel_current.init ( _("Select only within current layer"), "/options/kbselection/inlayer", PREFS_SELECTION_LAYER, true, &_sel_all); @@ -1052,6 +1142,9 @@ void InkscapePreferences::initPageBehavior() _sel_locked.init ( _("Ignore locked objects and layers"), "/options/kbselection/onlysensitive", true); _sel_layer_deselects.init ( _("Deselect upon layer change"), "/options/selection/layerdeselect", true); + _page_select.add_line( false, "", _sel_layer_deselects, "", + _("Uncheck this to be able to keep the current objects selected when the current layer changes")); + _page_select.add_group_header( _("Ctrl+A, Tab, Shift+Tab")); _page_select.add_line( true, "", _sel_all, "", _("Make keyboard selection commands work on objects in all layers")); @@ -1064,8 +1157,11 @@ void InkscapePreferences::initPageBehavior() _page_select.add_line( true, "", _sel_locked, "", _("Uncheck this to be able to select objects that are locked (either by themselves or by being in a locked layer)")); - _page_select.add_line( false, "", _sel_layer_deselects, "", - _("Uncheck this to be able to keep the current objects selected when the current layer changes")); + _sel_cycle.init ( _("Wrap when cycling objects in z-order"), "/options/selection/cycleWrap", true); + + _page_select.add_group_header( _("Alt+Scroll Wheel")); + _page_select.add_line( true, "", _sel_cycle, "", + _("Wrap around at start and end when cycling objects in z-order")); this->AddPage(_page_select, _("Selecting"), iter_behavior, PREFS_PAGE_BEHAVIOR_SELECTING); @@ -1095,25 +1191,27 @@ void InkscapePreferences::initPageBehavior() // Scrolling options _scroll_wheel.init ( "/options/wheelscroll/value", 0.0, 1000.0, 1.0, 1.0, 40.0, true, false); - _page_scrolling.add_line( false, _("Mouse wheel scrolls by:"), _scroll_wheel, _("pixels"), + _page_scrolling.add_line( false, _("Mouse _wheel scrolls by:"), _scroll_wheel, _("pixels"), _("One mouse wheel notch scrolls by this distance in screen pixels (horizontally with Shift)"), false); _page_scrolling.add_group_header( _("Ctrl+arrows")); _scroll_arrow_px.init ( "/options/keyscroll/value", 0.0, 1000.0, 1.0, 1.0, 10.0, true, false); - _page_scrolling.add_line( true, _("Scroll by:"), _scroll_arrow_px, _("pixels"), + _page_scrolling.add_line( true, _("Sc_roll by:"), _scroll_arrow_px, _("pixels"), _("Pressing Ctrl+arrow key scrolls by this distance (in screen pixels)"), false); _scroll_arrow_acc.init ( "/options/scrollingacceleration/value", 0.0, 5.0, 0.01, 1.0, 0.35, false, false); - _page_scrolling.add_line( true, _("Acceleration:"), _scroll_arrow_acc, "", + _page_scrolling.add_line( true, _("_Acceleration:"), _scroll_arrow_acc, "", _("Pressing and holding Ctrl+arrow will gradually speed up scrolling (0 for no acceleration)"), false); _page_scrolling.add_group_header( _("Autoscrolling")); _scroll_auto_speed.init ( "/options/autoscrollspeed/value", 0.0, 5.0, 0.01, 1.0, 0.7, false, false); - _page_scrolling.add_line( true, _("Speed:"), _scroll_auto_speed, "", + _page_scrolling.add_line( true, _("_Speed:"), _scroll_auto_speed, "", _("How fast the canvas autoscrolls when you drag beyond canvas edge (0 to turn autoscroll off)"), false); _scroll_auto_thres.init ( "/options/autoscrolldistance/value", -600.0, 600.0, 1.0, 1.0, -10.0, true, false); - _page_scrolling.add_line( true, _("Threshold:"), _scroll_auto_thres, _("pixels"), + _page_scrolling.add_line( true, _("_Threshold:"), _scroll_auto_thres, _("pixels"), _("How far (in screen pixels) you need to be from the canvas edge to trigger autoscroll; positive is outside the canvas, negative is within the canvas"), false); +/* _scroll_space.init ( _("Left mouse button pans when Space is pressed"), "/options/spacepans/value", false); _page_scrolling.add_line( false, "", _scroll_space, "", _("When on, pressing and holding Space and dragging with left mouse button pans canvas (as in Adobe Illustrator); when off, Space temporarily switches to Selector tool (default)")); +*/ _wheel_zoom.init ( _("Mouse wheel zooms by default"), "/options/wheelzooms/value", false); _page_scrolling.add_line( false, "", _wheel_zoom, "", _("When on, mouse wheel zooms without Ctrl and scrolls canvas with Ctrl; when off, it zooms with Ctrl and scrolls without Ctrl")); @@ -1125,7 +1223,7 @@ void InkscapePreferences::initPageBehavior() _("After snapping, a symbol is drawn at the point that has snapped")); _snap_delay.init("/options/snapdelay/value", 0, 1000, 50, 100, 300, 0); - _page_snapping.add_line( false, _("Delay (in ms):"), _snap_delay, "", + _page_snapping.add_line( false, _("_Delay (in ms):"), _snap_delay, "", _("Postpone snapping as long as the mouse is moving, and then wait an additional fraction of a second. This additional delay is specified here. When set to zero or to a very small number, snapping will be immediate."), true); _snap_closest_only.init( _("Only snap the node closest to the pointer"), "/options/snapclosestonly/value", false); @@ -1133,7 +1231,7 @@ void InkscapePreferences::initPageBehavior() _("Only try to snap the node that is initially closest to the mouse pointer")); _snap_weight.init("/options/snapweight/value", 0, 1, 0.1, 0.2, 0.5, 1); - _page_snapping.add_line( false, _("Weight factor:"), _snap_weight, "", + _page_snapping.add_line( false, _("_Weight factor:"), _snap_weight, "", _("When multiple snap solutions are found, then Inkscape can either prefer the closest transformation (when set to 0), or prefer the node that was initially the closest to the pointer (when set to 1)"), true); _snap_mouse_pointer.init( _("Snap the mouse pointer when dragging a constrained knot"), "/options/snapmousepointer/value", false); @@ -1145,14 +1243,14 @@ void InkscapePreferences::initPageBehavior() // Steps options _steps_arrow.init ( "/options/nudgedistance/value", 0.0, 1000.0, 0.01, 2.0, UNIT_TYPE_LINEAR, "px"); //nudgedistance is limited to 1000 in select-context.cpp: use the same limit here - _page_steps.add_line( false, _("Arrow keys move by:"), _steps_arrow, "", + _page_steps.add_line( false, _("_Arrow keys move by:"), _steps_arrow, "", _("Pressing an arrow key moves selected object(s) or node(s) by this distance"), false); _steps_scale.init ( "/options/defaultscale/value", 0.0, 1000.0, 0.01, 2.0, UNIT_TYPE_LINEAR, "px"); //defaultscale is limited to 1000 in select-context.cpp: use the same limit here - _page_steps.add_line( false, _("> and < scale by:"), _steps_scale, "", + _page_steps.add_line( false, _("> and < _scale by:"), _steps_scale, "", _("Pressing > or < scales selection up or down by this increment"), false); _steps_inset.init ( "/options/defaultoffsetwidth/value", 0.0, 3000.0, 0.01, 2.0, UNIT_TYPE_LINEAR, "px"); - _page_steps.add_line( false, _("Inset/Outset by:"), _steps_inset, "", + _page_steps.add_line( false, _("_Inset/Outset by:"), _steps_inset, "", _("Inset and Outset commands displace the path by this distance"), false); _steps_compass.init ( _("Compass-like display of angles"), "/options/compassangledisplay/value", true); _page_steps.add_line( false, "", _steps_compass, "", @@ -1162,13 +1260,13 @@ void InkscapePreferences::initPageBehavior() int values[num_items] = {2, 3, 4, 5, 6, 8, 10, 12, 15, 18, 24, 30, 60, 90, 180, 360, 0}; _steps_rot_snap.set_size_request(_sb_width); _steps_rot_snap.init("/options/rotationsnapsperpi/value", labels, values, num_items, 12); - _page_steps.add_line( false, _("Rotation snaps every:"), _steps_rot_snap, _("degrees"), + _page_steps.add_line( false, _("_Rotation snaps every:"), _steps_rot_snap, _("degrees"), _("Rotating with Ctrl pressed snaps every that much degrees; also, pressing [ or ] rotates by this amount"), false); _steps_rot_relative.init ( _("Relative snapping of guideline angles"), "/options/relativeguiderotationsnap/value", false); _page_steps.add_line( false, "", _steps_rot_relative, "", _("When on, the snap angles when rotating a guideline will be relative to the original angle")); _steps_zoom.init ( "/options/zoomincrement/value", 101.0, 500.0, 1.0, 1.0, 1.414213562, true, true); - _page_steps.add_line( false, _("Zoom in/out by:"), _steps_zoom, _("%"), + _page_steps.add_line( false, _("_Zoom in/out by:"), _steps_zoom, _("%"), _("Zoom tool click, +/- keys, and middle click zoom in and out by this multiplier"), false); this->AddPage(_page_steps, _("Steps"), iter_behavior, PREFS_PAGE_BEHAVIOR_STEPS); @@ -1217,7 +1315,7 @@ void InkscapePreferences::initPageBehavior() _page_mask.add_group_header( _("Before applying")); _mask_grouping_none.init( _("Do not group clipped/masked objects"), "/options/maskobject/grouping", PREFS_MASKOBJECT_GROUPING_NONE, true, 0); - _mask_grouping_separate.init( _("Enclose every clipped/masked object in its own group"), "/options/maskobject/grouping", PREFS_MASKOBJECT_GROUPING_SEPARATE, false, &_mask_grouping_none); + _mask_grouping_separate.init( _("Put every clipped/masked object in its own group"), "/options/maskobject/grouping", PREFS_MASKOBJECT_GROUPING_SEPARATE, false, &_mask_grouping_none); _mask_grouping_all.init( _("Put all clipped/masked objects into one group"), "/options/maskobject/grouping", PREFS_MASKOBJECT_GROUPING_ALL, false, &_mask_grouping_none); _page_mask.add_line(true, "", _mask_grouping_none, "", @@ -1236,6 +1334,24 @@ void InkscapePreferences::initPageBehavior() _("Ungroup groups created when setting clip/mask")); this->AddPage(_page_mask, _("Clippaths and masks"), iter_behavior, PREFS_PAGE_BEHAVIOR_MASKS); + + + _page_markers.add_group_header( _("Stroke Style Markers")); + _page_markers.add_line( true, "", _markers_color_stock, "", + _("Stroke color same as object, fill color either object fill color or marker fill color")); + _page_markers.add_line( true, "", _markers_color_custom, "", + _("Stroke color same as object, fill color either object fill color or marker fill color")); + _page_markers.add_line( true, "", _markers_color_update, "", + _("Update marker color when object color changes")); + + this->AddPage(_page_markers, _("Markers"), iter_behavior, PREFS_PAGE_BEHAVIOR_MARKERS); + + + _page_cleanup.add_group_header( _("Document cleanup")); + _cleanup_swatches.init ( _("Remove unused swatches when doing a document cleanup"), "/options/cleanupswatches/value", false); // text label + _page_cleanup.add_line( true, "", _cleanup_swatches, "", + _("Remove unused swatches when doing a document cleanup")); // tooltip + this->AddPage(_page_cleanup, _("Cleanup"), iter_behavior, PREFS_PAGE_BEHAVIOR_CLEANUP); } void InkscapePreferences::initPageRendering() @@ -1243,12 +1359,12 @@ void InkscapePreferences::initPageRendering() /* threaded blur */ //related comments/widgets/functions should be renamed and option should be moved elsewhere when inkscape is fully multi-threaded _filter_multi_threaded.init("/options/threading/numthreads", 1.0, 8.0, 1.0, 2.0, 4.0, true, false); - _page_rendering.add_line( false, _("Number of Threads:"), _filter_multi_threaded, _("(requires restart)"), + _page_rendering.add_line( false, _("Number of _Threads:"), _filter_multi_threaded, _("(requires restart)"), _("Configure number of processors/threads to use when rendering filters"), false); // rendering cache _rendering_cache_size.init("/options/renderingcache/size", 0.0, 4096.0, 1.0, 32.0, 64.0, true, false); - _page_rendering.add_line( false, _("Rendering cache size:"), _rendering_cache_size, C_("mebibyte (2^20 bytes) abbreviation","MiB"), _("Set the amount of memory per document which can be used to store rendered parts of the drawing for later reuse; set to zero to disable caching"), false); + _page_rendering.add_line( false, _("Rendering _cache size:"), _rendering_cache_size, C_("mebibyte (2^20 bytes) abbreviation","MiB"), _("Set the amount of memory per document which can be used to store rendered parts of the drawing for later reuse; set to zero to disable caching"), false); /* blur quality */ _blur_quality_best.init ( _("Best quality (slowest)"), "/options/blurquality/value", @@ -1303,35 +1419,382 @@ void InkscapePreferences::initPageRendering() void InkscapePreferences::initPageBitmaps() { - { - Glib::ustring labels[] = {_("None"), _("2x2"), _("4x4"), _("8x8"), _("16x16")}; - int values[] = {0, 1, 2, 3, 4}; - _misc_overs_bitmap.set_size_request(_sb_width); - _misc_overs_bitmap.init("/options/bitmapoversample/value", labels, values, G_N_ELEMENTS(values), 1); - _page_bitmaps.add_line( false, _("Oversample bitmaps:"), _misc_overs_bitmap, "", "", false); - } - + /* Note: /options/bitmapoversample removed with Cairo renderer */ + _page_bitmaps.add_group_header( _("Edit")); _misc_bitmap_autoreload.init(_("Automatically reload bitmaps"), "/options/bitmapautoreload/value", true); _page_bitmaps.add_line( false, "", _misc_bitmap_autoreload, "", _("Automatically reload linked images when file is changed on disk")); _misc_bitmap_editor.init("/options/bitmapeditor/value", true); - _page_bitmaps.add_line( false, _("Bitmap editor:"), _misc_bitmap_editor, "", "", true); - _importexport_export.init("/dialogs/export/defaultxdpi/value", 0.0, 6000.0, 1.0, 1.0, PX_PER_IN, true, false); - _page_bitmaps.add_line( false, _("Default export resolution:"), _importexport_export, _("dpi"), + _page_bitmaps.add_line( false, _("_Bitmap editor:"), _misc_bitmap_editor, "", "", true); + + _page_bitmaps.add_group_header( _("Export")); + _importexport_export_res.init("/dialogs/export/defaultxdpi/value", 0.0, 6000.0, 1.0, 1.0, Inkscape::Util::Quantity::convert(1, "in", "px"), true, false); + _page_bitmaps.add_line( false, _("Default export _resolution:"), _importexport_export_res, _("dpi"), _("Default bitmap resolution (in dots per inch) in the Export dialog"), false); - _bitmap_copy_res.init("/options/createbitmap/resolution", 1.0, 6000.0, 1.0, 1.0, PX_PER_IN, true, false); - _page_bitmaps.add_line( false, _("Resolution for Create Bitmap Copy:"), _bitmap_copy_res, _("dpi"), + _page_bitmaps.add_group_header( _("Create")); + _bitmap_copy_res.init("/options/createbitmap/resolution", 1.0, 6000.0, 1.0, 1.0, Inkscape::Util::Quantity::convert(1, "in", "px"), true, false); + _page_bitmaps.add_line( false, _("Resolution for Create Bitmap _Copy:"), _bitmap_copy_res, _("dpi"), _("Resolution used by the Create Bitmap Copy command"), false); + + _page_bitmaps.add_group_header( _("Import")); + _bitmap_ask.init(_("Ask about linking and scaling when importing"), "/dialogs/import/ask", true); + _page_bitmaps.add_line( true, "", _bitmap_ask, "", + _("Pop-up linking and scaling dialog when importing bitmap image.")); + + { + Glib::ustring labels[] = {_("Embed"), _("Link")}; + Glib::ustring values[] = {"embed", "link"}; + _bitmap_link.init("/dialogs/import/link", labels, values, G_N_ELEMENTS(values), "link"); + _page_bitmaps.add_line( false, _("Bitmap link:"), _bitmap_link, "", "", false); + } + { - Glib::ustring labels[] = {_("Always embed"), _("Always link"), _("Ask")}; - Glib::ustring values[] = {"embed", "link", "ask"}; - _bitmap_import.init("/dialogs/import/link", labels, values, G_N_ELEMENTS(values), "ask"); - _page_bitmaps.add_line( false, _("Bitmap import:"), _bitmap_import, "", "", false); + Glib::ustring labels[] = {_("None (auto)"), _("Smooth (optimizeQuality)"), _("Blocky (optimizeSpeed)") }; + Glib::ustring values[] = {"auto", "optimizeQuality", "optimizeSpeed"}; + _bitmap_scale.init("/dialogs/import/scale", labels, values, G_N_ELEMENTS(values), "scale"); + _page_bitmaps.add_line( false, _("Bitmap scale (image-rendering):"), _bitmap_scale, "", "", false); } + /* Note: /dialogs/import/quality removed use of in r12542 */ + _importexport_import_res.init("/dialogs/import/defaultxdpi/value", 0.0, 6000.0, 1.0, 1.0, Inkscape::Util::Quantity::convert(1, "in", "px"), true, false); + _page_bitmaps.add_line( false, _("Default _import resolution:"), _importexport_import_res, _("dpi"), + _("Default bitmap resolution (in dots per inch) for bitmap import"), false); + _importexport_import_res_override.init(_("Override file resolution"), "/dialogs/import/forcexdpi", false); + _page_bitmaps.add_line( false, "", _importexport_import_res_override, "", + _("Use default bitmap resolution in favor of information from file")); + this->AddPage(_page_bitmaps, _("Bitmaps"), PREFS_PAGE_BITMAPS); } +void InkscapePreferences::initKeyboardShortcuts(Gtk::TreeModel::iterator iter_ui) +{ + std::vector<Glib::ustring> fileNames; + std::vector<Glib::ustring> fileLabels; + + sp_shortcut_get_file_names(&fileLabels, &fileNames); + + _kb_filelist.init( "/options/kbshortcuts/shortcutfile", &fileLabels[0], &fileNames[0], fileLabels.size(), fileNames[0]); + + Glib::ustring tooltip(_("Select a file of predefined shortcuts to use. Any customized shortcuts you create will be added seperately to ")); + tooltip += Glib::ustring(IO::Resource::get_path(IO::Resource::USER, IO::Resource::KEYS, "default.xml")); + + _page_keyshortcuts.add_line( false, _("Shortcut file:"), _kb_filelist, "", tooltip.c_str(), false); + + _kb_search.init("/options/kbshortcuts/value", true); + _page_keyshortcuts.add_line( false, _("Search:"), _kb_search, "", "", true); + + _kb_store = Gtk::TreeStore::create( _kb_columns ); + _kb_store->set_sort_column (_kb_columns.id, Gtk::SORT_ASCENDING ); + + _kb_filter = Gtk::TreeModelFilter::create(_kb_store); + _kb_filter->set_visible_func (sigc::mem_fun(*this, &InkscapePreferences::onKBSearchFilter)); + + _kb_shortcut_renderer.property_editable() = true; + + _kb_tree.set_model(_kb_filter); + _kb_tree.append_column(_("Name"), _kb_columns.name); + _kb_tree.append_column(_("Shortcut"), _kb_shortcut_renderer); + _kb_tree.append_column(_("Description"), _kb_columns.description); + _kb_tree.append_column(_("ID"), _kb_columns.id); + + _kb_tree.set_expander_column(*_kb_tree.get_column(0)); + + _kb_tree.get_column(0)->set_resizable(true); + _kb_tree.get_column(0)->set_clickable(true); + _kb_tree.get_column(0)->set_fixed_width (200); + + _kb_tree.get_column(1)->set_resizable(true); + _kb_tree.get_column(1)->set_clickable(true); + _kb_tree.get_column(1)->set_fixed_width (150); + //_kb_tree.get_column(1)->add_attribute(_kb_shortcut_renderer.property_text(), _kb_columns.shortcut); + _kb_tree.get_column(1)->set_cell_data_func(_kb_shortcut_renderer, sigc::ptr_fun(InkscapePreferences::onKBShortcutRenderer)); + + _kb_tree.get_column(2)->set_resizable(true); + _kb_tree.get_column(2)->set_clickable(true); + + _kb_tree.get_column(3)->set_resizable(true); + _kb_tree.get_column(3)->set_clickable(true); + + _kb_shortcut_renderer.signal_accel_edited().connect( sigc::mem_fun(*this, &InkscapePreferences::onKBTreeEdited) ); + _kb_shortcut_renderer.signal_accel_cleared().connect( sigc::mem_fun(*this, &InkscapePreferences::onKBTreeCleared) ); + + Gtk::ScrolledWindow* scroller = new Gtk::ScrolledWindow(); + scroller->add(_kb_tree); + + int row = 3; + +#if WITH_GTKMM_3_0 + scroller->set_hexpand(); + scroller->set_vexpand(); + _page_keyshortcuts.attach(*scroller, 0, row, 2, 1); +#else + _page_keyshortcuts.attach(*scroller, 0, 2, row, row+1, Gtk::EXPAND | Gtk::FILL, Gtk::EXPAND | Gtk::FILL); +#endif + + row++; + +#if WITH_GTKMM_3_0 + Gtk::ButtonBox *box_buttons = manage(new Gtk::ButtonBox); +#else + Gtk::HButtonBox *box_buttons = manage (new Gtk::HButtonBox); +#endif + + box_buttons->set_layout(Gtk::BUTTONBOX_END); + box_buttons->set_spacing(4); + +#if WITH_GTKMM_3_0 + box_buttons->set_hexpand(); + _page_keyshortcuts.attach(*box_buttons, 0, row, 3, 1); +#else + _page_keyshortcuts.attach(*box_buttons, 0, 3, row, row+1, Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK); +#endif + + UI::Widget::Button *kb_reset = manage(new UI::Widget::Button(_("Reset"), _("Remove all your customized keyboard shortcuts, and revert to the shortcuts in the shortcut file listed above"))); + box_buttons->pack_start(*kb_reset, true, true, 6); + box_buttons->set_child_secondary(*kb_reset); + + UI::Widget::Button *kb_import = manage(new UI::Widget::Button(_("Import ..."), _("Import custom keyboard shortcuts from a file"))); + box_buttons->pack_end(*kb_import, true, true, 6); + + UI::Widget::Button *kb_export = manage(new UI::Widget::Button(_("Export ..."), _("Export custom keyboard shortcuts to a file"))); + box_buttons->pack_end(*kb_export, true, true, 6); + + kb_reset->signal_clicked().connect( sigc::mem_fun(*this, &InkscapePreferences::onKBReset) ); + kb_import->signal_clicked().connect( sigc::mem_fun(*this, &InkscapePreferences::onKBImport) ); + kb_export->signal_clicked().connect( sigc::mem_fun(*this, &InkscapePreferences::onKBExport) ); + _kb_search.signal_key_release_event().connect( sigc::mem_fun(*this, &InkscapePreferences::onKBSearchKeyEvent) ); + _kb_filelist.signal_changed().connect( sigc::mem_fun(*this, &InkscapePreferences::onKBList) ); + _page_keyshortcuts.signal_realize().connect( sigc::mem_fun(*this, &InkscapePreferences::onKBRealize) ); + + this->AddPage(_page_keyshortcuts, _("Keyboard Shortcuts"), iter_ui, PREFS_PAGE_UI_KEYBOARD_SHORTCUTS); + + _kb_shortcuts_loaded = false; + Gtk::TreeStore::iterator iter_group = _kb_store->append(); + (*iter_group)[_kb_columns.name] = "Loading ..."; + (*iter_group)[_kb_columns.shortcut] = ""; + (*iter_group)[_kb_columns.id] = ""; + (*iter_group)[_kb_columns.description] = ""; + (*iter_group)[_kb_columns.shortcutid] = 0; + (*iter_group)[_kb_columns.user_set] = 0; + +} + +void InkscapePreferences::onKBList() +{ + sp_shortcut_init(); + onKBListKeyboardShortcuts(); +} + +void InkscapePreferences::onKBReset() +{ + sp_shortcuts_delete_all_from_file(); + sp_shortcut_init(); + onKBListKeyboardShortcuts(); +} + +void InkscapePreferences::onKBImport() +{ + if (sp_shortcut_file_import()) { + onKBListKeyboardShortcuts(); + } +} + +void InkscapePreferences::onKBExport() +{ + sp_shortcut_file_export(); +} + +bool InkscapePreferences::onKBSearchKeyEvent(GdkEventKey * /*event*/) +{ + _kb_filter->refilter(); + return FALSE; +} + +void InkscapePreferences::onKBTreeCleared(const Glib::ustring& path) +{ + Gtk::TreeModel::iterator iter = _kb_filter->get_iter(path); + Glib::ustring id = (*iter)[_kb_columns.id]; + unsigned int const current_shortcut_id = (*iter)[_kb_columns.shortcutid]; + + // Remove current shortcut from file + sp_shortcut_delete_from_file(id.c_str(), current_shortcut_id); + + sp_shortcut_init(); + onKBListKeyboardShortcuts(); + +} + +void InkscapePreferences::onKBTreeEdited (const Glib::ustring& path, guint accel_key, Gdk::ModifierType accel_mods, guint hardware_keycode) +{ + Gtk::TreeModel::iterator iter = _kb_filter->get_iter(path); + + Glib::ustring id = (*iter)[_kb_columns.id]; + Glib::ustring current_shortcut = (*iter)[_kb_columns.shortcut]; + unsigned int const current_shortcut_id = (*iter)[_kb_columns.shortcutid]; + + Inkscape::Verb *const verb = Inkscape::Verb::getbyid(id.c_str()); + if (!verb) { + return; + } + + unsigned int const new_shortcut_id = sp_gdkmodifier_to_shortcut(accel_key, accel_mods, hardware_keycode); + if (new_shortcut_id) { + + // Delete current shortcut if it existed + sp_shortcut_delete_from_file(id.c_str(), current_shortcut_id); + // Delete any references to the new shortcut + sp_shortcut_delete_from_file(id.c_str(), new_shortcut_id); + // Add the new shortcut + sp_shortcut_add_to_file(id.c_str(), new_shortcut_id); + + sp_shortcut_init(); + onKBListKeyboardShortcuts(); + } +} + +bool InkscapePreferences::onKBSearchFilter(const Gtk::TreeModel::const_iterator& iter) +{ + Glib::ustring search = _kb_search.get_text().lowercase(); + if (search.empty()) { + return TRUE; + } + + Glib::ustring name = (*iter)[_kb_columns.name]; + Glib::ustring desc = (*iter)[_kb_columns.description]; + Glib::ustring shortcut = (*iter)[_kb_columns.shortcut]; + Glib::ustring id = (*iter)[_kb_columns.id]; + + if (id.empty()) { + return TRUE; // Keep all group nodes visible + } + + return (name.lowercase().find(search) != name.npos + || shortcut.lowercase().find(search) != name.npos + || desc.lowercase().find(search) != name.npos + || id.lowercase().find(search) != name.npos); +} + +void InkscapePreferences::onKBRealize() +{ + if (!_kb_shortcuts_loaded /*&& _current_page == &_page_keyshortcuts*/) { + _kb_shortcuts_loaded = true; + onKBListKeyboardShortcuts(); + } +} + +InkscapePreferences::ModelColumns &InkscapePreferences::onKBGetCols() +{ + static InkscapePreferences::ModelColumns cols; + return cols; +} + +void InkscapePreferences::onKBShortcutRenderer(Gtk::CellRenderer *renderer, Gtk::TreeIter const &iter) { + + Glib::ustring shortcut = (*iter)[onKBGetCols().shortcut]; + unsigned int user_set = (*iter)[onKBGetCols().user_set]; + Gtk::CellRendererAccel *accel = dynamic_cast<Gtk::CellRendererAccel *>(renderer); + if (user_set) { + accel->property_markup() = Glib::ustring("<span foreground=\"blue\"> " + shortcut + " </span>").c_str(); + } else { + accel->property_markup() = Glib::ustring("<span> " + shortcut + " </span>").c_str(); + } +} + +void InkscapePreferences::onKBListKeyboardShortcuts() +{ + // Save the current selection + Gtk::TreeStore::iterator iter = _kb_tree.get_selection()->get_selected(); + Glib::ustring selected_id = ""; + if (iter) { + selected_id = (*iter)[_kb_columns.id]; + } + + _kb_store->clear(); + + std::vector<Verb *>verbs = Inkscape::Verb::getList(); + + for (unsigned int i = 0; i < verbs.size(); i++) { + + Inkscape::Verb* verb = verbs[i]; + if (!verb) { + continue; + } + if (!verb->get_name()){ + continue; + } + + Gtk::TreeStore::Path path; + if (_kb_store->iter_is_valid(_kb_store->get_iter("0"))) { + path = _kb_store->get_path(_kb_store->get_iter("0")); + } + + // Find this group in the tree + Glib::ustring group = verb->get_group() ? _(verb->get_group()) : _("Misc"); + Gtk::TreeStore::iterator iter_group; + bool found = false; + while (path) { + iter_group = _kb_store->get_iter(path); + if (!_kb_store->iter_is_valid(iter_group)) { + break; + } + Glib::ustring name = (*iter_group)[_kb_columns.name]; + if ((*iter_group)[_kb_columns.name] == group) { + found = true; + break; + } + path.next(); + } + + if (!found) { + // Add the group if not there + iter_group = _kb_store->append(); + (*iter_group)[_kb_columns.name] = group; + (*iter_group)[_kb_columns.shortcut] = ""; + (*iter_group)[_kb_columns.id] = ""; + (*iter_group)[_kb_columns.description] = ""; + (*iter_group)[_kb_columns.shortcutid] = 0; + (*iter_group)[_kb_columns.user_set] = 0; + } + + // Remove the key accelerators from the verb name + Glib::ustring name = _(verb->get_name()); + std::string::size_type k = 0; + while((k=name.find('_',k))!=name.npos) { + name.erase(k, 1); + } + + // Get the shortcut label + unsigned int shortcut_id = sp_shortcut_get_primary(verb); + Glib::ustring shortcut_label = ""; + if (shortcut_id != GDK_KEY_VoidSymbol) { + gchar* str = sp_shortcut_get_label(shortcut_id); + if (str) { + shortcut_label = str; + g_free(str); + str = 0; + } + } + // Add the verb to the group + Gtk::TreeStore::iterator row = _kb_store->append(iter_group->children()); + (*row)[_kb_columns.name] = name; + (*row)[_kb_columns.shortcut] = shortcut_label; + (*row)[_kb_columns.description] = verb->get_short_tip() ? _(verb->get_short_tip()) : ""; + (*row)[_kb_columns.shortcutid] = shortcut_id; + (*row)[_kb_columns.id] = verb->get_id(); + (*row)[_kb_columns.user_set] = sp_shortcut_is_user_set(verb); + + if (selected_id == verb->get_id()) { + Gtk::TreeStore::Path sel_path = _kb_filter->convert_child_path_to_path(_kb_store->get_path(row)); + _kb_tree.expand_to_path(sel_path); + _kb_tree.get_selection()->select(sel_path); + } + } + + if (selected_id.empty()) { + _kb_tree.expand_to_path(_kb_store->get_path(_kb_store->get_iter("0:1"))); + } + +} void InkscapePreferences::initPageSpellcheck() { @@ -1423,7 +1886,7 @@ static void appendList( Glib::ustring& tmp, const gchar* const*listing ) void InkscapePreferences::initPageSystem() { _misc_latency_skew.init("/debug/latency/skew", 0.5, 2.0, 0.01, 0.10, 1.0, false, false); - _page_system.add_line( false, _("Latency skew:"), _misc_latency_skew, _("(requires restart)"), + _page_system.add_line( false, _("Latency _skew:"), _misc_latency_skew, _("(requires restart)"), _("Factor by which the event clock is skewed from the actual time (0.9766 on some systems)"), false); _misc_namedicon_delay.init( _("Pre-render named icons"), "/options/iconrender/named_nodelay", false); @@ -1446,7 +1909,7 @@ void InkscapePreferences::initPageSystem() _sys_user_prefs.set_editable(false); _page_system.add_line(true, _("User preferences: "), _sys_user_prefs, "", _("Location of the users preferences file"), true); - _sys_user_extension_dir.set_text((char const *)get_path(IO::Resource::USER, IO::Resource::EXTENSIONS, "")); + _sys_user_extension_dir.set_text((char const *)IO::Resource::get_path(IO::Resource::USER, IO::Resource::EXTENSIONS, "")); _sys_user_extension_dir.set_editable(false); _page_system.add_line(true, _("User extensions: "), _sys_user_extension_dir, "", _("Location of the users extensions"), true); @@ -1512,7 +1975,13 @@ bool InkscapePreferences::SetMaxDialogSize(const Gtk::TreeModel::iterator& iter) DialogPage* page = row[_page_list_columns._col_page]; _page_frame.add(*page); this->show_all_children(); - Gtk:: Requisition sreq = this->size_request(); + Gtk::Requisition sreq; +#if WITH_GTKMM_3_0 + Gtk::Requisition sreq_natural; + this->get_preferred_size(sreq_natural, sreq); +#else + sreq = this->size_request(); +#endif _max_dialog_width=std::max(_max_dialog_width, sreq.width); _max_dialog_height=std::max(_max_dialog_height, sreq.height); _page_frame.remove(); @@ -1530,7 +1999,7 @@ bool InkscapePreferences::PresentPage(const Gtk::TreeModel::iterator& iter) _page_list.expand_row(_path_tools, false); if (desired_page >= PREFS_PAGE_TOOLS_SHAPES && desired_page <= PREFS_PAGE_TOOLS_SHAPES_SPIRAL) _page_list.expand_row(_path_shapes, false); - if (desired_page >= PREFS_PAGE_UI && desired_page <= PREFS_PAGE_UI_GRIDS) + if (desired_page >= PREFS_PAGE_UI && desired_page <= PREFS_PAGE_UI_KEYBOARD_SHORTCUTS) _page_list.expand_row(_path_ui, false); if (desired_page >= PREFS_PAGE_BEHAVIOR && desired_page <= PREFS_PAGE_BEHAVIOR_MASKS) _page_list.expand_row(_path_behavior, false); diff --git a/src/ui/dialog/inkscape-preferences.h b/src/ui/dialog/inkscape-preferences.h index 101831086..da85b805d 100644 --- a/src/ui/dialog/inkscape-preferences.h +++ b/src/ui/dialog/inkscape-preferences.h @@ -7,7 +7,7 @@ * Johan Engelen <j.b.c.engelen@ewi.utwente.nl> * Bruno Dilly <bruno.dilly@gmail.com> * - * Copyright (C) 2004-2007 Authors + * Copyright (C) 2004-2013 Authors * * Released under GNU GPL. Read the file 'COPYING' for more information. */ @@ -18,15 +18,19 @@ #include <iostream> #include <vector> #include "ui/widget/preferences-widget.h" +#include "ui/widget/button.h" +#include <stddef.h> #include <gtkmm/colorbutton.h> #include <gtkmm/comboboxtext.h> #include <gtkmm/treestore.h> #include <gtkmm/treeview.h> #include <gtkmm/frame.h> #include <gtkmm/notebook.h> -#include <stddef.h> #include <gtkmm/textview.h> #include <gtkmm/scrolledwindow.h> +#include <gtkmm/liststore.h> +#include <gtkmm/treemodel.h> +#include <gtkmm/treemodelfilter.h> #include "ui/widget/panel.h" @@ -60,6 +64,7 @@ enum { PREFS_PAGE_UI, PREFS_PAGE_UI_WINDOWS, PREFS_PAGE_UI_GRIDS, + PREFS_PAGE_UI_KEYBOARD_SHORTCUTS, PREFS_PAGE_BEHAVIOR, PREFS_PAGE_BEHAVIOR_SELECTING, PREFS_PAGE_BEHAVIOR_TRANSFORMS, @@ -68,6 +73,8 @@ enum { PREFS_PAGE_BEHAVIOR_STEPS, PREFS_PAGE_BEHAVIOR_CLONES, PREFS_PAGE_BEHAVIOR_MASKS, + PREFS_PAGE_BEHAVIOR_MARKERS, + PREFS_PAGE_BEHAVIOR_CLEANUP, PREFS_PAGE_IO, PREFS_PAGE_IO_MOUSE, PREFS_PAGE_IO_SVGOUTPUT, @@ -78,8 +85,17 @@ enum { PREFS_PAGE_BITMAPS, PREFS_PAGE_RENDERING, PREFS_PAGE_SPELLCHECK + }; +namespace Gtk { +#if WITH_GTKMM_3_0 +class Scale; +#else +class HScale; +#endif +} + namespace Inkscape { namespace UI { namespace Dialog { @@ -151,6 +167,8 @@ protected: UI::Widget::DialogPage _page_steps; UI::Widget::DialogPage _page_clones; UI::Widget::DialogPage _page_mask; + UI::Widget::DialogPage _page_markers; + UI::Widget::DialogPage _page_cleanup; UI::Widget::DialogPage _page_io; UI::Widget::DialogPage _page_mouse; @@ -164,6 +182,8 @@ protected: UI::Widget::DialogPage _page_bitmaps; UI::Widget::DialogPage _page_spellcheck; + UI::Widget::DialogPage _page_keyshortcuts; + UI::Widget::PrefSpinButton _mouse_sens; UI::Widget::PrefSpinButton _mouse_thres; UI::Widget::PrefSlider _mouse_grabsize; @@ -178,7 +198,12 @@ protected: UI::Widget::PrefCheckButton _scroll_space; UI::Widget::PrefCheckButton _wheel_zoom; +#if WITH_GTKMM_3_0 + Gtk::Scale *_slider_snapping_delay; +#else Gtk::HScale *_slider_snapping_delay; +#endif + UI::Widget::PrefCheckButton _snap_indicator; UI::Widget::PrefCheckButton _snap_closest_only; UI::Widget::PrefCheckButton _snap_mouse_pointer; @@ -218,6 +243,7 @@ protected: UI::Widget::PrefRadioButton _win_gtk; UI::Widget::PrefRadioButton _win_save_dialog_pos_on; UI::Widget::PrefRadioButton _win_save_dialog_pos_off; + UI::Widget::PrefCombo _win_default_size; UI::Widget::PrefRadioButton _win_ontop_none; UI::Widget::PrefRadioButton _win_ontop_normal; UI::Widget::PrefRadioButton _win_ontop_agressive; @@ -225,6 +251,7 @@ protected: UI::Widget::PrefRadioButton _win_save_geom; UI::Widget::PrefRadioButton _win_save_geom_prefs; UI::Widget::PrefCheckButton _win_hide_task; + UI::Widget::PrefCheckButton _win_save_viewport; UI::Widget::PrefCheckButton _win_zoom_resize; UI::Widget::PrefCheckButton _win_show_close; UI::Widget::PrefSpinButton _win_trans_focus; /**< The dialog transparency setting for when the dialog is focused. */ @@ -263,6 +290,8 @@ protected: UI::Widget::PrefRadioButton _filter_quality_worse; UI::Widget::PrefRadioButton _filter_quality_worst; UI::Widget::PrefCheckButton _show_filters_info_box; + UI::Widget::PrefCombo _dockbar_style; + UI::Widget::PrefCombo _switcher_style; UI::Widget::PrefSpinButton _rendering_cache_size; UI::Widget::PrefSpinButton _filter_multi_threaded; @@ -279,13 +308,28 @@ protected: UI::Widget::PrefCheckButton _sel_hidden; UI::Widget::PrefCheckButton _sel_locked; UI::Widget::PrefCheckButton _sel_layer_deselects; + UI::Widget::PrefCheckButton _sel_cycle; + + UI::Widget::PrefCheckButton _markers_color_stock; + UI::Widget::PrefCheckButton _markers_color_custom; + UI::Widget::PrefCheckButton _markers_color_update; + + UI::Widget::PrefCheckButton _cleanup_swatches; - UI::Widget::PrefSpinButton _importexport_export; + UI::Widget::PrefSpinButton _importexport_export_res; + UI::Widget::PrefSpinButton _importexport_import_res; + UI::Widget::PrefCheckButton _importexport_import_res_override; UI::Widget::PrefSlider _snap_delay; UI::Widget::PrefSlider _snap_weight; + UI::Widget::PrefCheckButton _font_dialog; + UI::Widget::PrefCombo _font_unit_type; + UI::Widget::PrefCheckButton _font_output_px; UI::Widget::PrefCheckButton _misc_comment; + UI::Widget::PrefCheckButton _misc_default_metadata; UI::Widget::PrefCheckButton _misc_forkvectors; + UI::Widget::PrefCheckButton _misc_gradienteditor; + UI::Widget::PrefSpinButton _misc_gradientangle; UI::Widget::PrefCheckButton _misc_scripts; UI::Widget::PrefCheckButton _misc_namedicon_delay; @@ -321,11 +365,18 @@ protected: UI::Widget::PrefCheckButton _spell_ignorenumbers; UI::Widget::PrefCheckButton _spell_ignoreallcaps; + // Bitmaps UI::Widget::PrefCombo _misc_overs_bitmap; UI::Widget::PrefEntryFileButtonHBox _misc_bitmap_editor; UI::Widget::PrefCheckButton _misc_bitmap_autoreload; UI::Widget::PrefSpinButton _bitmap_copy_res; - UI::Widget::PrefCombo _bitmap_import; + UI::Widget::PrefCheckButton _bitmap_ask; + UI::Widget::PrefCombo _bitmap_link; + UI::Widget::PrefCombo _bitmap_scale; + UI::Widget::PrefSpinButton _bitmap_import_quality; + + UI::Widget::PrefEntry _kb_search; + UI::Widget::PrefCombo _kb_filelist; UI::Widget::PrefCheckButton _save_use_current_dir; UI::Widget::PrefCheckButton _save_autosave_enable; @@ -346,7 +397,8 @@ protected: UI::Widget::PrefCheckButton _cms_proof_preserveblack; Gtk::Notebook _grids_notebook; - UI::Widget::PrefCheckButton _grids_no_emphasize_on_zoom; + UI::Widget::PrefRadioButton _grids_no_emphasize_on_zoom; + UI::Widget::PrefRadioButton _grids_emphasize_on_zoom; UI::Widget::DialogPage _grids_xy; UI::Widget::DialogPage _grids_axonom; // CanvasXYGrid properties: @@ -376,7 +428,7 @@ protected: UI::Widget::PrefSpinButton _svgoutput_minimumexponent; UI::Widget::PrefCheckButton _svgoutput_inlineattrs; UI::Widget::PrefSpinButton _svgoutput_indent; - UI::Widget::PrefCheckButton _svgoutput_allowrelativecoordinates; + UI::Widget::PrefCombo _svgoutput_pathformat; UI::Widget::PrefCheckButton _svgoutput_forcerepeatcommands; // Attribute Checking controls for SVG Output page: @@ -394,6 +446,37 @@ protected: UI::Widget::PrefEntry _importexport_ocal_username; UI::Widget::PrefEntry _importexport_ocal_password; + /* + * Keyboard shortcut members + */ + class ModelColumns: public Gtk::TreeModel::ColumnRecord { + public: + ModelColumns() { + add(name); + add(id); + add(shortcut); + add(description); + add(shortcutid); + add(user_set); + } + virtual ~ModelColumns() { + } + + Gtk::TreeModelColumn<Glib::ustring> name; + Gtk::TreeModelColumn<Glib::ustring> id; + Gtk::TreeModelColumn<Glib::ustring> shortcut; + Gtk::TreeModelColumn<Glib::ustring> description; + Gtk::TreeModelColumn<unsigned int> shortcutid; + Gtk::TreeModelColumn<unsigned int> user_set; + }; + ModelColumns _kb_columns; + static ModelColumns &onKBGetCols(); + Glib::RefPtr<Gtk::TreeStore> _kb_store; + Gtk::TreeView _kb_tree; + Gtk::CellRendererAccel _kb_shortcut_renderer; + Glib::RefPtr<Gtk::TreeModelFilter> _kb_filter; + gboolean _kb_shortcuts_loaded; + int _max_dialog_width; int _max_dialog_height; int _sb_width; @@ -424,9 +507,26 @@ protected: void initPageBitmaps(); void initPageSystem(); void initPageI18n(); // Do we still need it? + void initKeyboardShortcuts(Gtk::TreeModel::iterator iter_ui); void _presentPages(); + /* + * Functions for the Keyboard shortcut editor panel + */ + void onKBReset(); + void onKBImport(); + void onKBExport(); + void onKBList(); + void onKBRealize(); + void onKBListKeyboardShortcuts(); + void onKBTreeEdited (const Glib::ustring& path, guint accel_key, Gdk::ModifierType accel_mods, guint hardware_keycode); + void onKBTreeCleared(const Glib::ustring& path_string); + bool onKBSearchKeyEvent(GdkEventKey *event); + bool onKBSearchFilter(const Gtk::TreeModel::const_iterator& iter); + static void onKBShortcutRenderer(Gtk::CellRenderer *rndr, Gtk::TreeIter const &iter); + + private: InkscapePreferences(); InkscapePreferences(InkscapePreferences const &d); diff --git a/src/ui/dialog/input.cpp b/src/ui/dialog/input.cpp index eb2ddb88f..2d4755fd2 100644 --- a/src/ui/dialog/input.cpp +++ b/src/ui/dialog/input.cpp @@ -17,7 +17,9 @@ #include <glib/gprintf.h> #include <glibmm/i18n.h> + #include <gtkmm/alignment.h> +#include <gtkmm/buttonbox.h> #include <gtkmm/cellrenderercombo.h> #include <gtkmm/checkbutton.h> #include <gtkmm/comboboxtext.h> @@ -31,7 +33,13 @@ #include <gtkmm/paned.h> #include <gtkmm/progressbar.h> #include <gtkmm/scrolledwindow.h> -#include <gtkmm/table.h> + +#if WITH_GTKMM_3_0 +# include <gtkmm/grid.h> +#else +# include <gtkmm/table.h> +#endif + #include <gtkmm/treemodel.h> #include <gtkmm/treemodelcolumn.h> #include <gtkmm/treestore.h> @@ -45,10 +53,10 @@ /* XPM */ static char const * core_xpm[] = { "16 16 4 1", -" c None", -". c #808080", -"+ c #000000", -"@ c #FFFFFF", +" c None", +". c #808080", +"+ c #000000", +"@ c #FFFFFF", " ", " ", " ", @@ -283,9 +291,9 @@ static char const *button_on[] = { /* XPM */ static char const * axis_none_xpm[] = { "24 8 3 1", -" c None", -". c #000000", -"+ c #808080", +" c None", +". c #000000", +"+ c #808080", " ", " .++++++++++++++++++. ", " .+ . .+. ", @@ -297,10 +305,10 @@ static char const * axis_none_xpm[] = { /* XPM */ static char const * axis_off_xpm[] = { "24 8 4 1", -" c None", -". c #808080", -"+ c #000000", -"@ c #FFFFFF", +" c None", +". c #808080", +"+ c #000000", +"@ c #FFFFFF", " ", " .++++++++++++++++++. ", " .+@@@@@@@@@@@@@@@@@@+. ", @@ -312,9 +320,9 @@ static char const * axis_off_xpm[] = { /* XPM */ static char const * axis_on_xpm[] = { "24 8 3 1", -" c None", -". c #000000", -"+ c #00FF00", +" c None", +". c #000000", +"+ c #00FF00", " ", " .................... ", " ..++++++++++++++++++.. ", @@ -357,6 +365,15 @@ static std::map<Gdk::InputMode, Glib::ustring> &getModeToString() return mapping; } +static int getModeId(Gdk::InputMode im) +{ + if (im == Gdk::MODE_DISABLED) return 0; + if (im == Gdk::MODE_SCREEN) return 1; + if (im == Gdk::MODE_WINDOW) return 2; + + return 0; +} + static std::map<Glib::ustring, Gdk::InputMode> &getStringToMode() { static std::map<Glib::ustring, Gdk::InputMode> mapping; @@ -400,15 +417,64 @@ private: static void setCellStateToggle(Gtk::CellRenderer *rndr, Gtk::TreeIter const &iter); void saveSettings(); + void onTreeSelect(); void useExtToggled(); - Glib::RefPtr<Gtk::TreeStore> store; - Gtk::TreeIter tabletIter; - Gtk::TreeView tree; - Gtk::ScrolledWindow treeScroller; + void onModeChange(); + void setKeys(gint count); + void setAxis(gint count); + + Glib::RefPtr<Gtk::TreeStore> confDeviceStore; + Gtk::TreeIter confDeviceIter; + Gtk::TreeView confDeviceTree; + Gtk::ScrolledWindow confDeviceScroller; Blink watcher; Gtk::CheckButton useExt; Gtk::Button save; + +#if WITH_GTKMM_3_0 + Gtk::Paned pane; +#else + Gtk::HPaned pane; +#endif + + Gtk::VBox detailsBox; + Gtk::HBox titleFrame; + Gtk::Label titleLabel; + Inkscape::UI::Widget::Frame axisFrame; + Inkscape::UI::Widget::Frame keysFrame; + Gtk::VBox axisVBox; + Gtk::ComboBoxText modeCombo; + Gtk::Label modeLabel; + Gtk::HBox modeBox; + + class KeysColumns : public Gtk::TreeModel::ColumnRecord + { + public: + KeysColumns() + { + add(name); + add(value); + } + virtual ~KeysColumns() {} + + Gtk::TreeModelColumn<Glib::ustring> name; + Gtk::TreeModelColumn<Glib::ustring> value; + }; + + KeysColumns keysColumns; + KeysColumns axisColumns; + + Glib::RefPtr<Gtk::ListStore> axisStore; + Gtk::TreeView axisTree; + Gtk::ScrolledWindow axisScroll; + + Glib::RefPtr<Gtk::ListStore> keysStore; + Gtk::TreeView keysTree; + Gtk::ScrolledWindow keysScroll; + Gtk::CellRendererAccel _kb_shortcut_renderer; + + }; static DeviceModelColumns &getCols(); @@ -425,40 +491,60 @@ private: GdkInputSource lastSourceSeen; Glib::ustring lastDevnameSeen; - Glib::RefPtr<Gtk::TreeStore> store; - Gtk::TreeIter tabletIter; - Gtk::TreeView tree; - Inkscape::UI::Widget::Frame detailFrame; + Glib::RefPtr<Gtk::TreeStore> deviceStore; + Gtk::TreeIter deviceIter; + Gtk::TreeView deviceTree; Inkscape::UI::Widget::Frame testFrame; + Inkscape::UI::Widget::Frame axisFrame; Gtk::ScrolledWindow treeScroller; Gtk::ScrolledWindow detailScroller; + +#if WITH_GTKMM_3_0 + Gtk::Paned splitter; + Gtk::Paned split2; +#else Gtk::HPaned splitter; Gtk::VPaned split2; +#endif + Gtk::Label devName; Gtk::Label devKeyCount; Gtk::Label devAxesCount; Gtk::ComboBoxText axesCombo; Gtk::ProgressBar axesValues[6]; + +#if WITH_GTKMM_3_0 + Gtk::Grid axisTable; +#else + Gtk::Table axisTable; +#endif + Gtk::ComboBoxText buttonCombo; Gtk::ComboBoxText linkCombo; sigc::connection linkConnection; Gtk::Label keyVal; Gtk::Entry keyEntry; - Gtk::Table devDetails; Gtk::Notebook topHolder; Gtk::Image testThumb; Gtk::Image testButtons[24]; Gtk::Image testAxes[8]; + +#if WITH_GTKMM_3_0 + Gtk::Grid imageTable; +#else Gtk::Table imageTable; +#endif + Gtk::EventBox testDetector; ConfPanel cfgPanel; + static void setupTree( Glib::RefPtr<Gtk::TreeStore> store, Gtk::TreeIter &tablet ); void setupValueAndCombo( gint reported, gint actual, Gtk::Label& label, Gtk::ComboBoxText& combo ); void updateTestButtons( Glib::ustring const& key, gint hotButton ); void updateTestAxes( Glib::ustring const& key, GdkDevice* dev ); - void mapAxesValues( Glib::ustring const& key, guint numAxes, gdouble const * axes, GdkDevice* dev); + void mapAxesValues( Glib::ustring const& key, gdouble const * axes, GdkDevice* dev); Glib::ustring getKeyFor( GdkDevice* device ); bool eventSnoop(GdkEvent* event); void linkComboChanged(); @@ -526,19 +612,28 @@ InputDialogImpl::InputDialogImpl() : lastSourceSeen((GdkInputSource)-1), lastDevnameSeen(""), - store(Gtk::TreeStore::create(getCols())), - tabletIter(), - tree(store), - detailFrame(), + deviceStore(Gtk::TreeStore::create(getCols())), + deviceIter(), + deviceTree(deviceStore), testFrame(_("Test Area")), + axisFrame(_("Axis")), treeScroller(), detailScroller(), splitter(), +#if WITH_GTKMM_3_0 + split2(Gtk::ORIENTATION_VERTICAL), + axisTable(), +#else split2(), + axisTable(11, 2), +#endif linkCombo(), - devDetails(12, 2), topHolder(), +#if WITH_GTKMM_3_0 + imageTable(), +#else imageTable(8, 7), +#endif testDetector(), cfgPanel() { @@ -547,10 +642,12 @@ InputDialogImpl::InputDialogImpl() : treeScroller.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); treeScroller.set_shadow_type(Gtk::SHADOW_IN); - treeScroller.add(tree); + treeScroller.add(deviceTree); treeScroller.set_size_request(50, 0); - split2.pack1(testFrame, false, false); - split2.pack2(detailFrame, true, true); + + split2.pack1(axisFrame, false, false); + split2.pack2(testFrame, true, true); + splitter.pack1(treeScroller); splitter.pack2(split2); @@ -558,13 +655,27 @@ InputDialogImpl::InputDialogImpl() : testFrame.add(testDetector); testThumb.set(getPix(PIX_TABLET)); testThumb.set_padding(24, 24); + +#if WITH_GTKMM_3_0 + testThumb.set_hexpand(); + testThumb.set_vexpand(); + imageTable.attach(testThumb, 0, 0, 8, 1); +#else imageTable.attach(testThumb, 0, 8, 0, 1, ::Gtk::EXPAND, ::Gtk::EXPAND); +#endif + { guint col = 0; guint row = 1; for ( guint num = 0; num < G_N_ELEMENTS(testButtons); num++ ) { testButtons[num].set(getPix(PIX_BUTTONS_NONE)); + +#if WITH_GTKMM_3_0 + imageTable.attach(testButtons[num], col, row, 1, 1); +#else imageTable.attach(testButtons[num], col, col + 1, row, row + 1, ::Gtk::FILL, ::Gtk::FILL); +#endif + col++; if (col > 7) { col = 0; @@ -575,7 +686,13 @@ InputDialogImpl::InputDialogImpl() : col = 0; for ( guint num = 0; num < G_N_ELEMENTS(testAxes); num++ ) { testAxes[num].set(getPix(PIX_AXIS_NONE)); + +#if WITH_GTKMM_3_0 + imageTable.attach(testAxes[num], col * 2, row, 2, 1); +#else imageTable.attach(testAxes[num], col * 2, (col + 1) * 2, row, row + 1, ::Gtk::FILL, ::Gtk::FILL); +#endif + col++; if (col > 3) { col = 0; @@ -585,54 +702,76 @@ InputDialogImpl::InputDialogImpl() : } - topHolder.append_page(cfgPanel, _("Configuration")); - topHolder.append_page(splitter, _("Hardware")); - topHolder.show_all(); - topHolder.set_current_page(0); + // This is a hidden preference to enable the "hardware" details in a separate tab + // By default this is not available to users + if (Preferences::get()->getBool("/dialogs/inputdevices/test")) { + topHolder.append_page(cfgPanel, _("Configuration")); + topHolder.append_page(splitter, _("Hardware")); + topHolder.show_all(); + topHolder.set_current_page(0); + contents->pack_start(topHolder); + } else { + contents->pack_start(cfgPanel); + } - contents->pack_start(topHolder); int rowNum = 0; /* Gtk::Label* lbl = Gtk::manage(new Gtk::Label(_("Name:"))); - devDetails.attach(*lbl, 0, 1, rowNum, rowNum+ 1, + axisTable.attach(*lbl, 0, 1, rowNum, rowNum+ 1, ::Gtk::FILL, ::Gtk::SHRINK); - devDetails.attach(devName, 1, 2, rowNum, rowNum + 1, + axisTable.attach(devName, 1, 2, rowNum, rowNum + 1, ::Gtk::SHRINK, ::Gtk::SHRINK); rowNum++;*/ + axisFrame.add(axisTable); + Gtk::Label *lbl = Gtk::manage(new Gtk::Label(_("Link:"))); - devDetails.attach(*lbl, 0, 1, rowNum, rowNum+ 1, + +#if WITH_GTKMM_3_0 + axisTable.attach(*lbl, 0, rowNum, 1, 1); +#else + axisTable.attach(*lbl, 0, 1, rowNum, rowNum+ 1, ::Gtk::FILL, ::Gtk::SHRINK); +#endif -#if WITH_GTKMM_2_24 linkCombo.append(_("None")); -#else - linkCombo.append_text(_("None")); -#endif linkCombo.set_active_text(_("None")); linkCombo.set_sensitive(false); linkConnection = linkCombo.signal_changed().connect(sigc::mem_fun(*this, &InputDialogImpl::linkComboChanged)); - devDetails.attach(linkCombo, 1, 2, rowNum, rowNum + 1, +#if WITH_GTKMM_3_0 + axisTable.attach(linkCombo, 1, rowNum, 1, 1); +#else + axisTable.attach(linkCombo, 1, 2, rowNum, rowNum + 1, ::Gtk::FILL, ::Gtk::SHRINK); +#endif + rowNum++; + lbl = Gtk::manage(new Gtk::Label(_("Axes count:"))); - devDetails.attach(*lbl, 0, 1, rowNum, rowNum+ 1, + +#if WITH_GTKMM_3_0 + axisTable.attach(*lbl, 0, rowNum, 1, 1); + axisTable.attach(devAxesCount, 1, rowNum, 1, 1); +#else + axisTable.attach(*lbl, 0, 1, rowNum, rowNum+ 1, ::Gtk::FILL, ::Gtk::SHRINK); - devDetails.attach(devAxesCount, 1, 2, rowNum, rowNum + 1, + axisTable.attach(devAxesCount, 1, 2, rowNum, rowNum + 1, ::Gtk::SHRINK, ::Gtk::SHRINK); +#endif rowNum++; + /* lbl = Gtk::manage(new Gtk::Label(_("Actual axes count:"))); devDetails.attach(*lbl, 0, 1, rowNum, rowNum+ 1, @@ -647,24 +786,42 @@ InputDialogImpl::InputDialogImpl() : for ( guint barNum = 0; barNum < static_cast<guint>(G_N_ELEMENTS(axesValues)); barNum++ ) { lbl = Gtk::manage(new Gtk::Label(_("axis:"))); - devDetails.attach(*lbl, 0, 1, rowNum, rowNum+ 1, - ::Gtk::FILL, + +#if WITH_GTKMM_3_0 + lbl->set_hexpand(); + axisTable.attach(*lbl, 0, rowNum, 1, 1); + + axesValues[barNum].set_hexpand(); + axisTable.attach(axesValues[barNum], 1, rowNum, 1, 1); +#else + axisTable.attach(*lbl, 0, 1, rowNum, rowNum+ 1, + ::Gtk::EXPAND, ::Gtk::SHRINK); - devDetails.attach(axesValues[barNum], 1, 2, rowNum, rowNum + 1, + axisTable.attach(axesValues[barNum], 1, 2, rowNum, rowNum + 1, ::Gtk::EXPAND, ::Gtk::SHRINK); +#endif + axesValues[barNum].set_sensitive(false); rowNum++; + + } lbl = Gtk::manage(new Gtk::Label(_("Button count:"))); - devDetails.attach(*lbl, 0, 1, rowNum, rowNum+ 1, + +#if WITH_GTKMM_3_0 + axisTable.attach(*lbl, 0, rowNum, 1, 1); + axisTable.attach(devKeyCount, 1, rowNum, 1, 1); +#else + axisTable.attach(*lbl, 0, 1, rowNum, rowNum+ 1, ::Gtk::FILL, ::Gtk::SHRINK); - devDetails.attach(devKeyCount, 1, 2, rowNum, rowNum + 1, + axisTable.attach(devKeyCount, 1, 2, rowNum, rowNum + 1, ::Gtk::SHRINK, ::Gtk::SHRINK); +#endif rowNum++; @@ -680,9 +837,14 @@ InputDialogImpl::InputDialogImpl() : rowNum++; */ - devDetails.attach(keyVal, 0, 2, rowNum, rowNum + 1, +#if WITH_GTKMM_3_0 + axisTable.attach(keyVal, 0, rowNum, 2, 1); +#else + axisTable.attach(keyVal, 0, 2, rowNum, rowNum + 1, ::Gtk::FILL, ::Gtk::SHRINK); +#endif + rowNum++; @@ -692,22 +854,31 @@ InputDialogImpl::InputDialogImpl() : // gint mask, // GdkExtensionMode mode); + + // TODO: Extension event stuff has been removed from public API in GTK+ 3 + // Need to check that this hasn't broken anything +#if !GTK_CHECK_VERSION(3,0,0) gtk_widget_set_extension_events( GTK_WIDGET(testDetector.gobj()), GDK_EXTENSION_EVENTS_ALL ); +#endif testDetector.add_events(Gdk::POINTER_MOTION_MASK|Gdk::KEY_PRESS_MASK|Gdk::KEY_RELEASE_MASK |Gdk::PROXIMITY_IN_MASK|Gdk::PROXIMITY_OUT_MASK|Gdk::SCROLL_MASK); - devDetails.attach(keyEntry, 0, 2, rowNum, rowNum + 1, +#if WITH_GTKMM_3_0 + axisTable.attach(keyEntry, 0, rowNum, 2, 1); +#else + axisTable.attach(keyEntry, 0, 2, rowNum, rowNum + 1, ::Gtk::FILL, ::Gtk::SHRINK); +#endif + rowNum++; - devDetails.set_sensitive(false); - detailScroller.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); + axisTable.set_sensitive(false); + +/* detailScroller.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); detailScroller.set_shadow_type(Gtk::SHADOW_NONE); detailScroller.set_border_width (0); - detailScroller.add(devDetails); - detailFrame.add(detailScroller); - detailFrame.set_size_request(0, 60); + detailScroller.add(devDetails);*/ //- 16x16/devices // gnome-dev-mouse-optical @@ -716,25 +887,24 @@ InputDialogImpl::InputDialogImpl() : // mouse - //Add the TreeView's view columns: - tree.append_column("I", getCols().thumbnail); - tree.append_column("Bar", getCols().description); + deviceTree.append_column("I", getCols().thumbnail); + deviceTree.append_column("Bar", getCols().description); - tree.set_enable_tree_lines(); - tree.set_headers_visible(false); - tree.get_selection()->signal_changed().connect(sigc::mem_fun(*this, &InputDialogImpl::resyncToSelection)); + deviceTree.set_enable_tree_lines(); + deviceTree.set_headers_visible(false); + deviceTree.get_selection()->signal_changed().connect(sigc::mem_fun(*this, &InputDialogImpl::resyncToSelection)); - setupTree( store, tabletIter ); + setupTree( deviceStore, deviceIter ); Inkscape::DeviceManager::getManager().signalDeviceChanged().connect(sigc::mem_fun(*this, &InputDialogImpl::handleDeviceChange)); Inkscape::DeviceManager::getManager().signalAxesChanged().connect(sigc::mem_fun(*this, &InputDialogImpl::updateDeviceAxes)); Inkscape::DeviceManager::getManager().signalButtonsChanged().connect(sigc::mem_fun(*this, &InputDialogImpl::updateDeviceButtons)); - Glib::RefPtr<Gtk::TreeView> treePtr(&tree); - Inkscape::DeviceManager::getManager().signalLinkChanged().connect(sigc::bind(sigc::ptr_fun(&InputDialogImpl::updateDeviceLinks), tabletIter, treePtr)); + Glib::RefPtr<Gtk::TreeView> treePtr(&deviceTree); + Inkscape::DeviceManager::getManager().signalLinkChanged().connect(sigc::bind(sigc::ptr_fun(&InputDialogImpl::updateDeviceLinks), deviceIter, treePtr)); - tree.expand_all(); + deviceTree.expand_all(); show_all_children(); } @@ -776,12 +946,30 @@ static Glib::ustring getCommon( std::list<Glib::ustring> const &names ) return result; } + +void InputDialogImpl::ConfPanel::onModeChange() +{ + Glib::ustring newText = modeCombo.get_active_text(); + + Glib::RefPtr<Gtk::TreeSelection> sel = confDeviceTree.get_selection(); + Gtk::TreeModel::iterator iter = sel->get_selected(); + if (iter) { + Glib::RefPtr<InputDevice const> dev = (*iter)[getCols().device]; + if (dev && (getStringToMode().find(newText) != getStringToMode().end())) { + Gdk::InputMode mode = getStringToMode()[newText]; + Inkscape::DeviceManager::getManager().setMode( dev->getId(), mode ); + } + } + +} + + void InputDialogImpl::setupTree( Glib::RefPtr<Gtk::TreeStore> store, Gtk::TreeIter &tablet ) { std::list<Glib::RefPtr<InputDevice const> > devList = Inkscape::DeviceManager::getManager().getDevices(); if ( !devList.empty() ) { - Gtk::TreeModel::Row row = *(store->append()); - row[getCols().description] = _("Hardware"); + //Gtk::TreeModel::Row row = *(store->append()); + //row[getCols().description] = _("Hardware"); // Let's make some tablets!!! std::list<TabletTmp> tablets; @@ -806,7 +994,7 @@ void InputDialogImpl::setupTree( Glib::RefPtr<Gtk::TreeStore> store, Gtk::TreeIt // Phase 2 - build a UI for the present devices for ( std::list<TabletTmp>::iterator it = tablets.begin(); it != tablets.end(); ++it ) { - tablet = store->append(row.children()); + tablet = store->prepend(/*row.children()*/); Gtk::TreeModel::Row childrow = *tablet; if ( it->name.empty() ) { // Check to see if we can derive one @@ -869,13 +1057,14 @@ void InputDialogImpl::setupTree( Glib::RefPtr<Gtk::TreeStore> store, Gtk::TreeIt for ( std::list<Glib::RefPtr<InputDevice const> >::iterator it = devList.begin(); it != devList.end(); ++it ) { Glib::RefPtr<InputDevice const> dev = *it; if ( dev && (consumed.find( dev->getId() ) == consumed.end()) ) { - Gtk::TreeModel::Row deviceRow = *(store->append(row.children())); + Gtk::TreeModel::Row deviceRow = *(store->prepend(/*row.children()*/)); deviceRow[getCols().description] = dev->getName(); deviceRow[getCols().device] = dev; deviceRow[getCols().mode] = dev->getMode(); deviceRow[getCols().thumbnail] = getPix(PIX_CORE); } } + } else { g_warning("No devices found"); } @@ -884,88 +1073,163 @@ void InputDialogImpl::setupTree( Glib::RefPtr<Gtk::TreeStore> store, Gtk::TreeIt InputDialogImpl::ConfPanel::ConfPanel() : Gtk::VBox(), - store(Gtk::TreeStore::create(getCols())), - tabletIter(), - tree(store), - treeScroller(), + confDeviceStore(Gtk::TreeStore::create(getCols())), + confDeviceIter(), + confDeviceTree(confDeviceStore), + confDeviceScroller(), watcher(*this), useExt(_("_Use pressure-sensitive tablet (requires restart)"), true), - save(_("_Save"), true) + save(_("_Save"), true), + detailsBox(false, 4), + titleFrame(false, 4), + titleLabel(""), + axisFrame(_("Axes")), + keysFrame(_("Keys")), + modeLabel(_("Mode:")), + modeBox(false, 4) + { - pack_start(treeScroller); - treeScroller.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); - treeScroller.add(tree); - class Foo : public Gtk::TreeModel::ColumnRecord { + confDeviceScroller.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); + confDeviceScroller.set_shadow_type(Gtk::SHADOW_IN); + confDeviceScroller.add(confDeviceTree); + confDeviceScroller.set_size_request(120, 0); + + /* class Foo : public Gtk::TreeModel::ColumnRecord { public : Gtk::TreeModelColumn<Glib::ustring> one; Foo() {add(one);} }; static Foo foo; - Glib::RefPtr<Gtk::ListStore> poppers = Gtk::ListStore::create(foo); - poppers->reference(); - - Gtk::TreeModel::Row row = *(poppers->append()); - row[foo.one] = getModeToString()[Gdk::MODE_DISABLED]; - row = *(poppers->append()); - row[foo.one] = getModeToString()[Gdk::MODE_SCREEN]; - row = *(poppers->append()); - row[foo.one] = getModeToString()[Gdk::MODE_WINDOW]; //Add the TreeView's view columns: { Gtk::CellRendererToggle *rendr = new Gtk::CellRendererToggle(); Gtk::TreeViewColumn *col = new Gtk::TreeViewColumn("xx", *rendr); if (col) { - tree.append_column(*col); + confDeviceTree.append_column(*col); col->set_cell_data_func(*rendr, sigc::ptr_fun(setCellStateToggle)); - rendr->signal_toggled().connect(sigc::bind(sigc::ptr_fun(commitCellStateChange), store)); + rendr->signal_toggled().connect(sigc::bind(sigc::ptr_fun(commitCellStateChange), confDeviceStore)); } - } + }*/ - int expPos = tree.append_column("", getCols().expander); + //int expPos = confDeviceTree.append_column("", getCols().expander); - tree.append_column("I", getCols().thumbnail); - tree.append_column("Bar", getCols().description); + confDeviceTree.append_column("I", getCols().thumbnail); + confDeviceTree.append_column("Bar", getCols().description); - { - Gtk::CellRendererCombo *rendr = new Gtk::CellRendererCombo(); - rendr->property_model().set_value(poppers); - rendr->property_text_column().set_value(0); - rendr->property_has_entry() = false; + //confDeviceTree.get_column(0)->set_fixed_width(100); + //confDeviceTree.get_column(1)->set_expand(); + +/* { Gtk::TreeViewColumn *col = new Gtk::TreeViewColumn("X", *rendr); if (col) { - tree.append_column(*col); + confDeviceTree.append_column(*col); col->set_cell_data_func(*rendr, sigc::ptr_fun(setModeCellString)); - rendr->signal_edited().connect(sigc::bind(sigc::ptr_fun(commitCellModeChange), store)); + rendr->signal_edited().connect(sigc::bind(sigc::ptr_fun(commitCellModeChange), confDeviceStore)); rendr->property_editable() = true; } - } + }*/ - tree.set_enable_tree_lines(); - tree.set_headers_visible(false); - tree.set_expander_column( *tree.get_column(expPos - 1) ); + //confDeviceTree.set_enable_tree_lines(); + confDeviceTree.property_enable_tree_lines() = false; + confDeviceTree.property_enable_grid_lines() = false; + confDeviceTree.set_headers_visible(false); + //confDeviceTree.set_expander_column( *confDeviceTree.get_column(expPos - 1) ); - setupTree( store, tabletIter ); + confDeviceTree.get_selection()->signal_changed().connect(sigc::mem_fun(*this, &InputDialogImpl::ConfPanel::onTreeSelect)); - Glib::RefPtr<Gtk::TreeView> treePtr(&tree); - Inkscape::DeviceManager::getManager().signalLinkChanged().connect(sigc::bind(sigc::ptr_fun(&InputDialogImpl::updateDeviceLinks), tabletIter, treePtr)); + setupTree( confDeviceStore, confDeviceIter ); - tree.expand_all(); + Glib::RefPtr<Gtk::TreeView> treePtr(&confDeviceTree); + Inkscape::DeviceManager::getManager().signalLinkChanged().connect(sigc::bind(sigc::ptr_fun(&InputDialogImpl::updateDeviceLinks), confDeviceIter, treePtr)); + + confDeviceTree.expand_all(); useExt.set_active(Preferences::get()->getBool("/options/useextinput/value")); useExt.signal_toggled().connect(sigc::mem_fun(*this, &InputDialogImpl::ConfPanel::useExtToggled)); - pack_start(useExt, Gtk::PACK_SHRINK); - save.signal_clicked().connect(sigc::mem_fun(*this, &InputDialogImpl::ConfPanel::saveSettings)); -#if WITH_GTKMM_2_22 - Gtk::Alignment *align = new Gtk::Alignment(Gtk::ALIGN_END, Gtk::ALIGN_START, 0, 0); +#if WITH_GTKMM_3_0 + Gtk::ButtonBox *buttonBox = manage(new Gtk::ButtonBox); #else - Gtk::Alignment *align = new Gtk::Alignment(Gtk::ALIGN_RIGHT, Gtk::ALIGN_TOP, 0, 0); + Gtk::HButtonBox *buttonBox = manage (new Gtk::HButtonBox); #endif - align->add(save); - pack_start(*Gtk::manage(align), Gtk::PACK_SHRINK); + + buttonBox->set_layout (Gtk::BUTTONBOX_END); + //Gtk::Alignment *align = new Gtk::Alignment(Gtk::ALIGN_END, Gtk::ALIGN_START, 0, 0); + buttonBox->add(save); + save.signal_clicked().connect(sigc::mem_fun(*this, &InputDialogImpl::ConfPanel::saveSettings)); + + titleFrame.pack_start(titleLabel, true, true); + //titleFrame.set_shadow_type(Gtk::SHADOW_IN); + + modeCombo.append(getModeToString()[Gdk::MODE_DISABLED]); + modeCombo.append(getModeToString()[Gdk::MODE_SCREEN]); + modeCombo.append(getModeToString()[Gdk::MODE_WINDOW]); + modeCombo.set_tooltip_text(_("A device can be 'Disabled', its co-ordinates mapped to the whole 'Screen', or to a single (usually focused) 'Window'")); + modeCombo.signal_changed().connect(sigc::mem_fun(*this, &InputDialogImpl::ConfPanel::onModeChange)); + + modeBox.pack_start(modeLabel, false, false); + modeBox.pack_start(modeCombo, true, true); + + axisVBox.add(axisScroll); + axisFrame.add(axisVBox); + + keysFrame.add(keysScroll); + + /** + * Scrolled Window + */ + keysScroll.add(keysTree); + keysScroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); + keysScroll.set_shadow_type(Gtk::SHADOW_IN); + keysScroll.set_size_request(120, 80); + + keysStore = Gtk::ListStore::create(keysColumns); + + _kb_shortcut_renderer.property_editable() = true; + + keysTree.set_model(keysStore); + keysTree.set_headers_visible(false); + keysTree.append_column("Name", keysColumns.name); + keysTree.append_column("Value", keysColumns.value); + + //keysTree.append_column("Value", _kb_shortcut_renderer); + //keysTree.get_column(1)->add_attribute(_kb_shortcut_renderer.property_text(), keysColumns.value); + //_kb_shortcut_renderer.signal_accel_edited().connect( sigc::mem_fun(*this, &InputDialogImpl::onKBTreeEdited) ); + //_kb_shortcut_renderer.signal_accel_cleared().connect( sigc::mem_fun(*this, &InputDialogImpl::onKBTreeCleared) ); + + axisStore = Gtk::ListStore::create(axisColumns); + + axisTree.set_model(axisStore); + axisTree.set_headers_visible(false); + axisTree.append_column("Name", axisColumns.name); + axisTree.append_column("Value", axisColumns.value); + + /** + * Scrolled Window + */ + axisScroll.add(axisTree); + axisScroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); + axisScroll.set_shadow_type(Gtk::SHADOW_IN); + axisScroll.set_size_request(0, 150); + + pane.pack1(confDeviceScroller); + pane.pack2(detailsBox); + + detailsBox.pack_start(titleFrame, false, false, 6); + detailsBox.pack_start(modeBox, false, false, 6); + detailsBox.pack_start(axisFrame, false, false); + detailsBox.pack_start(keysFrame, false, false); + + pack_start(pane, true, true); + pack_start(useExt, Gtk::PACK_SHRINK); + pack_start(*buttonBox, false, false); + + // Select the first device + confDeviceTree.get_selection()->select(confDeviceStore->get_iter("0")); + } InputDialogImpl::ConfPanel::~ConfPanel() @@ -998,6 +1262,8 @@ void InputDialogImpl::ConfPanel::commitCellModeChange(Glib::ustring const &path, Inkscape::DeviceManager::getManager().setMode( dev->getId(), mode ); } } + + } void InputDialogImpl::ConfPanel::setCellStateToggle(Gtk::CellRenderer *rndr, Gtk::TreeIter const &iter) @@ -1032,6 +1298,25 @@ void InputDialogImpl::ConfPanel::commitCellStateChange(Glib::ustring const &path } } +void InputDialogImpl::ConfPanel::onTreeSelect() +{ + Glib::RefPtr<Gtk::TreeSelection> treeSel = confDeviceTree.get_selection(); + Gtk::TreeModel::iterator iter = treeSel->get_selected(); + if (iter) { + Gtk::TreeModel::Row row = *iter; + Glib::ustring val = row[getCols().description]; + Glib::RefPtr<InputDevice const> dev = row[getCols().device]; + Gdk::InputMode mode = (*iter)[getCols().mode]; + modeCombo.set_active(getModeId(mode)); + + titleLabel.set_markup("<b>" + row[getCols().description] + "</b>"); + + if (dev) { + setKeys(dev->getNumKeys()); + setAxis(dev->getNumAxes()); + } + } +} void InputDialogImpl::ConfPanel::saveSettings() { Inkscape::DeviceManager::getManager().saveConfig(); @@ -1073,8 +1358,8 @@ void InputDialogImpl::handleDeviceChange(Glib::RefPtr<InputDevice const> device) { // g_message("OUCH!!!! for %p hits %s", &device, device->getId().c_str()); std::vector<Glib::RefPtr<Gtk::TreeStore> > stores; - stores.push_back(store); - stores.push_back(cfgPanel.store); + stores.push_back(deviceStore); + stores.push_back(cfgPanel.confDeviceStore); for (std::vector<Glib::RefPtr<Gtk::TreeStore> >::iterator it = stores.begin(); it != stores.end(); ++it) { Gtk::TreeModel::iterator deviceIter; @@ -1157,11 +1442,11 @@ bool InputDialogImpl::findDeviceByLink(const Gtk::TreeModel::iterator& iter, void InputDialogImpl::updateDeviceLinks(Glib::RefPtr<InputDevice const> device, Gtk::TreeIter tabletIter, Glib::RefPtr<Gtk::TreeView> tree) { - Glib::RefPtr<Gtk::TreeStore> store = Glib::RefPtr<Gtk::TreeStore>::cast_dynamic(tree->get_model()); + Glib::RefPtr<Gtk::TreeStore> deviceStore = Glib::RefPtr<Gtk::TreeStore>::cast_dynamic(tree->get_model()); // g_message("Links!!!! for %p hits [%s] with link of [%s]", &device, device->getId().c_str(), device->getLink().c_str()); Gtk::TreeModel::iterator deviceIter; - store->foreach_iter( sigc::bind<Glib::ustring, Gtk::TreeModel::iterator*>( + deviceStore->foreach_iter( sigc::bind<Glib::ustring, Gtk::TreeModel::iterator*>( sigc::ptr_fun(&InputDialogImpl::findDevice), device->getId(), &deviceIter) ); @@ -1179,16 +1464,16 @@ void InputDialogImpl::updateDeviceLinks(Glib::RefPtr<InputDevice const> device, Glib::ustring descr = (*deviceIter)[getCols().description]; Glib::RefPtr<Gdk::Pixbuf> thumb = (*deviceIter)[getCols().thumbnail]; - Gtk::TreeModel::Row deviceRow = *store->append(tabletIter->children()); + Gtk::TreeModel::Row deviceRow = *deviceStore->append(tabletIter->children()); deviceRow[getCols().description] = descr; deviceRow[getCols().thumbnail] = thumb; deviceRow[getCols().device] = dev; deviceRow[getCols().mode] = dev->getMode(); Gtk::TreeModel::iterator oldParent = deviceIter->parent(); - store->erase(deviceIter); + deviceStore->erase(deviceIter); if ( oldParent->children().empty() ) { - store->erase(oldParent); + deviceStore->erase(oldParent); } } } else { @@ -1196,7 +1481,7 @@ void InputDialogImpl::updateDeviceLinks(Glib::RefPtr<InputDevice const> device, if ( deviceIter->parent() == tabletIter ) { // Simple case. Not already linked - Gtk::TreeIter newGroup = store->append(tabletIter->children()); + Gtk::TreeIter newGroup = deviceStore->append(tabletIter->children()); (*newGroup)[getCols().description] = _("Pen"); (*newGroup)[getCols().thumbnail] = getPix(PIX_PEN); @@ -1204,7 +1489,7 @@ void InputDialogImpl::updateDeviceLinks(Glib::RefPtr<InputDevice const> device, Glib::ustring descr = (*deviceIter)[getCols().description]; Glib::RefPtr<Gdk::Pixbuf> thumb = (*deviceIter)[getCols().thumbnail]; - Gtk::TreeModel::Row deviceRow = *store->append(newGroup->children()); + Gtk::TreeModel::Row deviceRow = *deviceStore->append(newGroup->children()); deviceRow[getCols().description] = descr; deviceRow[getCols().thumbnail] = thumb; deviceRow[getCols().device] = dev; @@ -1212,7 +1497,7 @@ void InputDialogImpl::updateDeviceLinks(Glib::RefPtr<InputDevice const> device, Gtk::TreeModel::iterator linkIter; - store->foreach_iter( sigc::bind<Glib::ustring, Gtk::TreeModel::iterator*>( + deviceStore->foreach_iter( sigc::bind<Glib::ustring, Gtk::TreeModel::iterator*>( sigc::ptr_fun(&InputDialogImpl::findDeviceByLink), device->getId(), &linkIter) ); @@ -1221,22 +1506,22 @@ void InputDialogImpl::updateDeviceLinks(Glib::RefPtr<InputDevice const> device, descr = (*linkIter)[getCols().description]; thumb = (*linkIter)[getCols().thumbnail]; - deviceRow = *store->append(newGroup->children()); + deviceRow = *deviceStore->append(newGroup->children()); deviceRow[getCols().description] = descr; deviceRow[getCols().thumbnail] = thumb; deviceRow[getCols().device] = dev; deviceRow[getCols().mode] = dev->getMode(); Gtk::TreeModel::iterator oldParent = linkIter->parent(); - store->erase(linkIter); + deviceStore->erase(linkIter); if ( oldParent->children().empty() ) { - store->erase(oldParent); + deviceStore->erase(oldParent); } } Gtk::TreeModel::iterator oldParent = deviceIter->parent(); - store->erase(deviceIter); + deviceStore->erase(deviceIter); if ( oldParent->children().empty() ) { - store->erase(oldParent); + deviceStore->erase(oldParent); } tree->expand_row(Gtk::TreePath(newGroup), true); } @@ -1245,7 +1530,7 @@ void InputDialogImpl::updateDeviceLinks(Glib::RefPtr<InputDevice const> device, } void InputDialogImpl::linkComboChanged() { - Glib::RefPtr<Gtk::TreeSelection> treeSel = tree.get_selection(); + Glib::RefPtr<Gtk::TreeSelection> treeSel = deviceTree.get_selection(); Gtk::TreeModel::iterator iter = treeSel->get_selected(); if (iter) { Gtk::TreeModel::Row row = *iter; @@ -1271,34 +1556,26 @@ void InputDialogImpl::linkComboChanged() { void InputDialogImpl::resyncToSelection() { bool clear = true; - Glib::RefPtr<Gtk::TreeSelection> treeSel = tree.get_selection(); + Glib::RefPtr<Gtk::TreeSelection> treeSel = deviceTree.get_selection(); Gtk::TreeModel::iterator iter = treeSel->get_selected(); if (iter) { Gtk::TreeModel::Row row = *iter; Glib::ustring val = row[getCols().description]; Glib::RefPtr<InputDevice const> dev = row[getCols().device]; + if ( dev ) { - devDetails.set_sensitive(true); + axisTable.set_sensitive(true); linkConnection.block(); -#if WITH_GTKMM_2_24 linkCombo.remove_all(); linkCombo.append(_("None")); -#else - linkCombo.clear_items(); - linkCombo.append_text(_("None")); -#endif linkCombo.set_active(0); if ( dev->getSource() != Gdk::SOURCE_MOUSE ) { Glib::ustring linked = dev->getLink(); std::list<Glib::RefPtr<InputDevice const> > devList = Inkscape::DeviceManager::getManager().getDevices(); for ( std::list<Glib::RefPtr<InputDevice const> >::const_iterator it = devList.begin(); it != devList.end(); ++it ) { if ( ((*it)->getSource() != Gdk::SOURCE_MOUSE) && ((*it) != dev) ) { -#if WITH_GTKMM_2_24 linkCombo.append((*it)->getName().c_str()); -#else - linkCombo.append_text((*it)->getName().c_str()); -#endif if ( (linked.length() > 0) && (linked == (*it)->getId()) ) { linkCombo.set_active_text((*it)->getName().c_str()); } @@ -1312,39 +1589,70 @@ void InputDialogImpl::resyncToSelection() { clear = false; devName.set_label(row[getCols().description]); - detailFrame.set_label(row[getCols().description]); + axisFrame.set_label(row[getCols().description]); setupValueAndCombo( dev->getNumAxes(), dev->getNumAxes(), devAxesCount, axesCombo); setupValueAndCombo( dev->getNumKeys(), dev->getNumKeys(), devKeyCount, buttonCombo); + + } } - devDetails.set_sensitive(!clear); + axisTable.set_sensitive(!clear); if (clear) { - detailFrame.set_label(""); + axisFrame.set_label(""); devName.set_label(""); devAxesCount.set_label(""); devKeyCount.set_label(""); } } +void InputDialogImpl::ConfPanel::setAxis(gint count) +{ + /* + * TODO - Make each axis editable + */ + axisStore->clear(); + + static Glib::ustring axesLabels[6] = {_("X"), _("Y"), _("Pressure"), _("X tilt"), _("Y tilt"), _("Wheel")}; + + for ( gint barNum = 0; barNum < static_cast<gint>(G_N_ELEMENTS(axesLabels)); barNum++ ) { + + Gtk::TreeModel::Row row = *(axisStore->append()); + row[axisColumns.name] = axesLabels[barNum]; + if (barNum < count) { + row[axisColumns.value] = Glib::ustring::format(barNum+1); + } else { + row[axisColumns.value] = _("None"); + } + } + +} +void InputDialogImpl::ConfPanel::setKeys(gint count) +{ + /* + * TODO - Make each key assignable + */ + + keysStore->clear(); + + for (gint i = 0; i < count; i++) { + Gtk::TreeModel::Row row = *(keysStore->append()); + row[keysColumns.name] = Glib::ustring::format(i+1); + row[keysColumns.value] = _("Disabled"); + } + + +} void InputDialogImpl::setupValueAndCombo( gint reported, gint actual, Gtk::Label& label, Gtk::ComboBoxText& combo ) { gchar *tmp = g_strdup_printf("%d", reported); label.set_label(tmp); g_free(tmp); -#if WITH_GTKMM_2_24 combo.remove_all(); -#else - combo.clear_items(); -#endif for ( gint i = 1; i <= reported; ++i ) { tmp = g_strdup_printf("%d", i); -#if WITH_GTKMM_2_24 combo.append(tmp); -#else - combo.append_text(tmp); -#endif g_free(tmp); } @@ -1370,9 +1678,9 @@ void InputDialogImpl::updateTestButtons( Glib::ustring const& key, gint hotButto void InputDialogImpl::updateTestAxes( Glib::ustring const& key, GdkDevice* dev ) { - static gdouble epsilon = 0.0001; + //static gdouble epsilon = 0.0001; { - Glib::RefPtr<Gtk::TreeSelection> treeSel = tree.get_selection(); + Glib::RefPtr<Gtk::TreeSelection> treeSel = deviceTree.get_selection(); Gtk::TreeModel::iterator iter = treeSel->get_selected(); if (iter) { Gtk::TreeModel::Row row = *iter; @@ -1384,7 +1692,6 @@ void InputDialogImpl::updateTestAxes( Glib::ustring const& key, GdkDevice* dev ) } } - for ( gint i = 0; i < static_cast<gint>(G_N_ELEMENTS(testAxes)); i++ ) { if ( axesMap[key].find(i) != axesMap[key].end() ) { switch ( axesMap[key][i].first ) { @@ -1399,10 +1706,15 @@ void InputDialogImpl::updateTestAxes( Glib::ustring const& key, GdkDevice* dev ) testAxes[i].set(getPix(PIX_AXIS_OFF)); axesValues[i].set_sensitive(true); if ( dev && (i < static_cast<gint>(G_N_ELEMENTS(axesValues)) ) ) { - if ( (dev->axes[i].max - dev->axes[i].min) > epsilon ) { + // FIXME: Device axis ranges are inaccessible in GTK+ 3 and + // are deprecated in GTK+ 2. Progress-bar ranges are disabled + // until we find an alternative solution + + // if ( (dev->axes[i].max - dev->axes[i].min) > epsilon ) { axesValues[i].set_sensitive(true); - axesValues[i].set_fraction( (axesMap[key][i].second- dev->axes[i].min) / (dev->axes[i].max - dev->axes[i].min) ); - } + // axesValues[i].set_fraction( (axesMap[key][i].second- dev->axes[i].min) / (dev->axes[i].max - dev->axes[i].min) ); + // } + gchar* str = g_strdup_printf("%f", axesMap[key][i].second); axesValues[i].set_text(str); g_free(str); @@ -1412,10 +1724,16 @@ void InputDialogImpl::updateTestAxes( Glib::ustring const& key, GdkDevice* dev ) testAxes[i].set(getPix(PIX_AXIS_ON)); axesValues[i].set_sensitive(true); if ( dev && (i < static_cast<gint>(G_N_ELEMENTS(axesValues)) ) ) { - if ( (dev->axes[i].max - dev->axes[i].min) > epsilon ) { + + // FIXME: Device axis ranges are inaccessible in GTK+ 3 and + // are deprecated in GTK+ 2. Progress-bar ranges are disabled + // until we find an alternative solution + + // if ( (dev->axes[i].max - dev->axes[i].min) > epsilon ) { axesValues[i].set_sensitive(true); - axesValues[i].set_fraction( (axesMap[key][i].second- dev->axes[i].min) / (dev->axes[i].max - dev->axes[i].min) ); - } + // axesValues[i].set_fraction( (axesMap[key][i].second- dev->axes[i].min) / (dev->axes[i].max - dev->axes[i].min) ); + // } + gchar* str = g_strdup_printf("%f", axesMap[key][i].second); axesValues[i].set_text(str); g_free(str); @@ -1435,8 +1753,10 @@ void InputDialogImpl::updateTestAxes( Glib::ustring const& key, GdkDevice* dev ) } } -void InputDialogImpl::mapAxesValues( Glib::ustring const& key, guint numAxes, gdouble const * axes, GdkDevice* dev ) +void InputDialogImpl::mapAxesValues( Glib::ustring const& key, gdouble const * axes, GdkDevice* dev ) { + guint numAxes = gdk_device_get_n_axes(dev); + static gdouble epsilon = 0.0001; if ( (numAxes > 0) && axes) { for ( guint axisNum = 0; axisNum < numAxes; axisNum++ ) { @@ -1487,7 +1807,11 @@ void InputDialogImpl::mapAxesValues( Glib::ustring const& key, guint numAxes, gd Glib::ustring InputDialogImpl::getKeyFor( GdkDevice* device ) { Glib::ustring key; - switch ( device->source ) { + + GdkInputSource source = gdk_device_get_source(device); + const gchar *name = gdk_device_get_name(device); + + switch ( source ) { case GDK_SOURCE_MOUSE: key = "M:"; break; @@ -1503,7 +1827,7 @@ Glib::ustring InputDialogImpl::getKeyFor( GdkDevice* device ) default: key = "?:"; } - key += device->name; + key += name; return key; } @@ -1536,10 +1860,10 @@ bool InputDialogImpl::eventSnoop(GdkEvent* event) GdkEventButton* btnEvt = reinterpret_cast<GdkEventButton*>(event); if ( btnEvt->device ) { key = getKeyFor(btnEvt->device); - source = btnEvt->device->source; - devName = btnEvt->device->name; + source = gdk_device_get_source(btnEvt->device); + devName = gdk_device_get_name(btnEvt->device); + mapAxesValues(key, btnEvt->axes, btnEvt->device); - mapAxesValues(key, btnEvt->device->num_axes, btnEvt->axes, btnEvt->device); if ( buttonMap[key].find(btnEvt->button) == buttonMap[key].end() ) { // g_message("New button found for %s = %d", key.c_str(), btnEvt->button); buttonMap[key].insert(btnEvt->button); @@ -1565,9 +1889,9 @@ bool InputDialogImpl::eventSnoop(GdkEvent* event) GdkEventMotion* btnMtn = reinterpret_cast<GdkEventMotion*>(event); if ( btnMtn->device ) { key = getKeyFor(btnMtn->device); - source = btnMtn->device->source; - devName = btnMtn->device->name; - mapAxesValues(key, btnMtn->device->num_axes, btnMtn->axes, btnMtn->device); + source = gdk_device_get_source(btnMtn->device); + devName = gdk_device_get_name(btnMtn->device); + mapAxesValues(key, btnMtn->axes, btnMtn->device); } gchar* name = gtk_accelerator_name(0, static_cast<GdkModifierType>(btnMtn->state)); keyVal.set_label(name); @@ -1591,19 +1915,16 @@ bool InputDialogImpl::eventSnoop(GdkEvent* event) if ( (lastSourceSeen != source) || (lastDevnameSeen != devName) ) { switch (source) { - case GDK_SOURCE_MOUSE: - { + case GDK_SOURCE_MOUSE: { testThumb.set(getPix(PIX_CORE)); + break; } - break; - case GDK_SOURCE_CURSOR: - { -// g_message("flip to cursor"); + case GDK_SOURCE_CURSOR: { +// g_message("flip to cursor"); testThumb.set(getPix(PIX_MOUSE)); + break; } - break; - case GDK_SOURCE_PEN: - { + case GDK_SOURCE_PEN: { if (devName == _("pad")) { // g_message("flip to pad"); testThumb.set(getPix(PIX_SIDEBUTTONS)); @@ -1611,17 +1932,24 @@ bool InputDialogImpl::eventSnoop(GdkEvent* event) // g_message("flip to pen"); testThumb.set(getPix(PIX_TIP)); } + break; } - break; - case GDK_SOURCE_ERASER: - { + case GDK_SOURCE_ERASER: { // g_message("flip to eraser"); testThumb.set(getPix(PIX_ERASER)); + break; } - break; -// default: -// g_message("gurgle"); +#if WITH_GTKMM_3_0 + /// \fixme GTK3 added new GDK_SOURCEs that should be handled here! + case GDK_SOURCE_KEYBOARD: + case GDK_SOURCE_TOUCHSCREEN: + case GDK_SOURCE_TOUCHPAD: { + g_warning("InputDialogImpl::eventSnoop : unhandled GDK_SOURCE type!"); + break; + } +#endif } + updateTestButtons(key, hotButton); lastSourceSeen = source; lastDevnameSeen = devName; diff --git a/src/ui/dialog/layer-properties.cpp b/src/ui/dialog/layer-properties.cpp index 4fd792407..f19828b1f 100644 --- a/src/ui/dialog/layer-properties.cpp +++ b/src/ui/dialog/layer-properties.cpp @@ -3,7 +3,7 @@ * Dialog for renaming layers. */ /* Author: - * Bryce W. Harrington <bryce@bryceharrington.com> + * Bryce W. Harrington <bryce@bryceharrington.org> * Andrius R. <knutux@gmail.com> * Abhishek Sharma * @@ -15,6 +15,7 @@ #include "layer-properties.h" #include <gtkmm/stock.h> +#include <glibmm/main.h> #include <glibmm/i18n.h> #include "inkscape.h" #include "desktop.h" @@ -27,7 +28,10 @@ #include "sp-item.h" #include "verbs.h" #include "selection.h" - +#include "selection-chemistry.h" +#include "ui/icon-names.h" +#include "ui/widget/imagetoggler.h" +#include "ui/tools/tool-base.h" namespace Inkscape { namespace UI { @@ -36,21 +40,38 @@ namespace Dialogs { LayerPropertiesDialog::LayerPropertiesDialog() : _strategy(NULL), _desktop(NULL), _layer(NULL), _position_visible(false) { +#if WITH_GTKMM_3_0 + Gtk::Box *mainVBox = get_content_area(); + _layout_table.set_row_spacing(4); + _layout_table.set_column_spacing(4); +#else Gtk::Box *mainVBox = get_vbox(); - _layout_table.set_spacings(4); _layout_table.resize (1, 2); +#endif // Layer name widgets _layer_name_entry.set_activates_default(true); _layer_name_label.set_label(_("Layer name:")); _layer_name_label.set_alignment(1.0, 0.5); +#if WITH_GTKMM_3_0 + _layer_name_label.set_halign(Gtk::ALIGN_FILL); + _layer_name_label.set_valign(Gtk::ALIGN_FILL); + _layout_table.attach(_layer_name_label, 0, 0, 1, 1); + + _layer_name_entry.set_halign(Gtk::ALIGN_FILL); + _layer_name_entry.set_valign(Gtk::ALIGN_FILL); + _layer_name_entry.set_hexpand(); + _layout_table.attach(_layer_name_entry, 1, 0, 1, 1); +#else _layout_table.attach(_layer_name_label, 0, 1, 0, 1, Gtk::FILL, Gtk::FILL); _layout_table.attach(_layer_name_entry, 1, 2, 0, 1, Gtk::FILL | Gtk::EXPAND, Gtk::FILL); - mainVBox->pack_start(_layout_table, false, false, 4); +#endif + + mainVBox->pack_start(_layout_table, true, true, 4); // Buttons _close_button.set_use_stock(true); @@ -81,6 +102,7 @@ LayerPropertiesDialog::LayerPropertiesDialog() } LayerPropertiesDialog::~LayerPropertiesDialog() { + _setDesktop(NULL); _setLayer(NULL); } @@ -144,7 +166,9 @@ LayerPropertiesDialog::_setup_position_controls() { _layer_position_combo.set_cell_data_func(_label_renderer, sigc::mem_fun(*this, &LayerPropertiesDialog::_prepareLabelRenderer)); +#if !WITH_GTKMM_3_0 _layout_table.resize (2, 2); +#endif Gtk::ListStore::iterator row; row = _dropdown_list->append(); @@ -158,15 +182,162 @@ LayerPropertiesDialog::_setup_position_controls() { row->set_value(_dropdown_columns.position, LPOS_CHILD); row->set_value(_dropdown_columns.name, Glib::ustring(_("As sublayer of current"))); - _layout_table.attach(_layer_position_combo, - 1, 2, 1, 2, Gtk::FILL | Gtk::EXPAND, Gtk::FILL); _layer_position_label.set_label(_("Position:")); _layer_position_label.set_alignment(1.0, 0.5); + +#if WITH_GTKMM_3_0 + _layer_position_combo.set_halign(Gtk::ALIGN_FILL); + _layer_position_combo.set_valign(Gtk::ALIGN_FILL); + _layer_position_combo.set_hexpand(); + _layout_table.attach(_layer_position_combo, 1, 1, 1, 1); + + _layer_position_label.set_halign(Gtk::ALIGN_FILL); + _layer_position_label.set_valign(Gtk::ALIGN_FILL); + _layout_table.attach(_layer_position_label, 0, 1, 1, 1); +#else + _layout_table.attach(_layer_position_combo, + 1, 2, 1, 2, Gtk::FILL | Gtk::EXPAND, Gtk::FILL); _layout_table.attach(_layer_position_label, 0, 1, 1, 2, Gtk::FILL, Gtk::FILL); +#endif + + show_all_children(); +} + +void +LayerPropertiesDialog::_setup_layers_controls() { + + ModelColumns *zoop = new ModelColumns(); + _model = zoop; + _store = Gtk::TreeStore::create( *zoop ); + _tree.set_model( _store ); + _tree.set_headers_visible(false); + + Inkscape::UI::Widget::ImageToggler *eyeRenderer = manage( new Inkscape::UI::Widget::ImageToggler( + INKSCAPE_ICON("object-visible"), INKSCAPE_ICON("object-hidden")) ); + int visibleColNum = _tree.append_column("vis", *eyeRenderer) - 1; + Gtk::TreeViewColumn* col = _tree.get_column(visibleColNum); + if ( col ) { + col->add_attribute( eyeRenderer->property_active(), _model->_colVisible ); + } + + Inkscape::UI::Widget::ImageToggler * renderer = manage( new Inkscape::UI::Widget::ImageToggler( + INKSCAPE_ICON("object-locked"), INKSCAPE_ICON("object-unlocked")) ); + int lockedColNum = _tree.append_column("lock", *renderer) - 1; + col = _tree.get_column(lockedColNum); + if ( col ) { + col->add_attribute( renderer->property_active(), _model->_colLocked ); + } + + Gtk::CellRendererText *_text_renderer = manage(new Gtk::CellRendererText()); + int nameColNum = _tree.append_column("Name", *_text_renderer) - 1; + Gtk::TreeView::Column *_name_column = _tree.get_column(nameColNum); + _name_column->add_attribute(_text_renderer->property_text(), _model->_colLabel); + + _tree.set_expander_column( *_tree.get_column(nameColNum) ); + _tree.signal_key_press_event().connect( sigc::mem_fun(*this, &LayerPropertiesDialog::_handleKeyEvent), false ); + _tree.signal_button_press_event().connect_notify( sigc::mem_fun(*this, &LayerPropertiesDialog::_handleButtonEvent) ); + + _scroller.add( _tree ); + _scroller.set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC ); + _scroller.set_shadow_type(Gtk::SHADOW_IN); + _scroller.set_size_request(220, 180); + + SPDocument* document = _desktop->doc(); + SPRoot* root = document->getRoot(); + if ( root ) { + SPObject* target = _desktop->currentLayer(); + _store->clear(); + _addLayer( document, SP_OBJECT(root), 0, target, 0 ); + } + + _layout_table.remove(_layer_name_entry); + _layout_table.remove(_layer_name_label); + +#if WITH_GTKMM_3_0 + _scroller.set_halign(Gtk::ALIGN_FILL); + _scroller.set_valign(Gtk::ALIGN_FILL); + _scroller.set_hexpand(); + _scroller.set_vexpand(); + _layout_table.attach(_scroller, 0, 1, 2, 1); +#else + _layout_table.attach(_scroller, + 0, 2, 1, 2, Gtk::FILL | Gtk::EXPAND, Gtk::FILL | Gtk::EXPAND); +#endif + show_all_children(); } +void LayerPropertiesDialog::_addLayer( SPDocument* doc, SPObject* layer, Gtk::TreeModel::Row* parentRow, SPObject* target, int level ) +{ + int _maxNestDepth = 20; + if ( _desktop && _desktop->layer_manager && layer && (level < _maxNestDepth) ) { + unsigned int counter = _desktop->layer_manager->childCount(layer); + for ( unsigned int i = 0; i < counter; i++ ) { + SPObject *child = _desktop->layer_manager->nthChildOf(layer, i); + if ( child ) { +#if DUMP_LAYERS + g_message(" %3d layer:%p {%s} [%s]", level, child, child->id, child->label() ); +#endif // DUMP_LAYERS + + Gtk::TreeModel::iterator iter = parentRow ? _store->prepend(parentRow->children()) : _store->prepend(); + Gtk::TreeModel::Row row = *iter; + row[_model->_colObject] = child; + row[_model->_colLabel] = child->label() ? child->label() : child->getId(); + row[_model->_colVisible] = SP_IS_ITEM(child) ? !SP_ITEM(child)->isHidden() : false; + row[_model->_colLocked] = SP_IS_ITEM(child) ? SP_ITEM(child)->isLocked() : false; + + if ( target && child == target ) { + _tree.expand_to_path( _store->get_path(iter) ); + + Glib::RefPtr<Gtk::TreeSelection> select = _tree.get_selection(); + select->select(iter); + + //_checkTreeSelection(); + } + + _addLayer( doc, child, &row, target, level + 1 ); + } + } + } +} + +SPObject* LayerPropertiesDialog::_selectedLayer() +{ + SPObject* obj = 0; + + Gtk::TreeModel::iterator iter = _tree.get_selection()->get_selected(); + if ( iter ) { + Gtk::TreeModel::Row row = *iter; + obj = row[_model->_colObject]; + } + + return obj; +} + +bool LayerPropertiesDialog::_handleKeyEvent(GdkEventKey *event) +{ + + switch (Inkscape::UI::Tools::get_group0_keyval(event)) { + case GDK_KEY_Return: + case GDK_KEY_KP_Enter: { + _strategy->perform(*this); + _close(); + return true; + } + break; + } + return false; +} + +void LayerPropertiesDialog::_handleButtonEvent(GdkEventButton* event) +{ + if ( (event->type == GDK_2BUTTON_PRESS) && (event->button == 1) ) { + _strategy->perform(*this); + _close(); + } +} + /** Formats the label for a given layer row */ void LayerPropertiesDialog::_prepareLabelRenderer( @@ -201,8 +372,11 @@ void LayerPropertiesDialog::Rename::perform(LayerPropertiesDialog &dialog) { void LayerPropertiesDialog::Create::setup(LayerPropertiesDialog &dialog) { dialog.set_title(_("Add Layer")); - //TODO: find an unused layer number, forming name from _("Layer ") + "%d" - dialog._layer_name_entry.set_text(_("Layer")); + + // Set the initial name to the "next available" layer name + LayerManager *mgr = dialog._desktop->layer_manager; + Glib::ustring newName = mgr->getNextLayerName(NULL, dialog._desktop->currentLayer()->label()); + dialog._layer_name_entry.set_text(newName.c_str()); dialog._apply_button.set_label(_("_Add")); dialog._setup_position_controls(); } @@ -230,6 +404,20 @@ void LayerPropertiesDialog::Create::perform(LayerPropertiesDialog &dialog) { desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("New layer created.")); } +void LayerPropertiesDialog::Move::setup(LayerPropertiesDialog &dialog) { + dialog.set_title(_("Move to Layer")); + //TODO: find an unused layer number, forming name from _("Layer ") + "%d" + dialog._layer_name_entry.set_text(_("Layer")); + dialog._apply_button.set_label(_("_Move")); + dialog._setup_layers_controls(); +} + +void LayerPropertiesDialog::Move::perform(LayerPropertiesDialog &dialog) { + + SPObject *moveto = dialog._selectedLayer(); + sp_selection_to_layer(dialog._desktop, moveto, false); +} + void LayerPropertiesDialog::_setDesktop(SPDesktop *desktop) { if (desktop) { Inkscape::GC::anchor (desktop); diff --git a/src/ui/dialog/layer-properties.h b/src/ui/dialog/layer-properties.h index c7d7de130..d114c6ba5 100644 --- a/src/ui/dialog/layer-properties.h +++ b/src/ui/dialog/layer-properties.h @@ -2,7 +2,7 @@ * @brief Dialog for renaming layers */ /* Author: - * Bryce W. Harrington <bryce@bryceharrington.com> + * Bryce W. Harrington <bryce@bryceharrington.org> * * Copyright (C) 2004 Bryce Harrington * @@ -12,14 +12,32 @@ #ifndef INKSCAPE_DIALOG_LAYER_PROPERTIES_H #define INKSCAPE_DIALOG_LAYER_PROPERTIES_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/dialog.h> #include <gtkmm/entry.h> #include <gtkmm/label.h> + +#if WITH_GTKMM_3_0 +#include <gtkmm/grid.h> +#else #include <gtkmm/table.h> +#endif + #include <gtkmm/combobox.h> #include <gtkmm/liststore.h> +#include <gtkmm/treeview.h> +#include <gtkmm/treestore.h> +#include <gtkmm/scrolledwindow.h> #include "layer-fns.h" +#include "ui/widget/layer-selector.h" class SPDesktop; @@ -40,6 +58,9 @@ class LayerPropertiesDialog : public Gtk::Dialog { static void showCreate(SPDesktop *desktop, SPObject *layer) { _showDialog(Create::instance(), desktop, layer); } + static void showMove(SPDesktop *desktop, SPObject *layer) { + _showDialog(Move::instance(), desktop, layer); + } protected: struct Strategy { @@ -57,9 +78,15 @@ protected: void setup(LayerPropertiesDialog &dialog); void perform(LayerPropertiesDialog &dialog); }; + struct Move : public Strategy { + static Move &instance() { static Move instance; return instance; } + void setup(LayerPropertiesDialog &dialog); + void perform(LayerPropertiesDialog &dialog); + }; - friend class Rename; - friend class Create; + friend struct Rename; + friend struct Create; + friend struct Move; Strategy *_strategy; SPDesktop *_desktop; @@ -79,9 +106,40 @@ protected: Gtk::Entry _layer_name_entry; Gtk::Label _layer_position_label; Gtk::ComboBox _layer_position_combo; + +#if WITH_GTKMM_3_0 + Gtk::Grid _layout_table; +#else Gtk::Table _layout_table; +#endif + bool _position_visible; + class ModelColumns : public Gtk::TreeModel::ColumnRecord + { + public: + + ModelColumns() + { + add(_colObject); + add(_colVisible); + add(_colLocked); + add(_colLabel); + } + virtual ~ModelColumns() {} + + Gtk::TreeModelColumn<SPObject*> _colObject; + Gtk::TreeModelColumn<Glib::ustring> _colLabel; + Gtk::TreeModelColumn<bool> _colVisible; + Gtk::TreeModelColumn<bool> _colLocked; + }; + + Gtk::TreeView _tree; + ModelColumns* _model; + Glib::RefPtr<Gtk::TreeStore> _store; + Gtk::ScrolledWindow _scroller; + + PositionDropdownColumns _dropdown_columns; Gtk::CellRendererText _label_renderer; Glib::RefPtr<Gtk::ListStore> _dropdown_list; @@ -104,8 +162,14 @@ protected: void _close(); void _setup_position_controls(); + void _setup_layers_controls(); void _prepareLabelRenderer(Gtk::TreeModel::const_iterator const &row); + void _addLayer( SPDocument* doc, SPObject* layer, Gtk::TreeModel::Row* parentRow, SPObject* target, int level ); + SPObject* _selectedLayer(); + bool _handleKeyEvent(GdkEventKey *event); + void _handleButtonEvent(GdkEventButton* event); + private: LayerPropertiesDialog(LayerPropertiesDialog const &); // no copy LayerPropertiesDialog &operator=(LayerPropertiesDialog const &); // no assign diff --git a/src/ui/dialog/layers.cpp b/src/ui/dialog/layers.cpp index 3bd047ebc..381810f1e 100644 --- a/src/ui/dialog/layers.cpp +++ b/src/ui/dialog/layers.cpp @@ -16,13 +16,18 @@ #include "layers.h" #include <gtkmm/widget.h> #include <gtkmm/icontheme.h> +#include <gtkmm/imagemenuitem.h> +#include <gtkmm/separatormenuitem.h> + #include <glibmm/i18n.h> +#include <glibmm/main.h> #include "desktop.h" #include "desktop-style.h" #include "document.h" #include "document-undo.h" #include "helper/action.h" +#include "helper/action-context.h" #include "inkscape.h" #include "layer-fns.h" #include "layer-manager.h" @@ -36,7 +41,8 @@ #include "widgets/icon.h" #include "xml/repr.h" #include "sp-root.h" - +#include "ui/tools/tool-base.h" +#include "selection-chemistry.h" //#define DUMP_LAYERS 1 @@ -63,7 +69,13 @@ enum { BUTTON_DOWN, BUTTON_DUPLICATE, BUTTON_DELETE, - BUTTON_SOLO + BUTTON_SOLO, + BUTTON_SHOW_ALL, + BUTTON_HIDE_ALL, + BUTTON_LOCK_OTHERS, + BUTTON_LOCK_ALL, + BUTTON_UNLOCK_ALL, + DRAGNDROP }; class LayersPanel::InternalUIBounce @@ -88,7 +100,7 @@ void LayersPanel::_styleButton( Gtk::Button& btn, SPDesktop *desktop, unsigned i if ( desktop ) { Verb *verb = Verb::get( code ); if ( verb ) { - SPAction *action = verb->get_action(desktop); + SPAction *action = verb->get_action(Inkscape::ActionContext(desktop)); if ( !set && action && action->image ) { GtkWidget *child = sp_icon_new( Inkscape::ICON_SIZE_SMALL_TOOLBAR, action->image ); gtk_widget_show( child ); @@ -120,7 +132,7 @@ Gtk::MenuItem& LayersPanel::_addPopupItem( SPDesktop *desktop, unsigned int code if ( desktop ) { Verb *verb = Verb::get( code ); if ( verb ) { - SPAction *action = verb->get_action(desktop); + SPAction *action = verb->get_action(Inkscape::ActionContext(desktop)); if ( !iconWidget && action && action->image ) { iconWidget = sp_icon_new( Inkscape::ICON_SIZE_MENU, action->image ); } @@ -142,15 +154,18 @@ Gtk::MenuItem& LayersPanel::_addPopupItem( SPDesktop *desktop, unsigned int code } + Gtk::MenuItem* item = 0; - Gtk::Menu::MenuList& menulist = _popupMenu.items(); - - if ( wrapped ) { - menulist.push_back( Gtk::Menu_Helpers::ImageMenuElem( label, *wrapped, sigc::bind( sigc::mem_fun(*this, &LayersPanel::_takeAction), id)) ); + if (wrapped) { + item = Gtk::manage(new Gtk::ImageMenuItem(*wrapped, label, true)); } else { - menulist.push_back( Gtk::Menu_Helpers::MenuElem( label, sigc::bind( sigc::mem_fun(*this, &LayersPanel::_takeAction), id)) ); + item = Gtk::manage(new Gtk::MenuItem(label, true)); } - return menulist.back(); + + item->signal_activate().connect(sigc::bind(sigc::mem_fun(*this, &LayersPanel::_takeAction), id)); + _popupMenu.append(*item); + + return *item; } void LayersPanel::_fireAction( unsigned int code ) @@ -158,7 +173,7 @@ void LayersPanel::_fireAction( unsigned int code ) if ( _desktop ) { Verb *verb = Verb::get( code ); if ( verb ) { - SPAction *action = verb->get_action(_desktop); + SPAction *action = verb->get_action(Inkscape::ActionContext(_desktop)); if ( action ) { sp_action_perform( action, NULL ); // } else { @@ -189,7 +204,7 @@ bool LayersPanel::_executeAction() // Make sure selected layer hasn't changed since the action was triggered if ( _pending && ( - (_pending->_actionCode == BUTTON_NEW) + (_pending->_actionCode == BUTTON_NEW || _pending->_actionCode == DRAGNDROP) || !( (_desktop && _desktop->currentLayer()) && (_desktop->currentLayer() != _pending->_target) ) @@ -244,6 +259,36 @@ bool LayersPanel::_executeAction() _fireAction( SP_VERB_LAYER_SOLO ); } break; + case BUTTON_SHOW_ALL: + { + _fireAction( SP_VERB_LAYER_SHOW_ALL ); + } + break; + case BUTTON_HIDE_ALL: + { + _fireAction( SP_VERB_LAYER_HIDE_ALL ); + } + break; + case BUTTON_LOCK_OTHERS: + { + _fireAction( SP_VERB_LAYER_LOCK_OTHERS ); + } + break; + case BUTTON_LOCK_ALL: + { + _fireAction( SP_VERB_LAYER_LOCK_ALL ); + } + break; + case BUTTON_UNLOCK_ALL: + { + _fireAction( SP_VERB_LAYER_UNLOCK_ALL ); + } + break; + case DRAGNDROP: + { + _doTreeMove( ); + } + break; } delete _pending; @@ -360,13 +405,13 @@ void LayersPanel::_addLayer( SPDocument* doc, SPObject* layer, Gtk::TreeModel::R SPObject *child = _desktop->layer_manager->nthChildOf(layer, i); if ( child ) { #if DUMP_LAYERS - g_message(" %3d layer:%p {%s} [%s]", level, child, child->id, child->label() ); + g_message(" %3d layer:%p {%s} [%s]", level, child, child->getId(), child->label() ); #endif // DUMP_LAYERS Gtk::TreeModel::iterator iter = parentRow ? _store->prepend(parentRow->children()) : _store->prepend(); Gtk::TreeModel::Row row = *iter; row[_model->_colObject] = child; - row[_model->_colLabel] = child->label() ? child->label() : child->getId(); + row[_model->_colLabel] = child->defaultLabel(); row[_model->_colVisible] = SP_IS_ITEM(child) ? !SP_ITEM(child)->isHidden() : false; row[_model->_colLocked] = SP_IS_ITEM(child) ? SP_ITEM(child)->isLocked() : false; @@ -493,45 +538,218 @@ void LayersPanel::_toggled( Glib::ustring const& str, int targetCol ) break; } } + Inkscape::SelectionHelper::fixSelection(_desktop); +} + +bool LayersPanel::_handleKeyEvent(GdkEventKey *event) +{ + + switch (Inkscape::UI::Tools::get_group0_keyval(event)) { + case GDK_KEY_Return: + case GDK_KEY_KP_Enter: + case GDK_KEY_F2: { + Gtk::TreeModel::iterator iter = _tree.get_selection()->get_selected(); + if (iter && !_text_renderer->property_editable()) { + Gtk::TreeModel::Path *path = new Gtk::TreeModel::Path(iter); + // Edit the layer label + _text_renderer->property_editable() = true; + _tree.set_cursor(*path, *_name_column, true); + grab_focus(); + return true; + } + } + break; + } + return false; +} + +bool LayersPanel::_handleButtonEvent(GdkEventButton* event) +{ + static unsigned doubleclick = 0; + + if ( (event->type == GDK_BUTTON_PRESS) && (event->button == 3) ) { + // TODO - fix to a better is-popup function + Gtk::TreeModel::Path path; + int x = static_cast<int>(event->x); + int y = static_cast<int>(event->y); + if ( _tree.get_path_at_pos( x, y, path ) ) { + _checkTreeSelection(); + _popupMenu.popup(event->button, event->time); + } + } + + if ( (event->type == GDK_BUTTON_PRESS) && (event->button == 1) + && (event->state & GDK_MOD1_MASK)) { + // Alt left click on the visible/lock columns - eat this event to keep row selection + Gtk::TreeModel::Path path; + Gtk::TreeViewColumn* col = 0; + int x = static_cast<int>(event->x); + int y = static_cast<int>(event->y); + int x2 = 0; + int y2 = 0; + if ( _tree.get_path_at_pos( x, y, path, col, x2, y2 ) ) { + if (col == _tree.get_column(COL_VISIBLE-1) || + col == _tree.get_column(COL_LOCKED-1)) { + return true; + } + } + } + + // TODO - ImageToggler doesn't seem to handle Shift/Alt clicks - so we deal with them here. + if ( (event->type == GDK_BUTTON_RELEASE) && (event->button == 1) + && (event->state & (GDK_SHIFT_MASK | GDK_MOD1_MASK))) { + + Gtk::TreeModel::Path path; + Gtk::TreeViewColumn* col = 0; + int x = static_cast<int>(event->x); + int y = static_cast<int>(event->y); + int x2 = 0; + int y2 = 0; + if ( _tree.get_path_at_pos( x, y, path, col, x2, y2 ) ) { + if (event->state & GDK_SHIFT_MASK) { + // Shift left click on the visible/lock columns toggles "solo" mode + if (col == _tree.get_column(COL_VISIBLE - 1)) { + _takeAction(BUTTON_SOLO); + } else if (col == _tree.get_column(COL_LOCKED - 1)) { + _takeAction(BUTTON_LOCK_OTHERS); + } + } else if (event->state & GDK_MOD1_MASK) { + // Alt+left click on the visible/lock columns toggles "solo" mode and preserves selection + Gtk::TreeModel::iterator iter = _store->get_iter(path); + if (_store->iter_is_valid(iter)) { + Gtk::TreeModel::Row row = *iter; + SPObject *obj = row[_model->_colObject]; + if (col == _tree.get_column(COL_VISIBLE - 1)) { + _desktop->toggleLayerSolo( obj ); + DocumentUndo::maybeDone(_desktop->doc(), "layer:solo", SP_VERB_LAYER_SOLO, _("Toggle layer solo")); + } else if (col == _tree.get_column(COL_LOCKED - 1)) { + _desktop->toggleLockOtherLayers( obj ); + DocumentUndo::maybeDone(_desktop->doc(), "layer:lockothers", SP_VERB_LAYER_LOCK_OTHERS, _("Lock other layers")); + } + } + } + } + } + + + if ( (event->type == GDK_2BUTTON_PRESS) && (event->button == 1) ) { + doubleclick = 1; + } + + if ( event->type == GDK_BUTTON_RELEASE && doubleclick) { + doubleclick = 0; + Gtk::TreeModel::Path path; + Gtk::TreeViewColumn* col = 0; + int x = static_cast<int>(event->x); + int y = static_cast<int>(event->y); + int x2 = 0; + int y2 = 0; + if ( _tree.get_path_at_pos( x, y, path, col, x2, y2 ) && col == _name_column) { + // Double click on the Layer name, enable editing + _text_renderer->property_editable() = true; + _tree.set_cursor (path, *_name_column, true); + grab_focus(); + } + } + + return false; } -void LayersPanel::_handleButtonEvent(GdkEventButton* evt) +/* + * Drap and drop within the tree + * Save the drag source and drop target SPObjects and if its a drag between layers or into (sublayer) a layer + */ +bool LayersPanel::_handleDragDrop(const Glib::RefPtr<Gdk::DragContext>& /*context*/, int x, int y, guint /*time*/) { - // TODO - fix to a better is-popup function - if ( (evt->type == GDK_BUTTON_PRESS) && (evt->button == 3) ) { - - - { - Gtk::TreeModel::Path path; - Gtk::TreeViewColumn* col = 0; - int x = static_cast<int>(evt->x); - int y = static_cast<int>(evt->y); - int x2 = 0; - int y2 = 0; - if ( _tree.get_path_at_pos( x, y, - path, col, - x2, y2 ) ) { - _checkTreeSelection(); - _popupMenu.popup(evt->button, evt->time); + int cell_x = 0, cell_y = 0; + Gtk::TreeModel::Path target_path; + Gtk::TreeView::Column *target_column; + SPObject *selected = _selectedLayer(); + + _dnd_into = false; + _dnd_target = NULL; + _dnd_source = ( selected && SP_IS_ITEM(selected) ) ? SP_ITEM(selected) : 0; + + if (_tree.get_path_at_pos (x, y, target_path, target_column, cell_x, cell_y)) { + // Are we before, inside or after the drop layer + Gdk::Rectangle rect; + _tree.get_background_area (target_path, *target_column, rect); + int cell_height = rect.get_height(); + _dnd_into = (cell_y > (int)(cell_height * 1/3) && cell_y <= (int)(cell_height * 2/3)); + if (cell_y > (int)(cell_height * 2/3)) { + Gtk::TreeModel::Path next_path = target_path; + next_path.next(); + if (_store->iter_is_valid(_store->get_iter(next_path))) { + target_path = next_path; + } else { + // Dragging to the "end" + Gtk::TreeModel::Path up_path = target_path; + up_path.up(); + if (_store->iter_is_valid(_store->get_iter(up_path))) { + // Drop into parent + target_path = up_path; + _dnd_into = true; + } else { + // Drop into the top level + _dnd_target = NULL; + } } } + Gtk::TreeModel::iterator iter = _store->get_iter(target_path); + if (_store->iter_is_valid(iter)) { + Gtk::TreeModel::Row row = *iter; + SPObject *obj = row[_model->_colObject]; + _dnd_target = ( obj && SP_IS_ITEM(obj) ) ? SP_ITEM(obj) : 0; + } + } + + _takeAction(DRAGNDROP); + + return false; +} + +/* + * Move a layer in response to a drag & drop action + */ +void LayersPanel::_doTreeMove( ) +{ + if (_dnd_source ) { + _dnd_source->moveTo(_dnd_target, _dnd_into); + _selectLayer(_dnd_source); + _dnd_source = NULL; + DocumentUndo::done( _desktop->doc() , SP_VERB_NONE, + _("Moved layer")); } } -void LayersPanel::_handleRowChange( Gtk::TreeModel::Path const& /*path*/, Gtk::TreeModel::iterator const& iter ) + +void LayersPanel::_handleEdited(const Glib::ustring& path, const Glib::ustring& new_text) { + Gtk::TreeModel::iterator iter = _tree.get_model()->get_iter(path); Gtk::TreeModel::Row row = *iter; + + _renameLayer(row, new_text); + _text_renderer->property_editable() = false; +} + +void LayersPanel::_handleEditingCancelled() +{ + _text_renderer->property_editable() = false; +} + +void LayersPanel::_renameLayer(Gtk::TreeModel::Row row, const Glib::ustring& name) +{ if ( row && _desktop && _desktop->layer_manager) { SPObject* obj = row[_model->_colObject]; if ( obj ) { gchar const* oldLabel = obj->label(); - Glib::ustring tmp = row[_model->_colLabel]; - if ( oldLabel && oldLabel[0] && !tmp.empty() && (tmp != oldLabel) ) { - _desktop->layer_manager->renameLayer( obj, tmp.c_str(), FALSE ); + if ( !name.empty() && (!oldLabel || name != oldLabel) ) { + _desktop->layer_manager->renameLayer( obj, name.c_str(), FALSE ); DocumentUndo::done( _desktop->doc() , SP_VERB_NONE, - _("Renamed layer")); + _("Rename layer")); } + } } } @@ -588,6 +806,8 @@ LayersPanel::LayersPanel() : _tree.set_model( _store ); _tree.set_headers_visible(false); + _tree.set_reorderable(true); + _tree.enable_model_drag_dest (Gdk::ACTION_MOVE); Inkscape::UI::Widget::ImageToggler *eyeRenderer = manage( new Inkscape::UI::Widget::ImageToggler( INKSCAPE_ICON("object-visible"), INKSCAPE_ICON("object-hidden")) ); @@ -600,6 +820,7 @@ LayersPanel::LayersPanel() : col->add_attribute( eyeRenderer->property_active(), _model->_colVisible ); } + Inkscape::UI::Widget::ImageToggler * renderer = manage( new Inkscape::UI::Widget::ImageToggler( INKSCAPE_ICON("object-locked"), INKSCAPE_ICON("object-unlocked")) ); int lockedColNum = _tree.append_column("lock", *renderer) - 1; @@ -611,22 +832,38 @@ LayersPanel::LayersPanel() : col->add_attribute( renderer->property_active(), _model->_colLocked ); } - int nameColNum = _tree.append_column_editable("Name", _model->_colLabel) - 1; + _text_renderer = manage(new Gtk::CellRendererText()); + int nameColNum = _tree.append_column("Name", *_text_renderer) - 1; + _name_column = _tree.get_column(nameColNum); + _name_column->add_attribute(_text_renderer->property_text(), _model->_colLabel); _tree.set_expander_column( *_tree.get_column(nameColNum) ); - + _tree.set_search_column(nameColNum + 1); + _compositeSettings.setSubject(&_subject); _selectedConnection = _tree.get_selection()->signal_changed().connect( sigc::mem_fun(*this, &LayersPanel::_pushTreeSelectionToCurrent) ); _tree.get_selection()->set_select_function( sigc::mem_fun(*this, &LayersPanel::_rowSelectFunction) ); - _tree.get_model()->signal_row_changed().connect( sigc::mem_fun(*this, &LayersPanel::_handleRowChange) ); - _tree.signal_button_press_event().connect_notify( sigc::mem_fun(*this, &LayersPanel::_handleButtonEvent) ); + _tree.signal_drag_drop().connect( sigc::mem_fun(*this, &LayersPanel::_handleDragDrop), false); + + _text_renderer->signal_edited().connect( sigc::mem_fun(*this, &LayersPanel::_handleEdited) ); + _text_renderer->signal_editing_canceled().connect( sigc::mem_fun(*this, &LayersPanel::_handleEditingCancelled) ); + + _tree.signal_button_press_event().connect( sigc::mem_fun(*this, &LayersPanel::_handleButtonEvent), false ); + _tree.signal_button_release_event().connect( sigc::mem_fun(*this, &LayersPanel::_handleButtonEvent), false ); + _tree.signal_key_press_event().connect( sigc::mem_fun(*this, &LayersPanel::_handleKeyEvent), false ); _scroller.add( _tree ); _scroller.set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC ); _scroller.set_shadow_type(Gtk::SHADOW_IN); - Gtk:: Requisition sreq = _scroller.size_request(); + Gtk::Requisition sreq; +#if WITH_GTKMM_3_0 + Gtk::Requisition sreq_natural; + _scroller.get_preferred_size(sreq_natural, sreq); +#else + sreq = _scroller.size_request(); +#endif int minHeight = 70; if (sreq.height < minHeight) { // Set a min height to see the layers when used with Ubuntu liboverlay-scrollbar @@ -643,50 +880,47 @@ LayersPanel::LayersPanel() : SPDesktop* targetDesktop = getDesktop(); - _buttonsRow.set_child_min_width( 16 ); - _buttonsRow.set_layout (Gtk::BUTTONBOX_END); - Gtk::Button* btn = manage( new Gtk::Button() ); - _styleButton( *btn, targetDesktop, SP_VERB_LAYER_NEW, GTK_STOCK_ADD, C_("Layers", "New") ); + _styleButton( *btn, targetDesktop, SP_VERB_LAYER_NEW, INKSCAPE_ICON("list-add"), C_("Layers", "New") ); btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &LayersPanel::_takeAction), (int)BUTTON_NEW) ); - _buttonsRow.add( *btn ); - _buttonsRow.set_child_secondary( *btn , true); + _buttonsSecondary.pack_start(*btn, Gtk::PACK_SHRINK); btn = manage( new Gtk::Button() ); - _styleButton( *btn, targetDesktop, SP_VERB_LAYER_TO_TOP, GTK_STOCK_GOTO_TOP, C_("Layers", "Top") ); - btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &LayersPanel::_takeAction), (int)BUTTON_TOP) ); - _watchingNonTop.push_back( btn ); - _buttonsRow.add( *btn ); - - btn = manage( new Gtk::Button() ); - _styleButton( *btn, targetDesktop, SP_VERB_LAYER_RAISE, GTK_STOCK_GO_UP, C_("Layers", "Up") ); - btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &LayersPanel::_takeAction), (int)BUTTON_UP) ); - _watchingNonTop.push_back( btn ); - _buttonsRow.add( *btn ); - + _styleButton( *btn, targetDesktop, SP_VERB_LAYER_TO_BOTTOM, INKSCAPE_ICON("go-bottom"), C_("Layers", "Bot") ); + btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &LayersPanel::_takeAction), (int)BUTTON_BOTTOM) ); + _watchingNonBottom.push_back( btn ); + _buttonsPrimary.pack_end(*btn, Gtk::PACK_SHRINK); + btn = manage( new Gtk::Button() ); - _styleButton( *btn, targetDesktop, SP_VERB_LAYER_LOWER, GTK_STOCK_GO_DOWN, C_("Layers", "Dn") ); + _styleButton( *btn, targetDesktop, SP_VERB_LAYER_LOWER, INKSCAPE_ICON("go-down"), C_("Layers", "Dn") ); btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &LayersPanel::_takeAction), (int)BUTTON_DOWN) ); _watchingNonBottom.push_back( btn ); - _buttonsRow.add( *btn ); - + _buttonsPrimary.pack_end(*btn, Gtk::PACK_SHRINK); + btn = manage( new Gtk::Button() ); - _styleButton( *btn, targetDesktop, SP_VERB_LAYER_TO_BOTTOM, GTK_STOCK_GOTO_BOTTOM, C_("Layers", "Bot") ); - btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &LayersPanel::_takeAction), (int)BUTTON_BOTTOM) ); - _watchingNonBottom.push_back( btn ); - _buttonsRow.add( *btn ); + _styleButton( *btn, targetDesktop, SP_VERB_LAYER_RAISE, INKSCAPE_ICON("go-up"), C_("Layers", "Up") ); + btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &LayersPanel::_takeAction), (int)BUTTON_UP) ); + _watchingNonTop.push_back( btn ); + _buttonsPrimary.pack_end(*btn, Gtk::PACK_SHRINK); + + btn = manage( new Gtk::Button() ); + _styleButton( *btn, targetDesktop, SP_VERB_LAYER_TO_TOP, INKSCAPE_ICON("go-top"), C_("Layers", "Top") ); + btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &LayersPanel::_takeAction), (int)BUTTON_TOP) ); + _watchingNonTop.push_back( btn ); + _buttonsPrimary.pack_end(*btn, Gtk::PACK_SHRINK); // btn = manage( new Gtk::Button("Dup") ); // btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &LayersPanel::_takeAction), (int)BUTTON_DUPLICATE) ); // _buttonsRow.add( *btn ); btn = manage( new Gtk::Button() ); - _styleButton( *btn, targetDesktop, SP_VERB_LAYER_DELETE, GTK_STOCK_REMOVE, _("X") ); + _styleButton( *btn, targetDesktop, SP_VERB_LAYER_DELETE, INKSCAPE_ICON("list-remove"), _("X") ); btn->signal_clicked().connect( sigc::bind( sigc::mem_fun(*this, &LayersPanel::_takeAction), (int)BUTTON_DELETE) ); _watching.push_back( btn ); - _buttonsRow.add( *btn ); - _buttonsRow.set_child_secondary( *btn , true); - + _buttonsSecondary.pack_start(*btn, Gtk::PACK_SHRINK); + + _buttonsRow.pack_start(_buttonsSecondary, Gtk::PACK_EXPAND_WIDGET); + _buttonsRow.pack_end(_buttonsPrimary, Gtk::PACK_EXPAND_WIDGET); @@ -695,12 +929,23 @@ LayersPanel::LayersPanel() : _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_RENAME, 0, "Rename", (int)BUTTON_RENAME ) ); _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_DUPLICATE, 0, "Duplicate", (int)BUTTON_DUPLICATE ) ); _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_NEW, 0, "New", (int)BUTTON_NEW ) ); + + _popupMenu.append(*manage(new Gtk::SeparatorMenuItem())); + _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_SOLO, 0, "Solo", (int)BUTTON_SOLO ) ); + _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_SHOW_ALL, 0, "Show All", (int)BUTTON_SHOW_ALL ) ); + _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_HIDE_ALL, 0, "Hide All", (int)BUTTON_HIDE_ALL ) ); + + _popupMenu.append(*manage(new Gtk::SeparatorMenuItem())); + + _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_LOCK_OTHERS, 0, "Lock Others", (int)BUTTON_LOCK_OTHERS ) ); + _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_LOCK_ALL, 0, "Lock All", (int)BUTTON_LOCK_ALL ) ); + _watching.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_UNLOCK_ALL, 0, "Unlock All", (int)BUTTON_UNLOCK_ALL ) ); - _popupMenu.items().push_back( Gtk::Menu_Helpers::SeparatorElem() ); + _popupMenu.append(*manage(new Gtk::SeparatorMenuItem())); - _watchingNonTop.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_RAISE, GTK_STOCK_GO_UP, "Up", (int)BUTTON_UP ) ); - _watchingNonBottom.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_LOWER, GTK_STOCK_GO_DOWN, "Down", (int)BUTTON_DOWN ) ); + _watchingNonTop.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_RAISE, INKSCAPE_ICON("go-up"), "Up", (int)BUTTON_UP ) ); + _watchingNonBottom.push_back( &_addPopupItem( targetDesktop, SP_VERB_LAYER_LOWER, INKSCAPE_ICON("go-down"), "Down", (int)BUTTON_DOWN ) ); _popupMenu.show_all_children(); } diff --git a/src/ui/dialog/layers.h b/src/ui/dialog/layers.h index 7959d0e6e..ae0ac6040 100644 --- a/src/ui/dialog/layers.h +++ b/src/ui/dialog/layers.h @@ -12,8 +12,15 @@ #ifndef SEEN_LAYERS_PANEL_H #define SEEN_LAYERS_PANEL_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> -#include <gtkmm/buttonbox.h> #include <gtkmm/treeview.h> #include <gtkmm/treestore.h> #include <gtkmm/scrolledwindow.h> @@ -65,8 +72,14 @@ private: void _preToggle( GdkEvent const *event ); void _toggled( Glib::ustring const& str, int targetCol ); - void _handleButtonEvent(GdkEventButton* evt); - void _handleRowChange( Gtk::TreeModel::Path const& path, Gtk::TreeModel::iterator const& iter ); + bool _handleButtonEvent(GdkEventButton *event); + bool _handleKeyEvent(GdkEventKey *event); + bool _handleDragDrop(const Glib::RefPtr<Gdk::DragContext>& context, int x, int y, guint time); + void _handleEdited(const Glib::ustring& path, const Glib::ustring& new_text); + void _handleEditingCancelled(); + + void _doTreeMove(); + void _renameLayer(Gtk::TreeModel::Row row, const Glib::ustring& name); void _pushTreeSelectionToCurrent(); void _checkTreeSelection(); @@ -102,17 +115,27 @@ private: SPDesktop* _desktop; ModelColumns* _model; InternalUIBounce* _pending; + gboolean _dnd_into; + SPItem* _dnd_source; + SPItem* _dnd_target; GdkEvent* _toggleEvent; + Glib::RefPtr<Gtk::TreeStore> _store; std::vector<Gtk::Widget*> _watching; std::vector<Gtk::Widget*> _watchingNonTop; std::vector<Gtk::Widget*> _watchingNonBottom; Gtk::TreeView _tree; + Gtk::CellRendererText *_text_renderer; + Gtk::TreeView::Column *_name_column; #if WITH_GTKMM_3_0 - Gtk::ButtonBox _buttonsRow; + Gtk::Box _buttonsRow; + Gtk::Box _buttonsPrimary; + Gtk::Box _buttonsSecondary; #else - Gtk::HButtonBox _buttonsRow; + Gtk::HBox _buttonsRow; + Gtk::HBox _buttonsPrimary; + Gtk::HBox _buttonsSecondary; #endif Gtk::ScrolledWindow _scroller; Gtk::Menu _popupMenu; diff --git a/src/ui/dialog/livepatheffect-add.cpp b/src/ui/dialog/livepatheffect-add.cpp index c22aace37..b5f51d81d 100644 --- a/src/ui/dialog/livepatheffect-add.cpp +++ b/src/ui/dialog/livepatheffect-add.cpp @@ -48,6 +48,7 @@ LivePathEffectAdd::LivePathEffectAdd() : effectlist_treeview.set_model(effectlist_store); effectlist_treeview.set_headers_visible(false); effectlist_treeview.append_column("Name", _columns.name); + //effectlist_treeview.set_activates_default(true); /** * Initialize Effect list @@ -68,11 +69,16 @@ LivePathEffectAdd::LivePathEffectAdd() : * Buttons */ close_button.set_use_stock(true); - close_button.set_can_default(); + //close_button.set_can_default(); add_button.set_use_underline(true); add_button.set_can_default(); +#if WITH_GTKMM_3_0 + Gtk::Box *mainVBox = get_content_area(); +#else Gtk::Box *mainVBox = get_vbox(); +#endif + mainVBox->pack_start(scrolled_window, true, true); add_action_widget(close_button, Gtk::RESPONSE_CLOSE); add_action_widget(add_button, Gtk::RESPONSE_APPLY); diff --git a/src/ui/dialog/livepatheffect-add.h b/src/ui/dialog/livepatheffect-add.h index 00f58b038..7fa766272 100644 --- a/src/ui/dialog/livepatheffect-add.h +++ b/src/ui/dialog/livepatheffect-add.h @@ -11,6 +11,14 @@ #ifndef INKSCAPE_DIALOG_LIVEPATHEFFECT_ADD_H #define INKSCAPE_DIALOG_LIVEPATHEFFECT_ADD_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/dialog.h> #include <gtkmm/liststore.h> #include <gtkmm/treeview.h> diff --git a/src/ui/dialog/livepatheffect-editor.cpp b/src/ui/dialog/livepatheffect-editor.cpp index 5b9f72453..b81b300e2 100644 --- a/src/ui/dialog/livepatheffect-editor.cpp +++ b/src/ui/dialog/livepatheffect-editor.cpp @@ -48,8 +48,6 @@ #include "livepatheffect-add.h" namespace Inkscape { -class Application; - namespace UI { namespace Dialog { @@ -80,6 +78,7 @@ static void lpeeditor_selection_modified (Inkscape::Selection * selection, guint LivePathEffectEditor::LivePathEffectEditor() : UI::Widget::Panel("", "/dialogs/livepatheffect", SP_VERB_DIALOG_LIVE_PATH_EFFECT), + deskTrack(), lpe_list_locked(false), effectwidget(NULL), status_label("", Gtk::ALIGN_CENTER), @@ -108,24 +107,54 @@ LivePathEffectEditor::LivePathEffectEditor() effectcontrol_frame.add(effectcontrol_vbox); button_add.set_tooltip_text(_("Add path effect")); - button_add.set_image(*manage(Glib::wrap(gtk_image_new_from_stock ( GTK_STOCK_ADD, GTK_ICON_SIZE_SMALL_TOOLBAR ) ))); +#if GTK_CHECK_VERSION(3,10,0) + button_add.set_image_from_icon_name(INKSCAPE_ICON("list-add"), Gtk::ICON_SIZE_SMALL_TOOLBAR); +#else + Gtk::Image *image_add = Gtk::manage(new Gtk::Image()); + image_add->set_from_icon_name(INKSCAPE_ICON("list-add"), Gtk::ICON_SIZE_SMALL_TOOLBAR); + button_add.set_image(*image_add); +#endif button_add.set_relief(Gtk::RELIEF_NONE); button_remove.set_tooltip_text(_("Delete current path effect")); - button_remove.set_image(*manage(Glib::wrap(gtk_image_new_from_stock ( GTK_STOCK_REMOVE, GTK_ICON_SIZE_SMALL_TOOLBAR ) ))); +#if GTK_CHECK_VERSION(3,10,0) + button_remove.set_image_from_icon_name(INKSCAPE_ICON("list-remove"), Gtk::ICON_SIZE_SMALL_TOOLBAR); +#else + Gtk::Image *image_remove = Gtk::manage(new Gtk::Image()); + image_remove->set_from_icon_name(INKSCAPE_ICON("list-remove"), Gtk::ICON_SIZE_SMALL_TOOLBAR); + button_remove.set_image(*image_remove); +#endif button_remove.set_relief(Gtk::RELIEF_NONE); button_up.set_tooltip_text(_("Raise the current path effect")); - button_up.set_image(*manage(Glib::wrap(gtk_image_new_from_stock ( GTK_STOCK_GO_UP, GTK_ICON_SIZE_SMALL_TOOLBAR ) ))); +#if GTK_CHECK_VERSION(3,10,0) + button_up.set_image_from_icon_name(INKSCAPE_ICON("go-up"), Gtk::ICON_SIZE_SMALL_TOOLBAR); +#else + Gtk::Image *image_up = Gtk::manage(new Gtk::Image()); + image_up->set_from_icon_name(INKSCAPE_ICON("go-up"), Gtk::ICON_SIZE_SMALL_TOOLBAR); + button_up.set_image(*image_up); +#endif button_up.set_relief(Gtk::RELIEF_NONE); button_down.set_tooltip_text(_("Lower the current path effect")); - button_down.set_image(*manage(Glib::wrap(gtk_image_new_from_stock ( GTK_STOCK_GO_DOWN, GTK_ICON_SIZE_SMALL_TOOLBAR ) ))); +#if GTK_CHECK_VERSION(3,10,0) + button_down.set_image_from_icon_name(INKSCAPE_ICON("go-down"), Gtk::ICON_SIZE_SMALL_TOOLBAR); +#else + Gtk::Image *image_down = Gtk::manage(new Gtk::Image()); + image_down->set_from_icon_name(INKSCAPE_ICON("go-down"), Gtk::ICON_SIZE_SMALL_TOOLBAR); + button_down.set_image(*image_down); +#endif button_down.set_relief(Gtk::RELIEF_NONE); // Add toolbar items to toolbar toolbar_hbox.set_layout (Gtk::BUTTONBOX_END); + +#if !WITH_GTKMM_3_0 + // TODO: This has been removed from Gtkmm 3.0. Check that + // everything still looks OK! toolbar_hbox.set_child_min_width( 16 ); +#endif + toolbar_hbox.add( button_add ); toolbar_hbox.set_child_secondary( button_add , true); toolbar_hbox.add( button_remove ); @@ -168,6 +197,9 @@ LivePathEffectEditor::LivePathEffectEditor() button_up.signal_clicked().connect(sigc::mem_fun(*this, &LivePathEffectEditor::onUp)); button_down.signal_clicked().connect(sigc::mem_fun(*this, &LivePathEffectEditor::onDown)); + desktopChangeConn = deskTrack.connectDesktopChanged( sigc::mem_fun(*this, &LivePathEffectEditor::setDesktop) ); + deskTrack.connect(GTK_WIDGET(gobj())); + show_all_children(); } @@ -271,8 +303,8 @@ LivePathEffectEditor::onSelectionChanged(Inkscape::Selection *sel) current_lpeitem = lpeitem; set_sensitize_all(true); - if ( sp_lpe_item_has_path_effect(lpeitem) ) { - Inkscape::LivePathEffect::Effect *lpe = sp_lpe_item_get_current_lpe(lpeitem); + if ( lpeitem->hasPathEffect() ) { + Inkscape::LivePathEffect::Effect *lpe = lpeitem->getCurrentLPE(); if (lpe) { showParams(*lpe); lpe_list_locked = true; @@ -288,7 +320,7 @@ LivePathEffectEditor::onSelectionChanged(Inkscape::Selection *sel) } } else if ( SP_IS_USE(item) ) { // test whether linked object is supported by the CLONE_ORIGINAL LPE - SPItem *orig = sp_use_get_original( SP_USE(item) ); + SPItem *orig = SP_USE(item)->get_original(); if ( SP_IS_SHAPE(orig) || SP_IS_TEXT(orig) ) { @@ -324,7 +356,7 @@ LivePathEffectEditor::effect_list_reload(SPLPEItem *lpeitem) { effectlist_store->clear(); - PathEffectList effectlist = sp_lpe_item_get_effect_list(lpeitem); + PathEffectList effectlist = lpeitem->getEffectList(); PathEffectList::iterator it; for( it = effectlist.begin() ; it!=effectlist.end(); ++it) { @@ -408,7 +440,7 @@ LivePathEffectEditor::onAdd() // If item is a SPRect, convert it to path first: if ( SP_IS_RECT(item) ) { - sp_selected_path_to_curves(current_desktop, false); + sp_selected_path_to_curves(sel, current_desktop, false); item = sel->singleItem(); // get new item } @@ -425,7 +457,7 @@ LivePathEffectEditor::onAdd() // convert to path, apply CLONE_ORIGINAL LPE, link it to the cloned path // test whether linked object is supported by the CLONE_ORIGINAL LPE - SPItem *orig = sp_use_get_original( SP_USE(item) ); + SPItem *orig = SP_USE(item)->get_original(); if ( SP_IS_SHAPE(orig) || SP_IS_TEXT(orig) ) { @@ -440,9 +472,9 @@ LivePathEffectEditor::onAdd() // run sp_selection_clone_original_path_lpe sp_selection_clone_original_path_lpe(current_desktop); - item = sel->singleItem(); - item->getRepr()->setAttribute("id", id); - item->getRepr()->setAttribute("transform", transform); + SPItem *new_item = sel->singleItem(); + new_item->getRepr()->setAttribute("id", id); + new_item->getRepr()->setAttribute("transform", transform); g_free(id); g_free(transform); @@ -467,7 +499,7 @@ LivePathEffectEditor::onRemove() if ( sel && !sel->isEmpty() ) { SPItem *item = sel->singleItem(); if ( item && SP_IS_LPE_ITEM(item) ) { - sp_lpe_item_remove_current_path_effect(SP_LPE_ITEM(item), false); + SP_LPE_ITEM(item)->removeCurrentPathEffect(false); DocumentUndo::done( sp_desktop_document(current_desktop), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Remove path effect") ); @@ -483,13 +515,13 @@ void LivePathEffectEditor::onUp() Inkscape::Selection *sel = _getSelection(); if ( sel && !sel->isEmpty() ) { SPItem *item = sel->singleItem(); - if ( item && SP_IS_LPE_ITEM(item) ) { - sp_lpe_item_up_current_path_effect(SP_LPE_ITEM(item)); + if ( SPLPEItem *lpeitem = SP_LPE_ITEM(item) ) { + lpeitem->upCurrentPathEffect(); DocumentUndo::done( sp_desktop_document(current_desktop), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Move path effect up") ); - effect_list_reload(SP_LPE_ITEM(item)); + effect_list_reload(lpeitem); } } } @@ -499,13 +531,13 @@ void LivePathEffectEditor::onDown() Inkscape::Selection *sel = _getSelection(); if ( sel && !sel->isEmpty() ) { SPItem *item = sel->singleItem(); - if ( item && SP_IS_LPE_ITEM(item) ) { - sp_lpe_item_down_current_path_effect(SP_LPE_ITEM(item)); + if ( SPLPEItem *lpeitem = SP_LPE_ITEM(item) ) { + lpeitem->downCurrentPathEffect(); DocumentUndo::done( sp_desktop_document(current_desktop), SP_VERB_DIALOG_LIVE_PATH_EFFECT, _("Move path effect down") ); - effect_list_reload(SP_LPE_ITEM(item)); + effect_list_reload(lpeitem); } } } @@ -522,7 +554,7 @@ void LivePathEffectEditor::on_effect_selection_changed() if (lperef && current_lpeitem) { if (lperef->lpeobject->get_lpe()) { lpe_list_locked = true; // prevent reload of the list which would lose selection - sp_lpe_item_set_current_path_effect(current_lpeitem, lperef); + current_lpeitem->setCurrentPathEffect(lperef); showParams(*lperef->lpeobject->get_lpe()); } } diff --git a/src/ui/dialog/livepatheffect-editor.h b/src/ui/dialog/livepatheffect-editor.h index 20b0a673d..4aac25eaa 100644 --- a/src/ui/dialog/livepatheffect-editor.h +++ b/src/ui/dialog/livepatheffect-editor.h @@ -23,7 +23,7 @@ #include <gtkmm/scrolledwindow.h> #include <gtkmm/toolbar.h> #include <gtkmm/buttonbox.h> - +#include "ui/dialog/desktop-tracker.h" class SPDesktop; class SPLPEItem; @@ -50,6 +50,16 @@ public: void setDesktop(SPDesktop *desktop); private: + + /** + * Auxiliary widget to keep track of desktop changes for the floating dialog. + */ + DesktopTracker deskTrack; + + /** + * Link to callback function for a change in desktop (window). + */ + sigc::connection desktopChangeConn; sigc::connection selection_changed_connection; sigc::connection selection_modified_connection; diff --git a/src/ui/dialog/memory.cpp b/src/ui/dialog/memory.cpp index 97a3dc93c..0008eb284 100644 --- a/src/ui/dialog/memory.cpp +++ b/src/ui/dialog/memory.cpp @@ -15,6 +15,7 @@ #endif #include "ui/dialog/memory.h" +#include <glibmm/main.h> #include <glibmm/i18n.h> #include <gtkmm/liststore.h> #include <gtkmm/treeview.h> diff --git a/src/ui/dialog/messages.h b/src/ui/dialog/messages.h index 6ed246ece..54ca84f47 100644 --- a/src/ui/dialog/messages.h +++ b/src/ui/dialog/messages.h @@ -16,6 +16,14 @@ #ifndef INKSCAPE_UI_DIALOG_MESSAGES_H #define INKSCAPE_UI_DIALOG_MESSAGES_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> #include <gtkmm/textview.h> #include <gtkmm/button.h> diff --git a/src/ui/dialog/new-from-template.cpp b/src/ui/dialog/new-from-template.cpp new file mode 100644 index 000000000..71d1c22d0 --- /dev/null +++ b/src/ui/dialog/new-from-template.cpp @@ -0,0 +1,62 @@ +/** @file + * @brief New From Template main dialog - implementation + */ +/* Authors: + * Jan Darowski <jan.darowski@gmail.com>, supervised by Krzysztof Kosiński + * + * Copyright (C) 2013 Authors + * Released under GNU GPL, read the file 'COPYING' for more information + */ + + +#include "new-from-template.h" +#include "file.h" + +#include <gtkmm/alignment.h> +#include <glibmm/i18n.h> + + +namespace Inkscape { +namespace UI { + + +NewFromTemplate::NewFromTemplate() + : _create_template_button(_("Create from template")) +{ + set_title(_("New From Template")); + resize(400, 400); + + get_vbox()->pack_start(_main_widget); + + Gtk::Alignment *align; + align = manage(new Gtk::Alignment(Gtk::ALIGN_END, Gtk::ALIGN_CENTER, 0.0, 0.0)); + get_vbox()->pack_end(*align, Gtk::PACK_SHRINK); + align->set_padding(0, 0, 0, 15); + align->add(_create_template_button); + + _create_template_button.signal_clicked().connect( + sigc::mem_fun(*this, &NewFromTemplate::_createFromTemplate)); + + show_all(); +} + + +void NewFromTemplate::_createFromTemplate() +{ + _main_widget.createTemplate(); + _onClose(); +} + +void NewFromTemplate::_onClose() +{ + response(0); +} + +void NewFromTemplate::load_new_from_template() +{ + NewFromTemplate dl; + dl.run(); +} + +} +} diff --git a/src/ui/dialog/new-from-template.h b/src/ui/dialog/new-from-template.h new file mode 100644 index 000000000..2b40af2a6 --- /dev/null +++ b/src/ui/dialog/new-from-template.h @@ -0,0 +1,42 @@ +/** @file + * @brief New From Template main dialog + */ +/* Authors: + * Jan Darowski <jan.darowski@gmail.com>, supervised by Krzysztof Kosiński + * + * Copyright (C) 2013 Authors + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifndef INKSCAPE_SEEN_UI_DIALOG_NEW_FROM_TEMPLATE_H +#define INKSCAPE_SEEN_UI_DIALOG_NEW_FROM_TEMPLATE_H + +#include <gtkmm/dialog.h> +#include <gtkmm/button.h> + +#include "template-load-tab.h" + + +namespace Inkscape { +namespace UI { + + +class NewFromTemplate : public Gtk::Dialog +{ + +friend class TemplateLoadTab; +public: + static void load_new_from_template(); + +private: + NewFromTemplate(); + Gtk::Button _create_template_button; + TemplateLoadTab _main_widget; + + void _createFromTemplate(); + void _onClose(); +}; + +} +} +#endif diff --git a/src/ui/dialog/object-attributes.cpp b/src/ui/dialog/object-attributes.cpp index 74deffb06..cfa5c6182 100644 --- a/src/ui/dialog/object-attributes.cpp +++ b/src/ui/dialog/object-attributes.cpp @@ -1,28 +1,38 @@ /** @file * Generic object attribute editor */ -/* Authors: - * Lauris Kaplinski <lauris@kaplinski.com> - * bulia byak <buliabyak@users.sf.net> - * Kris De Gussem <Kris.DeGussem@gmail.com> - * - * Copyright (C) 1999-2012 Authors - * - * Released under GNU GPL, read the file 'COPYING' for more information +/* + * Inkscape, an Open Source vector graphics editor + * Copyright (C) 2012 Kris De Gussem <Kris.DeGussem@gmail.com> + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -#include <glibmm/i18n.h> - +#include "ui/dialog/dialog-manager.h" +#include "desktop.h" #include "desktop-handles.h" #include "macros.h" #include "sp-anchor.h" #include "sp-image.h" #include "verbs.h" #include "xml/repr.h" -#include "ui/dialog/dialog-manager.h" #include "ui/dialog/object-attributes.h" +#include "widgets/sp-attribute-widget.h" #include "inkscape.h" #include "selection.h" +#include <glibmm/i18n.h> namespace Inkscape { namespace UI { @@ -57,6 +67,7 @@ static const SPAttrDesc image_desc[] = { { N_("Y:"), "y"}, { N_("Width:"), "width"}, { N_("Height:"), "height"}, + { N_("Image Rendering:"), "image-rendering"}, { NULL, NULL} }; @@ -72,14 +83,14 @@ ObjectAttributes::ObjectAttributes (void) : UI::Widget::Panel ("", "/dialogs/objectattr/", SP_VERB_DIALOG_ATTR), blocked (false), CurrentItem(NULL), - attrTable(), + attrTable(Gtk::manage(new SPAttributeTable())), desktop(NULL), deskTrack(), selectChangedConn(), subselChangedConn(), selectModifiedConn() { - attrTable.show(); + attrTable->show(); widget_setup(); desktopChangeConn = deskTrack.connectDesktopChanged( sigc::mem_fun(*this, &ObjectAttributes::setTargetDesktop) ); @@ -114,16 +125,20 @@ void ObjectAttributes::widget_setup (void) } blocked = true; - SPObject *obj = (SPObject*)item; //to get the selected item - GObjectClass *klass = G_OBJECT_GET_CLASS(obj); //to deduce the object's type - GType type = G_TYPE_FROM_CLASS(klass); + + // CPPIFY + SPObject *obj = SP_OBJECT(item); //to get the selected item +// GObjectClass *klass = G_OBJECT_GET_CLASS(obj); //to deduce the object's type +// GType type = G_TYPE_FROM_CLASS(klass); const SPAttrDesc *desc; - if (type == SP_TYPE_ANCHOR) +// if (type == SP_TYPE_ANCHOR) + if (SP_IS_ANCHOR(item)) { desc = anchor_desc; } - else if (type == SP_TYPE_IMAGE) +// else if (type == SP_TYPE_IMAGE) + else if (SP_IS_IMAGE(item)) { Inkscape::XML::Node *ir = obj->getRepr(); const gchar *href = ir->attribute("xlink:href"); @@ -154,12 +169,12 @@ void ObjectAttributes::widget_setup (void) attrs.push_back (desc[len].attribute); len += 1; } - attrTable.set_object(obj, labels, attrs, (GtkWidget*)gobj()); + attrTable->set_object(obj, labels, attrs, (GtkWidget*)gobj()); CurrentItem = item; } else { - attrTable.change_object(obj); + attrTable->change_object(obj); } set_sensitive (true); @@ -192,7 +207,7 @@ void ObjectAttributes::selectionModifiedCB( guint flags ) if (flags & ( SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG) ) { - attrTable.reread_properties(); + attrTable->reread_properties(); } } diff --git a/src/ui/dialog/object-attributes.h b/src/ui/dialog/object-attributes.h index a5a361c25..956091989 100644 --- a/src/ui/dialog/object-attributes.h +++ b/src/ui/dialog/object-attributes.h @@ -1,23 +1,32 @@ /** @file * Generic object attribute editor */ -/* Author: - * Lauris Kaplinski <lauris@ximian.com> - * - * Copyright (C) 2001 Ximian, Inc. - * - * Licensed under GNU GPL +/* + * Inkscape, an Open Source vector graphics editor + * Copyright (C) 2012 Kris De Gussem <Kris.DeGussem@gmail.com> + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef SEEN_DIALOGS_OBJECT_ATTRIBUTES_H #define SEEN_DIALOGS_OBJECT_ATTRIBUTES_H -#include <glib.h> - -#include "desktop.h" #include "ui/dialog/desktop-tracker.h" #include "ui/widget/panel.h" -#include "widgets/sp-attribute-widget.h" + +class SPAttributeTable; namespace Inkscape { namespace UI { @@ -61,7 +70,7 @@ private: * in the SPAttrDesc arrays at the top of the cpp-file. This widgets also * ensures object attribute modifications by the user are set. */ - SPAttributeTable attrTable; + SPAttributeTable *attrTable; /** * Stores the current desktop. diff --git a/src/ui/dialog/object-properties.cpp b/src/ui/dialog/object-properties.cpp index 23c0f72ee..28e9b360b 100644 --- a/src/ui/dialog/object-properties.cpp +++ b/src/ui/dialog/object-properties.cpp @@ -1,424 +1,600 @@ /** * @file Object properties dialog. */ -/* Authors: +/* + * Inkscape, an Open Source vector graphics editor + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * Copyright (C) 2012 Kris De Gussem <Kris.DeGussem@gmail.com> + * c++ version based on former C-version (GPL v2) with authors: * Lauris Kaplinski <lauris@kaplinski.com> * bulia byak <buliabyak@users.sf.net> * Johan Engelen <goejendaagh@zonnet.nl> * Abhishek Sharma - * Kris De Gussem <Kris.DeGussem@gmail.com> - * - * Copyright (C) 1999-2012 Authors - * Copyright (C) 2001 Ximian, Inc. - * - * Released under GNU GPL, read the file 'COPYING' for more information */ -#ifdef HAVE_CONFIG_H -# include "config.h" -#endif - #include "object-properties.h" -#include "../../desktop-handles.h" -#include "../../document.h" -#include "../../document-undo.h" +#include "widgets/sp-attribute-widget.h" +#include "desktop-handles.h" +#include "document.h" +#include "document-undo.h" #include "verbs.h" #include "inkscape.h" #include "selection.h" #include "desktop.h" #include "sp-item.h" +#include "sp-image.h" +#include "xml/repr.h" #include <glibmm/i18n.h> +#if WITH_GTKMM_3_0 +# include <gtkmm/grid.h> +#else +# include <gtkmm/table.h> +#endif + namespace Inkscape { namespace UI { namespace Dialog { -ObjectProperties::ObjectProperties (void) : - UI::Widget::Panel ("", "/dialogs/object/", SP_VERB_DIALOG_ITEM), - blocked (false), - CurrentItem(NULL), - TopTable (3, 4, false), - LabelID(_("_ID:"), 1), - LabelLabel(_("_Label:"), 1), - LabelTitle(_("_Title:"),1), - LabelDescription(_("_Description"),1), - FrameDescription("", FALSE), - HBoxCheck(FALSE, 0), - CheckTable(1, 2, TRUE), - CBHide(_("_Hide"), 1), - CBLock(_("L_ock"), 1), - BSet (_("_Set"), 1), - LabelInteractivity(_("_Interactivity"), 1), - attrTable(), - desktop(NULL), - deskTrack(), - selectChangedConn(), - subselChangedConn() - // selectModifiedConn() +ObjectProperties::ObjectProperties() + : UI::Widget::Panel ("", "/dialogs/object/", SP_VERB_DIALOG_ITEM) + , _blocked (false) + , _current_item(NULL) + , _label_id(_("_ID:"), 1) + , _label_label(_("_Label:"), 1) + , _label_title(_("_Title:"), 1) + , _label_image_rendering(_("_Image Rendering:"), 1) + , _cb_hide(_("_Hide"), 1) + , _cb_lock(_("L_ock"), 1) + , _attr_table(Gtk::manage(new SPAttributeTable())) + , _desktop(NULL) { //initialize labels for the table at the bottom of the dialog - int_labels.push_back("onclick"); - int_labels.push_back("onmouseover"); - int_labels.push_back("onmouseout"); - int_labels.push_back("onmousedown"); - int_labels.push_back("onmouseup"); - int_labels.push_back("onmousemove"); - int_labels.push_back("onfocusin"); - int_labels.push_back("onfocusout"); - int_labels.push_back("onfocusout"); - int_labels.push_back("onload"); - - desktopChangeConn = deskTrack.connectDesktopChanged( sigc::mem_fun(*this, &ObjectProperties::setTargetDesktop) ); - deskTrack.connect(GTK_WIDGET(gobj())); - - MakeWidget(); + _int_attrs.push_back("onclick"); + _int_attrs.push_back("onmouseover"); + _int_attrs.push_back("onmouseout"); + _int_attrs.push_back("onmousedown"); + _int_attrs.push_back("onmouseup"); + _int_attrs.push_back("onmousemove"); + _int_attrs.push_back("onfocusin"); + _int_attrs.push_back("onfocusout"); + _int_attrs.push_back("onload"); + + _int_labels.push_back("onclick:"); + _int_labels.push_back("onmouseover:"); + _int_labels.push_back("onmouseout:"); + _int_labels.push_back("onmousedown:"); + _int_labels.push_back("onmouseup:"); + _int_labels.push_back("onmousemove:"); + _int_labels.push_back("onfocusin:"); + _int_labels.push_back("onfocusout:"); + _int_labels.push_back("onload:"); + + _desktop_changed_connection = _desktop_tracker.connectDesktopChanged( + sigc::mem_fun(*this, &ObjectProperties::_setTargetDesktop) + ); + _desktop_tracker.connect(GTK_WIDGET(gobj())); + + _init(); } -ObjectProperties::~ObjectProperties (void) +ObjectProperties::~ObjectProperties() { - // selectModifiedConn.disconnect(); - subselChangedConn.disconnect(); - selectChangedConn.disconnect(); - desktopChangeConn.disconnect(); - deskTrack.disconnect(); + _subselection_changed_connection.disconnect(); + _selection_changed_connection.disconnect(); + _desktop_changed_connection.disconnect(); + _desktop_tracker.disconnect(); } -void ObjectProperties::MakeWidget(void) +void ObjectProperties::_init() { Gtk::Box *contents = _getContents(); contents->set_spacing(0); - - TopTable.set_border_width(4); - TopTable.set_row_spacings(4); - TopTable.set_col_spacings(4); - contents->pack_start (TopTable, true, true, 0); + +#if WITH_GTKMM_3_0 + Gtk::Grid *grid_top = Gtk::manage(new Gtk::Grid()); + grid_top->set_row_spacing(4); + grid_top->set_column_spacing(0); +#else + Gtk::Table *grid_top = Gtk::manage(new Gtk::Table(4, 4)); + grid_top->set_row_spacings(4); + grid_top->set_col_spacings(0); +#endif + + grid_top->set_border_width(4); + + contents->pack_start(*grid_top, false, false, 0); + /* Create the label for the object id */ - LabelID.set_alignment (1, 0.5); - TopTable.attach (LabelID, 0, 1, 0, 1, - Gtk::SHRINK | Gtk::FILL, - Gtk::AttachOptions(), 0, 0 ); + _label_id.set_label(_label_id.get_label() + " "); + _label_id.set_alignment(1, 0.5); + +#if WITH_GTKMM_3_0 + _label_id.set_valign(Gtk::ALIGN_CENTER); + grid_top->attach(_label_id, 0, 0, 1, 1); +#else + grid_top->attach(_label_id, 0, 1, 0, 1, + Gtk::SHRINK | Gtk::FILL, + Gtk::AttachOptions(), 0, 0 ); +#endif + /* Create the entry box for the object id */ - EntryID.set_tooltip_text (_("The id= attribute (only letters, digits, and the characters .-_: allowed)")); - EntryID.set_max_length (64); - TopTable.attach (EntryID, 1, 2, 0, 1, - Gtk::EXPAND | Gtk::FILL, - Gtk::AttachOptions(), 0, 0 ); - LabelID.set_mnemonic_widget (EntryID); + _entry_id.set_tooltip_text(_("The id= attribute (only letters, digits, and the characters .-_: allowed)")); + _entry_id.set_max_length(64); + +#if WITH_GTKMM_3_0 + _entry_id.set_valign(Gtk::ALIGN_CENTER); + grid_top->attach(_entry_id, 1, 0, 1, 1); +#else + grid_top->attach(_entry_id, 1, 2, 0, 1, + Gtk::EXPAND | Gtk::FILL, + Gtk::AttachOptions(), 0, 0 ); +#endif + + _label_id.set_mnemonic_widget(_entry_id); // pressing enter in the id field is the same as clicking Set: - EntryID.signal_activate().connect(sigc::mem_fun(this, &ObjectProperties::label_changed)); + _entry_id.signal_activate().connect(sigc::mem_fun(this, &ObjectProperties::_labelChanged)); // focus is in the id field initially: - EntryID.grab_focus(); + _entry_id.grab_focus(); + /* Create the label for the object label */ - LabelLabel.set_alignment (1, 0.5); - TopTable.attach (LabelLabel, 0, 1, 1, 2, - Gtk::SHRINK | Gtk::FILL, - Gtk::AttachOptions(), 0, 0 ); + _label_label.set_label(_label_label.get_label() + " "); + _label_label.set_alignment(1, 0.5); + +#if WITH_GTKMM_3_0 + _label_label.set_valign(Gtk::ALIGN_CENTER); + grid_top->attach(_label_label, 0, 1, 1, 1); +#else + grid_top->attach(_label_label, 0, 1, 1, 2, + Gtk::SHRINK | Gtk::FILL, + Gtk::AttachOptions(), 0, 0 ); +#endif + /* Create the entry box for the object label */ - EntryLabel.set_tooltip_text (_("A freeform label for the object")); - EntryLabel.set_max_length (256); - TopTable.attach (EntryLabel, 1, 2, 1, 2, - Gtk::EXPAND | Gtk::FILL, - Gtk::AttachOptions(), 0, 0 ); - LabelLabel.set_mnemonic_widget (EntryLabel); + _entry_label.set_tooltip_text(_("A freeform label for the object")); + _entry_label.set_max_length(256); + +#if WITH_GTKMM_3_0 + _entry_label.set_hexpand(); + _entry_label.set_valign(Gtk::ALIGN_CENTER); + grid_top->attach(_entry_label, 1, 1, 1, 1); +#else + grid_top->attach(_entry_label, 1, 2, 1, 2, + Gtk::EXPAND | Gtk::FILL, + Gtk::AttachOptions(), 0, 0 ); +#endif + + _label_label.set_mnemonic_widget(_entry_label); // pressing enter in the label field is the same as clicking Set: - EntryLabel.signal_activate().connect(sigc::mem_fun(this, &ObjectProperties::label_changed)); + _entry_label.signal_activate().connect(sigc::mem_fun(this, &ObjectProperties::_labelChanged)); + /* Create the label for the object title */ - LabelTitle.set_alignment (1, 0.5); - TopTable.attach (LabelTitle, 0, 1, 2, 3, - Gtk::SHRINK | Gtk::FILL, - Gtk::AttachOptions(), 0, 0 ); + _label_title.set_label(_label_title.get_label() + " "); + _label_title.set_alignment (1, 0.5); + +#if WITH_GTKMM_3_0 + _label_title.set_valign(Gtk::ALIGN_CENTER); + grid_top->attach(_label_title, 0, 2, 1, 1); +#else + grid_top->attach(_label_title, 0, 1, 2, 3, + Gtk::SHRINK | Gtk::FILL, + Gtk::AttachOptions(), 0, 0 ); +#endif /* Create the entry box for the object title */ - EntryTitle.set_sensitive (FALSE); - EntryTitle.set_max_length (256); - TopTable.attach (EntryTitle, 1, 3, 2, 3, - Gtk::EXPAND | Gtk::FILL, - Gtk::AttachOptions(), 0, 0 ); - LabelTitle.set_mnemonic_widget (EntryTitle); + _entry_title.set_sensitive (FALSE); + _entry_title.set_max_length (256); + +#if WITH_GTKMM_3_0 + _entry_title.set_hexpand(); + _entry_title.set_valign(Gtk::ALIGN_CENTER); + grid_top->attach(_entry_title, 1, 2, 1, 1); +#else + grid_top->attach(_entry_title, 1, 2, 2, 3, + Gtk::EXPAND | Gtk::FILL, + Gtk::AttachOptions(), 0, 0 ); +#endif - /* Create the frame for the object description */ - FrameDescription.set_label_widget (LabelDescription); - FrameDescription.set_padding (4,0,0,0); + _label_title.set_mnemonic_widget(_entry_title); + // pressing enter in the label field is the same as clicking Set: + _entry_title.signal_activate().connect(sigc::mem_fun(this, &ObjectProperties::_labelChanged)); - TopTable.attach (FrameDescription, 0, 3, 3, 4, - Gtk::EXPAND | Gtk::FILL, - Gtk::EXPAND | Gtk::FILL, 0, 0 ); + /* Create the frame for the object description */ + Gtk::Label *label_desc = Gtk::manage(new Gtk::Label(_("_Description:"), 1)); + UI::Widget::Frame *frame_desc = Gtk::manage(new UI::Widget::Frame("", FALSE)); + frame_desc->set_label_widget(*label_desc); + frame_desc->set_padding (0,0,0,0); + contents->pack_start(*frame_desc, true, true, 0); /* Create the text view box for the object description */ - FrameTextDescription.set_border_width(4); - FrameTextDescription.set_sensitive (FALSE); - FrameDescription.add (FrameTextDescription); - FrameTextDescription.set_shadow_type (Gtk::SHADOW_IN); + _ft_description.set_border_width(4); + _ft_description.set_sensitive(FALSE); + frame_desc->add(_ft_description); + _ft_description.set_shadow_type(Gtk::SHADOW_IN); + + _tv_description.set_wrap_mode(Gtk::WRAP_WORD); + _tv_description.get_buffer()->set_text(""); + _ft_description.add(_tv_description); + _tv_description.add_mnemonic_label(*label_desc); + + /* Image rendering */ + /* Create the label for the object ImageRendering */ + _label_image_rendering.set_label(_label_image_rendering.get_label() + " "); + _label_image_rendering.set_alignment(1, 0.5); + +#if WITH_GTKMM_3_0 + _label_image_rendering.set_valign(Gtk::ALIGN_CENTER); + grid_top->attach(_label_image_rendering, 0, 3, 1, 1); +#else + grid_top->attach(_label_image_rendering, 0, 1, 3, 4, + Gtk::SHRINK | Gtk::FILL, + Gtk::AttachOptions(), 0, 0 ); +#endif - TextViewDescription.set_wrap_mode(Gtk::WRAP_WORD); - TextViewDescription.get_buffer()->set_text(""); - FrameTextDescription.add (TextViewDescription); - TextViewDescription.add_mnemonic_label(LabelDescription); + /* Create the combo box text for the 'image-rendering' property */ + _combo_image_rendering.append( "auto" ); + _combo_image_rendering.append( "optimizeQuality" ); + _combo_image_rendering.append( "optimizeSpeed" ); + _combo_image_rendering.set_tooltip_text(_("The 'image-rendering' property can influence how a bitmap is up-scaled:\n\t'auto' no preference;\n\t'optimizeQuality' smooth;\n\t'optimizeSpeed' blocky.\nNote that this behaviour is not defined in the SVG 1.1 specification and not all browsers follow this interpretation.")); + +#if WITH_GTKMM_3_0 + _combo_image_rendering.set_valign(Gtk::ALIGN_CENTER); + grid_top->attach(_combo_image_rendering, 1, 3, 1, 1); +#else + grid_top->attach(_combo_image_rendering, 1, 2, 3, 4, + Gtk::EXPAND | Gtk::FILL, + Gtk::AttachOptions(), 0, 0 ); +#endif + + _label_image_rendering.set_mnemonic_widget(_combo_image_rendering); + + _combo_image_rendering.signal_changed().connect( + sigc::mem_fun(this, &ObjectProperties::_imageRenderingChanged) + ); /* Check boxes */ - contents->pack_start (HBoxCheck, FALSE, FALSE, 0); - CheckTable.set_border_width(0); - HBoxCheck.pack_start (CheckTable, TRUE, TRUE, 10); + Gtk::HBox *hb_checkboxes = Gtk::manage(new Gtk::HBox()); + contents->pack_start(*hb_checkboxes, FALSE, FALSE, 0); + +#if WITH_GTKMM_3_0 + Gtk::Grid *grid_cb = Gtk::manage(new Gtk::Grid()); + grid_cb->set_row_homogeneous(); + grid_cb->set_column_homogeneous(true); +#else + Gtk::Table *grid_cb = Gtk::manage(new Gtk::Table(1, 2, true)); +#endif + + grid_cb->set_border_width(4); + hb_checkboxes->pack_start(*grid_cb, true, true, 0); /* Hide */ - CBHide.set_tooltip_text (_("Check to make the object invisible")); - CheckTable.attach (CBHide, 0, 1, 0, 1, + _cb_hide.set_tooltip_text (_("Check to make the object invisible")); + +#if WITH_GTKMM_3_0 + _cb_hide.set_hexpand(); + _cb_hide.set_valign(Gtk::ALIGN_CENTER); + grid_cb->attach(_cb_hide, 0, 0, 1, 1); +#else + grid_cb->attach(_cb_hide, 0, 1, 0, 1, Gtk::EXPAND | Gtk::FILL, Gtk::AttachOptions(), 0, 0 ); - CBHide.signal_toggled().connect(sigc::mem_fun(this, &ObjectProperties::hidden_toggled)); +#endif + + _cb_hide.signal_toggled().connect(sigc::mem_fun(this, &ObjectProperties::_hiddenToggled)); /* Lock */ // TRANSLATORS: "Lock" is a verb here - CBLock.set_tooltip_text (_("Check to make the object insensitive (not selectable by mouse)")); - CheckTable.attach (CBLock, 1, 2, 0, 1, - Gtk::EXPAND | Gtk::FILL, - Gtk::AttachOptions(), 0, 0 ); - CBLock.signal_toggled().connect(sigc::mem_fun(this, &ObjectProperties::sensitivity_toggled)); + _cb_lock.set_tooltip_text(_("Check to make the object insensitive (not selectable by mouse)")); + +#if WITH_GTKMM_3_0 + _cb_lock.set_hexpand(); + _cb_lock.set_valign(Gtk::ALIGN_CENTER); + grid_cb->attach(_cb_lock, 1, 0, 1, 1); +#else + grid_cb->attach(_cb_lock, 1, 2, 0, 1, + Gtk::EXPAND | Gtk::FILL, + Gtk::AttachOptions(), 0, 0 ); +#endif + + _cb_lock.signal_toggled().connect(sigc::mem_fun(this, &ObjectProperties::_sensitivityToggled)); /* Button for setting the object's id, label, title and description. */ - HBoxCheck.pack_start (BSet, TRUE, TRUE, 10); - BSet.signal_clicked().connect(sigc::mem_fun(this, &ObjectProperties::label_changed)); + Gtk::Button *btn_set = Gtk::manage(new Gtk::Button(_("_Set"), 1)); +#if WITH_GTKMM_3_0 + btn_set->set_hexpand(); + btn_set->set_valign(Gtk::ALIGN_CENTER); + grid_cb->attach(*btn_set, 2, 0, 1, 1); +#else + grid_cb->attach(*btn_set, 2, 3, 0, 1, + Gtk::EXPAND | Gtk::FILL, + Gtk::AttachOptions(), 0, 0 ); +#endif + + btn_set->signal_clicked().connect(sigc::mem_fun(this, &ObjectProperties::_labelChanged)); /* Create the frame for interactivity options */ - EInteractivity.set_label_widget (LabelInteractivity); - contents->pack_start (EInteractivity, FALSE, FALSE, 0); - show_all (); - widget_setup(); + Gtk::Label *label_interactivity = Gtk::manage(new Gtk::Label(_("_Interactivity"), 1)); + _exp_interactivity.set_label_widget(*label_interactivity); + contents->pack_start(_exp_interactivity, FALSE, FALSE, 0); + + show_all(); + update(); } -void ObjectProperties::widget_setup(void) +void ObjectProperties::update() { - if (blocked || !desktop) - { + if (_blocked || !_desktop) { return; } - if (SP_ACTIVE_DESKTOP != desktop) - { + if (SP_ACTIVE_DESKTOP != _desktop) { return; } - Inkscape::Selection *selection = sp_desktop_selection (SP_ACTIVE_DESKTOP); + Inkscape::Selection *selection = sp_desktop_selection(SP_ACTIVE_DESKTOP); Gtk::Box *contents = _getContents(); if (!selection->singleItem()) { contents->set_sensitive (false); - CurrentItem = NULL; + _current_item = NULL; //no selection anymore or multiple objects selected, means that we need //to close the connections to the previously selected object - attrTable.clear(); + _attr_table->clear(); return; } else { contents->set_sensitive (true); } SPItem *item = selection->singleItem(); - if (CurrentItem == item) + if (_current_item == item) { //otherwise we would end up wasting resources through the modify selection - //callback when moving an object (endlessly setting the labels and recreating attrTable) + //callback when moving an object (endlessly setting the labels and recreating _attr_table) return; } - blocked = true; + _blocked = true; - CBLock.set_active (item->isLocked()); /* Sensitive */ - CBHide.set_active (item->isExplicitlyHidden()); /* Hidden */ + _cb_lock.set_active(item->isLocked()); /* Sensitive */ + _cb_hide.set_active(item->isExplicitlyHidden()); /* Hidden */ if (item->cloned) { /* ID */ - EntryID.set_text (""); - EntryID.set_sensitive (FALSE); - LabelID.set_text (_("Ref")); + _entry_id.set_text(""); + _entry_id.set_sensitive(FALSE); + _label_id.set_text(_("Ref")); /* Label */ - EntryLabel.set_text (""); - EntryLabel.set_sensitive (FALSE); - LabelLabel.set_text (_("Ref")); + _entry_label.set_text(""); + _entry_label.set_sensitive(FALSE); + _label_label.set_text(_("Ref")); } else { SPObject *obj = static_cast<SPObject*>(item); /* ID */ - EntryID.set_text (obj->getId()); - EntryID.set_sensitive (TRUE); - LabelID.set_markup_with_mnemonic (_("_ID:")); + _entry_id.set_text(obj->getId()); + _entry_id.set_sensitive(TRUE); + _label_id.set_markup_with_mnemonic(_("_ID:") + Glib::ustring(" ")); /* Label */ - EntryLabel.set_text(obj->defaultLabel()); - EntryLabel.set_sensitive (TRUE); + _entry_label.set_text(obj->defaultLabel()); + _entry_label.set_sensitive(TRUE); /* Title */ gchar *title = obj->title(); if (title) { - EntryTitle.set_text(title); + _entry_title.set_text(title); g_free(title); } else { - EntryTitle.set_text(""); + _entry_title.set_text(""); + } + _entry_title.set_sensitive(TRUE); + + /* Image Rendering */ + if (SP_IS_IMAGE(item)) { + _combo_image_rendering.show(); + _label_image_rendering.show(); + char const *str = obj->getStyleProperty( "image-rendering", "auto" ); + if (strcmp( str, "auto" ) == 0) { + _combo_image_rendering.set_active(0); + } else if (strcmp(str, "optimizeQuality") == 0) { + _combo_image_rendering.set_active(1); + } else { + _combo_image_rendering.set_active(2); + } + } else { + _combo_image_rendering.hide(); + _combo_image_rendering.unset_active(); + _label_image_rendering.hide(); } - EntryTitle.set_sensitive(TRUE); /* Description */ gchar *desc = obj->desc(); if (desc) { - TextViewDescription.get_buffer()->set_text(desc); + _tv_description.get_buffer()->set_text(desc); g_free(desc); } else { - TextViewDescription.get_buffer()->set_text(""); + _tv_description.get_buffer()->set_text(""); } - FrameTextDescription.set_sensitive(TRUE); + _ft_description.set_sensitive(TRUE); - if (CurrentItem == NULL) - { - attrTable.set_object(obj, int_labels, int_labels, (GtkWidget*)EInteractivity.gobj()); - } - else - { - attrTable.change_object(obj); + if (_current_item == NULL) { + _attr_table->set_object(obj, _int_labels, _int_attrs, (GtkWidget*) _exp_interactivity.gobj()); + } else { + _attr_table->change_object(obj); } - attrTable.show_all(); + _attr_table->show_all(); } - CurrentItem = item; - blocked = false; + _current_item = item; + _blocked = false; } -void ObjectProperties::label_changed(void) +void ObjectProperties::_labelChanged() { - if (blocked) - { + if (_blocked) { return; } SPItem *item = sp_desktop_selection(SP_ACTIVE_DESKTOP)->singleItem(); g_return_if_fail (item != NULL); - blocked = true; + _blocked = true; /* Retrieve the label widget for the object's id */ - gchar *id = g_strdup(EntryID.get_text().c_str()); - g_strcanon (id, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.:", '_'); - if (!strcmp (id, item->getId())) { - LabelID.set_markup_with_mnemonic(_("_ID:")); + gchar *id = g_strdup(_entry_id.get_text().c_str()); + g_strcanon(id, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.:", '_'); + if (strcmp(id, item->getId()) == 0) { + _label_id.set_markup_with_mnemonic(_("_ID:")); } else if (!*id || !isalnum (*id)) { - LabelID.set_text (_("Id invalid! ")); + _label_id.set_text(_("Id invalid! ")); } else if (SP_ACTIVE_DOCUMENT->getObjectById(id) != NULL) { - LabelID.set_text (_("Id exists! ")); + _label_id.set_text(_("Id exists! ")); } else { SPException ex; - LabelID.set_markup_with_mnemonic(_("_ID:")); - SP_EXCEPTION_INIT (&ex); + _label_id.set_markup_with_mnemonic(_("_ID:")); + SP_EXCEPTION_INIT(&ex); item->setAttribute("id", id, &ex); DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_DIALOG_ITEM, _("Set object ID")); } - g_free (id); + g_free(id); /* Retrieve the label widget for the object's label */ - Glib::ustring label = EntryLabel.get_text(); - g_assert(!label.empty()); + Glib::ustring label = _entry_label.get_text(); /* Give feedback on success of setting the drawing object's label * using the widget's label text */ SPObject *obj = static_cast<SPObject*>(item); - if (label.compare (obj->defaultLabel())) { + if (label.compare(obj->defaultLabel())) { obj->setLabel(label.c_str()); DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_DIALOG_ITEM, _("Set object label")); } /* Retrieve the title */ - if (obj->setTitle(EntryTitle.get_text().c_str())) + if (obj->setTitle(_entry_title.get_text().c_str())) { DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_DIALOG_ITEM, _("Set object title")); + } /* Retrieve the description */ Gtk::TextBuffer::iterator start, end; - TextViewDescription.get_buffer()->get_bounds(start, end); - Glib::ustring desc = TextViewDescription.get_buffer()->get_text(start, end, TRUE); - if (obj->setDesc(desc.c_str())) + _tv_description.get_buffer()->get_bounds(start, end); + Glib::ustring desc = _tv_description.get_buffer()->get_text(start, end, TRUE); + if (obj->setDesc(desc.c_str())) { DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_DIALOG_ITEM, _("Set object description")); + } - blocked = false; + _blocked = false; } -void ObjectProperties::sensitivity_toggled (void) +void ObjectProperties::_imageRenderingChanged() { - if (blocked) - { + if (_blocked) { return; } - + SPItem *item = sp_desktop_selection(SP_ACTIVE_DESKTOP)->singleItem(); g_return_if_fail (item != NULL); - blocked = true; - item->setLocked(CBLock.get_active()); + _blocked = true; + + Glib::ustring scale = _combo_image_rendering.get_active_text(); + + // We should unset if the parent computed value is auto and the desired value is auto. + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_set_property(css, "image-rendering", scale.c_str()); + Inkscape::XML::Node *image_node = item->getRepr(); + if( image_node ) { + sp_repr_css_change(image_node, css, "style"); + } + sp_repr_css_attr_unref( css ); + + _blocked = false; +} + +void ObjectProperties::_sensitivityToggled() +{ + if (_blocked) { + return; + } + + SPItem *item = sp_desktop_selection(SP_ACTIVE_DESKTOP)->singleItem(); + g_return_if_fail(item != NULL); + + _blocked = true; + item->setLocked(_cb_lock.get_active()); DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_DIALOG_ITEM, - CBLock.get_active()? _("Lock object") : _("Unlock object")); - blocked = false; + _cb_lock.get_active() ? _("Lock object") : _("Unlock object")); + _blocked = false; } -void ObjectProperties::hidden_toggled(void) +void ObjectProperties::_hiddenToggled() { - if (blocked) - { + if (_blocked) { return; } SPItem *item = sp_desktop_selection(SP_ACTIVE_DESKTOP)->singleItem(); - g_return_if_fail (item != NULL); + g_return_if_fail(item != NULL); - blocked = true; - item->setExplicitlyHidden(CBHide.get_active()); + _blocked = true; + item->setExplicitlyHidden(_cb_hide.get_active()); DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_DIALOG_ITEM, - CBHide.get_active()? _("Hide object") : _("Unhide object")); - blocked = false; + _cb_hide.get_active() ? _("Hide object") : _("Unhide object")); + _blocked = false; } -void ObjectProperties::setDesktop(SPDesktop *desktop) +void ObjectProperties::_setDesktop(SPDesktop *desktop) { Panel::setDesktop(desktop); - deskTrack.setBase(desktop); + _desktop_tracker.setBase(desktop); } -void ObjectProperties::setTargetDesktop(SPDesktop *desktop) +void ObjectProperties::_setTargetDesktop(SPDesktop *desktop) { - if (this->desktop != desktop) { - if (this->desktop) { - // selectModifiedConn.disconnect(); - subselChangedConn.disconnect(); - selectChangedConn.disconnect(); + if (this->_desktop != desktop) { + if (this->_desktop) { + _subselection_changed_connection.disconnect(); + _selection_changed_connection.disconnect(); } - this->desktop = desktop; + this->_desktop = desktop; if (desktop && desktop->selection) { - selectChangedConn = desktop->selection->connectChanged(sigc::hide(sigc::mem_fun(*this, &ObjectProperties::widget_setup))); - subselChangedConn = desktop->connectToolSubselectionChanged(sigc::hide(sigc::mem_fun(*this, &ObjectProperties::widget_setup))); - - //// Must check flags, so can't call widget_setup() directly. - // selectModifiedConn = desktop->selection->connectModified(sigc::hide<0>(sigc::mem_fun(*this, &ObjectProperties::selectionModifiedCB))); + _selection_changed_connection = desktop->selection->connectChanged( + sigc::hide(sigc::mem_fun(*this, &ObjectProperties::update)) + ); + _subselection_changed_connection = desktop->connectToolSubselectionChanged( + sigc::hide(sigc::mem_fun(*this, &ObjectProperties::update)) + ); } - widget_setup(); + update(); } } -// void ObjectProperties::selectionModifiedCB( guint flags ) -// { - // if (flags & ( SP_OBJECT_MODIFIED_FLAG | - // SP_OBJECT_PARENT_MODIFIED_FLAG | - // SP_OBJECT_STYLE_MODIFIED_FLAG) ) { - // widget_setup(); - // } -// } - } } } diff --git a/src/ui/dialog/object-properties.h b/src/ui/dialog/object-properties.h index d9d1a3fdd..093f273f6 100644 --- a/src/ui/dialog/object-properties.h +++ b/src/ui/dialog/object-properties.h @@ -1,31 +1,62 @@ /** * @file Object properties dialog. */ -/* Author: - * Lauris Kaplinski <lauris@ximian.com> - * Kris De Gussem <Kris.DeGussem@gmail.com> +/* + * Inkscape, an Open Source vector graphics editor + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * - * Copyright (C) 2001 Ximian, Inc. - * Copyright (C) 2012 Authors - * Released under GNU GPL, read the file 'COPYING' for more information + * Copyright (C) 2012 Kris De Gussem <Kris.DeGussem@gmail.com> + * c++version based on former C-version (GPL v2) with authors: + * Lauris Kaplinski <lauris@kaplinski.com> + * bulia byak <buliabyak@users.sf.net> + * Johan Engelen <goejendaagh@zonnet.nl> + * Abhishek Sharma */ #ifndef SEEN_DIALOGS_ITEM_PROPERTIES_H #define SEEN_DIALOGS_ITEM_PROPERTIES_H +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + #include "ui/widget/panel.h" #include "ui/widget/frame.h" + +#include <gtkmm/checkbutton.h> #include <gtkmm/entry.h> #include <gtkmm/expander.h> #include <gtkmm/frame.h> #include <gtkmm/textview.h> +#include <gtkmm/comboboxtext.h> #include "ui/dialog/desktop-tracker.h" -#include "widgets/sp-attribute-widget.h" +class SPAttributeTable; class SPDesktop; class SPItem; +namespace Gtk { +#if WITH_GTKMM_3_0 +class Grid; +#else +class Table; +#endif +} + namespace Inkscape { namespace UI { namespace Dialog { @@ -38,85 +69,64 @@ namespace Dialog { */ class ObjectProperties : public Widget::Panel { public: - ObjectProperties (); - ~ObjectProperties (); + ObjectProperties(); + ~ObjectProperties(); static ObjectProperties &getInstance() { return *new ObjectProperties(); } - /** - * Updates entries and other child widgets on selection change, object modification, etc. - */ - void widget_setup(void); + /// Updates entries and other child widgets on selection change, object modification, etc. + void update(); private: - bool blocked; - SPItem *CurrentItem; //to store the current item, for not wasting resources - std::vector<Glib::ustring> int_labels; - - Gtk::Table TopTable; //the table with the object properties - Gtk::Label LabelID; //the label for the object ID - Gtk::Entry EntryID; //the entry for the object ID - Gtk::Label LabelLabel; //the label for the object label - Gtk::Entry EntryLabel; //the entry for the object label - Gtk::Label LabelTitle; //the label for the object title - Gtk::Entry EntryTitle; //the entry for the object title - - Gtk::Label LabelDescription; //the label for the object description - UI::Widget::Frame FrameDescription; //the frame for the object description - Gtk::Frame FrameTextDescription; //the frame for the text of the object description - Gtk::TextView TextViewDescription; //the text view object showing the object description - - Gtk::HBox HBoxCheck; // the HBox for the check boxes - Gtk::Table CheckTable; //the table for the check boxes - Gtk::CheckButton CBHide; //the check button hide - Gtk::CheckButton CBLock; //the check button lock - Gtk::Button BSet; //the button set - - Gtk::Label LabelInteractivity; //the label for interactivity - Gtk::Expander EInteractivity; //the label for interactivity - SPAttributeTable attrTable; //the widget for showing the on... names at the bottom - - SPDesktop *desktop; - DesktopTracker deskTrack; - sigc::connection desktopChangeConn; - sigc::connection selectChangedConn; - sigc::connection subselChangedConn; - - /** - * Constructor auxiliary function creating the child widgets. - */ - void MakeWidget(void); - - /** - * Sets object properties (ID, label, title, description) on user input. - */ - void label_changed(void); - - /** - * Callback for checkbox Lock. - */ - void sensitivity_toggled (void); - - /** - * Callback for checkbox Hide. - */ - void hidden_toggled(void); + bool _blocked; + SPItem *_current_item; //to store the current item, for not wasting resources + std::vector<Glib::ustring> _int_attrs; + std::vector<Glib::ustring> _int_labels; + + Gtk::Label _label_id; //the label for the object ID + Gtk::Entry _entry_id; //the entry for the object ID + Gtk::Label _label_label; //the label for the object label + Gtk::Entry _entry_label; //the entry for the object label + Gtk::Label _label_title; //the label for the object title + Gtk::Entry _entry_title; //the entry for the object title + Gtk::Label _label_image_rendering; // the label for 'image-rendering' + Gtk::ComboBoxText _combo_image_rendering; // the combo box text for 'image-rendering' - /* - * On signal modified, invokes an update. - */ - //void selectionModifiedCB( guint flags ); + Gtk::Frame _ft_description; //the frame for the text of the object description + Gtk::TextView _tv_description; //the text view object showing the object description + + Gtk::CheckButton _cb_hide; //the check button hide + Gtk::CheckButton _cb_lock; //the check button lock + + Gtk::Expander _exp_interactivity; //the expander for interactivity + SPAttributeTable *_attr_table; //the widget for showing the on... names at the bottom - /** - * Can be invoked for setting the desktop. Currently not used. - */ - void setDesktop(SPDesktop *desktop); + SPDesktop *_desktop; + DesktopTracker _desktop_tracker; + sigc::connection _desktop_changed_connection; + sigc::connection _selection_changed_connection; + sigc::connection _subselection_changed_connection; - /** - * Is invoked by the desktop tracker when the desktop changes. - */ - void setTargetDesktop(SPDesktop *desktop); + /// Constructor auxiliary function creating the child widgets. + void _init(); + /// Sets object properties (ID, label, title, description) on user input. + void _labelChanged(); + + /// Callback for 'image-rendering'. + void _imageRenderingChanged(); + + /// Callback for checkbox Lock. + void _sensitivityToggled(); + + /// Callback for checkbox Hide. + void _hiddenToggled(); + + /// Can be invoked for setting the desktop. Currently not used. + void _setDesktop(SPDesktop *desktop); + + /// Is invoked by the desktop tracker when the desktop changes. + void _setTargetDesktop(SPDesktop *desktop); }; } diff --git a/src/ui/dialog/ocaldialogs.cpp b/src/ui/dialog/ocaldialogs.cpp index 9dccb9c85..f676e75fd 100644 --- a/src/ui/dialog/ocaldialogs.cpp +++ b/src/ui/dialog/ocaldialogs.cpp @@ -16,13 +16,14 @@ # include <config.h> #endif +#include "ocaldialogs.h" + #include <stdio.h> // rename() #include <unistd.h> // close() #include <errno.h> // errno #include <string.h> // strerror() #include "path-prefix.h" -#include "ocaldialogs.h" #include "filedialogimpl-gtkmm.h" #include "interface.h" #include "gc-core.h" @@ -33,10 +34,17 @@ #include <gtkmm/notebook.h> #include <gtkmm/spinner.h> #include <gtkmm/stock.h> -#include <glibmm/i18n.h> #include <gdkmm/general.h> #include <libxml/tree.h> +#include <glibmm/convert.h> +#include <glibmm/fileutils.h> +#include <glibmm/i18n.h> +#include <glibmm/main.h> +#include <glibmm/markup.h> +#include <glibmm/miscutils.h> +#include "ui/icon-names.h" + namespace Inkscape { namespace UI @@ -139,7 +147,7 @@ bool ExportDialog::show() { set_modal (TRUE); //Window - sp_transientize((GtkWidget *)gobj()); //Make transient + sp_transientize(GTK_WIDGET(gobj())); //Make transient gint b = run(); //Dialog hide(); @@ -244,7 +252,7 @@ bool ExportPasswordDialog::show() { set_modal (TRUE); //Window - sp_transientize((GtkWidget *)gobj()); //Make transient + sp_transientize(GTK_WIDGET(gobj())); //Make transient gint b = run(); //Dialog hide(); @@ -307,33 +315,56 @@ LoadingBox::LoadingBox() : Gtk::EventBox() set_visible_window(false); draw_spinner = false; spinner_step = 0; + +#if WITH_GTKMM_3_0 + signal_draw().connect(sigc::mem_fun(*this, &LoadingBox::_on_draw), false); +#else signal_expose_event().connect(sigc::mem_fun(*this, &LoadingBox::_on_expose_event), false); +#endif } +#if !WITH_GTKMM_3_0 bool LoadingBox::_on_expose_event(GdkEventExpose* /*event*/) { Cairo::RefPtr<Cairo::Context> cr = get_window()->create_cairo_context(); + return _on_draw(cr); +} +#endif + +bool LoadingBox::_on_draw(const Cairo::RefPtr<Cairo::Context> & +#if WITH_GTKMM_3_0 +cr +#endif +) +{ // Draw shadow int x = get_allocation().get_x(); int y = get_allocation().get_y(); int width = get_allocation().get_width(); int height = get_allocation().get_height(); +#if WITH_GTKMM_3_0 + get_style_context()->render_frame(cr, x, y, width, height); +#else get_style()->paint_shadow(get_window(), get_state(), Gtk::SHADOW_IN, Gdk::Rectangle(x, y, width, height), *this, Glib::ustring("viewport"), x, y, width, height); +#endif if (draw_spinner) { int spinner_size = 16; int spinner_x = x + (width - spinner_size) / 2; int spinner_y = y + (height - spinner_size) / 2; - // FIXME: Gtk::Style::paint_spinner not yet in gtkmm +#if WITH_GTKMM_3_0 + get_style_context()->render_activity(cr, spinner_x, spinner_y, spinner_size, spinner_size); +#else gtk_paint_spinner(gtk_widget_get_style(GTK_WIDGET(gobj())), gtk_widget_get_window(GTK_WIDGET(gobj())), gtk_widget_get_state(GTK_WIDGET(gobj())), NULL, GTK_WIDGET(gobj()), NULL, spinner_step, spinner_x, spinner_y, spinner_size, spinner_size); +#endif } return false; @@ -403,7 +434,11 @@ PreviewWidget::PreviewWidget() : Gtk::VBox(false, 12) box_loading->set_size_request(90, 90); set_border_width(12); +#if WITH_GTKMM_3_0 + signal_draw().connect(sigc::mem_fun(*this, &PreviewWidget::_on_draw), false); +#else signal_expose_event().connect(sigc::mem_fun(*this, &PreviewWidget::_on_expose_event), false); +#endif clear(); } @@ -447,19 +482,34 @@ void PreviewWidget::clear() image->hide(); } +#if !WITH_GTKMM_3_0 bool PreviewWidget::_on_expose_event(GdkEventExpose* /*event*/) { Cairo::RefPtr<Cairo::Context> cr = get_window()->create_cairo_context(); + return _on_draw(cr); +} +#endif + +bool PreviewWidget::_on_draw(const Cairo::RefPtr<Cairo::Context>& cr) +{ // Draw background int x = get_allocation().get_x(); int y = get_allocation().get_y(); int width = get_allocation().get_width(); int height = get_allocation().get_height(); - Gdk::Color background_fill = get_style()->get_base(get_state()); +#if WITH_GTKMM_3_0 + Gdk::RGBA background_fill; + get_style_context()->lookup_color("base_color", background_fill); + cr->rectangle(x, y, width, height); + Gdk::Cairo::set_source_rgba(cr, background_fill); +#else + Gdk::Color background_fill = get_style()->get_base(get_state()); cr->rectangle(x, y, width, height); Gdk::Cairo::set_source_color(cr, background_fill); +#endif + cr->fill(); return false; @@ -523,13 +573,14 @@ void StatusWidget::end_process() clear(); } +#if !GTK_CHECK_VERSION(3,6,0) SearchEntry::SearchEntry() : Gtk::Entry() { signal_changed().connect(sigc::mem_fun(*this, &SearchEntry::_on_changed)); signal_icon_press().connect(sigc::mem_fun(*this, &SearchEntry::_on_icon_pressed)); - set_icon_from_stock(Gtk::Stock::FIND, Gtk::ENTRY_ICON_PRIMARY); - gtk_entry_set_icon_from_stock(gobj(), GTK_ENTRY_ICON_SECONDARY, NULL); + set_icon_from_icon_name(INKSCAPE_ICON("edit-find"), Gtk::ENTRY_ICON_PRIMARY); + gtk_entry_set_icon_from_icon_name(gobj(), GTK_ENTRY_ICON_SECONDARY, NULL); } void SearchEntry::_on_icon_pressed(Gtk::EntryIconPosition icon_position, const GdkEventButton* /*event*/) @@ -546,36 +597,58 @@ void SearchEntry::_on_icon_pressed(Gtk::EntryIconPosition icon_position, const G void SearchEntry::_on_changed() { if (get_text().empty()) { - gtk_entry_set_icon_from_stock(gobj(), GTK_ENTRY_ICON_SECONDARY, NULL); + gtk_entry_set_icon_from_icon_name(gobj(), GTK_ENTRY_ICON_SECONDARY, NULL); } else { - set_icon_from_stock(Gtk::Stock::CLEAR, Gtk::ENTRY_ICON_SECONDARY); + set_icon_from_icon_name(INKSCAPE_ICON("edit-clear"), Gtk::ENTRY_ICON_SECONDARY); } } +#endif + BaseBox::BaseBox() : Gtk::EventBox() { +#if WITH_GTKMM_3_0 + signal_draw().connect(sigc::mem_fun(*this, &BaseBox::_on_draw), false); +#else signal_expose_event().connect(sigc::mem_fun(*this, &BaseBox::_on_expose_event), false); +#endif set_visible_window(false); } +#if !WITH_GTKMM_3_0 bool BaseBox::_on_expose_event(GdkEventExpose* /*event*/) { Cairo::RefPtr<Cairo::Context> cr = get_window()->create_cairo_context(); + return _on_draw(cr); +} +#endif + +bool BaseBox::_on_draw(const Cairo::RefPtr<Cairo::Context>& cr) +{ // Draw background and shadow int x = get_allocation().get_x(); int y = get_allocation().get_y(); int width = get_allocation().get_width(); int height = get_allocation().get_height(); - Gdk::Color background_fill = get_style()->get_base(get_state()); +#if WITH_GTKMM_3_0 + Gdk::RGBA background_fill; + get_style_context()->lookup_color("base_color", background_fill); + cr->rectangle(x, y, width, height); + Gdk::Cairo::set_source_rgba(cr, background_fill); + cr->fill(); + get_style_context()->render_frame(cr, x, y, width, height); +#else + Gdk::Color background_fill = get_style()->get_base(get_state()); cr->rectangle(x, y, width, height); Gdk::Cairo::set_source_color(cr, background_fill); cr->fill(); - + get_style()->paint_shadow(get_window(), get_state(), Gtk::SHADOW_IN, Gdk::Rectangle(x, y, width, height), *this, Glib::ustring("viewport"), x, y, width, height); +#endif return false; } @@ -591,12 +664,26 @@ LogoArea::LogoArea() : Gtk::EventBox() logo_mask = Cairo::ImageSurface::create(Cairo::FORMAT_ARGB32, 1,1); draw_logo = false; } + +#if WITH_GTKMM_3_0 + signal_draw().connect(sigc::mem_fun(*this, &LogoArea::_on_draw)); +#else signal_expose_event().connect(sigc::mem_fun(*this, &LogoArea::_on_expose_event)); +#endif set_visible_window(false); } +#if !WITH_GTKMM_3_0 bool LogoArea::_on_expose_event(GdkEventExpose* /*event*/) { + Cairo::RefPtr<Cairo::Context> cr = get_window()->create_cairo_context(); + + return _on_draw(cr); +} +#endif + +bool LogoArea::_on_draw(const Cairo::RefPtr<Cairo::Context>& cr) +{ if (draw_logo) { int x = get_allocation().get_x(); int y = get_allocation().get_y(); @@ -605,13 +692,17 @@ bool LogoArea::_on_expose_event(GdkEventExpose* /*event*/) int x_logo = x + (width - 220) / 2; int y_logo = y + (height - 76) / 2; - Cairo::RefPtr<Cairo::Context> cr = get_window()->create_cairo_context(); - // Draw logo, we mask [read fill] it with the mid colour from the // user's GTK theme +#if WITH_GTKMM_3_0 + // For GTK+ 3, use grey + Gdk::RGBA logo_fill("grey"); + Gdk::Cairo::set_source_rgba(cr, logo_fill); +#else Gdk::Color logo_fill = get_style()->get_mid(get_state()); - Gdk::Cairo::set_source_color(cr, logo_fill); +#endif + cr->mask(logo_mask, x_logo, y_logo); } @@ -830,7 +921,7 @@ void ImportDialog::on_image_downloaded(Glib::ustring path, bool success) m_signal_response.emit(path); widget_status->set_info(_("Clipart downloaded successfully")); } catch(Glib::Error) { - success = false; + // success = false; //has no effect, value not returned } cancelled_image = false; @@ -854,7 +945,7 @@ void ImportDialog::on_thumbnail_downloaded(Glib::ustring path, bool success) widget_status->clear(); preview_files->set_image(path); } catch(Glib::Error) { - success = false; + // success = false; //has no effect, value not returned } cancelled_thumbnail = false; @@ -881,44 +972,40 @@ void SearchResultList::populate_from_xml(xmlNode * a_node) for (xmlNode *cur_node = a_node; cur_node; cur_node = cur_node->next) { // Get items information - if (strcmp((const char*)cur_node->name, "rss")) // Avoid the root + if (strcmp(reinterpret_cast<const char*>(cur_node->name), "rss")) // Avoid the root if (cur_node->type == XML_ELEMENT_NODE && - (cur_node->parent->name && !strcmp((const char*)cur_node->parent->name, "item"))) + (cur_node->parent->name && !strcmp(reinterpret_cast<const char*>(cur_node->parent->name), "item"))) { - if (!strcmp((const char*)cur_node->name, "title")) + if (!strcmp(reinterpret_cast<const char*>(cur_node->name), "title")) { -#if WITH_GTKMM_2_24 row_num = append(""); -#else - row_num = append_text(""); -#endif xmlChar *xml_title = xmlNodeGetContent(cur_node); - char* title = (char*) xml_title; + char* title = reinterpret_cast<char*>(xml_title); set_text(row_num, RESULTS_COLUMN_TITLE, title); xmlFree(title); } - else if (!strcmp((const char*)cur_node->name, "pubDate")) + else if (!strcmp(reinterpret_cast<const char*>(cur_node->name), "pubDate")) { xmlChar *xml_date = xmlNodeGetContent(cur_node); - char* date = (char*) xml_date; + char* date = reinterpret_cast<char*>(xml_date); set_text(row_num, RESULTS_COLUMN_DATE, date); xmlFree(xml_date); } - else if (!strcmp((const char*)cur_node->name, "creator")) + else if (!strcmp(reinterpret_cast<const char*>(cur_node->name), "creator")) { xmlChar *xml_creator = xmlNodeGetContent(cur_node); - char* creator = (char*) xml_creator; + char* creator = reinterpret_cast<char*>(xml_creator); set_text(row_num, RESULTS_COLUMN_CREATOR, creator); xmlFree(xml_creator); } - else if (!strcmp((const char*)cur_node->name, "description")) + else if (!strcmp(reinterpret_cast<const char*>(cur_node->name), "description")) { xmlChar *xml_description = xmlNodeGetContent(cur_node); //char* final_description; - char* stripped_description = g_strstrip((char*) xml_description); + char* stripped_description = g_strstrip(reinterpret_cast<char*>(xml_description)); if (!strcmp(stripped_description, "")) { stripped_description = _("No description"); @@ -930,30 +1017,30 @@ void SearchResultList::populate_from_xml(xmlNode * a_node) set_text(row_num, RESULTS_COLUMN_DESCRIPTION, stripped_description); xmlFree(xml_description); } - else if (!strcmp((const char*)cur_node->name, "enclosure")) + else if (!strcmp(reinterpret_cast<const char*>(cur_node->name), "enclosure")) { - xmlChar *xml_url = xmlGetProp(cur_node, (xmlChar*) "url"); - char* url = (char*) xml_url; + xmlChar *xml_url = xmlGetProp(cur_node, reinterpret_cast<xmlChar const*>("url")); + char* url = reinterpret_cast<char*>(xml_url); char* filename = g_path_get_basename(url); set_text(row_num, RESULTS_COLUMN_URL, url); set_text(row_num, RESULTS_COLUMN_FILENAME, filename); xmlFree(xml_url); } - else if (!strcmp((const char*)cur_node->name, "thumbnail")) + else if (!strcmp(reinterpret_cast<const char*>(cur_node->name), "thumbnail")) { - xmlChar *xml_thumbnail_url = xmlGetProp(cur_node, (xmlChar*) "url"); - char* thumbnail_url = (char*) xml_thumbnail_url; + xmlChar *xml_thumbnail_url = xmlGetProp(cur_node, reinterpret_cast<xmlChar const*>("url")); + char* thumbnail_url = reinterpret_cast<char*>(xml_thumbnail_url); char* thumbnail_filename = g_path_get_basename(thumbnail_url); set_text(row_num, RESULTS_COLUMN_THUMBNAIL_URL, thumbnail_url); set_text(row_num, RESULTS_COLUMN_THUMBNAIL_FILENAME, thumbnail_filename); xmlFree(xml_thumbnail_url); } - else if (!strcmp((const char*)cur_node->name, "guid")) + else if (!strcmp(reinterpret_cast<const char*>(cur_node->name), "guid")) { xmlChar *xml_guid = xmlNodeGetContent(cur_node); - char* guid_url = (char*) xml_guid; + char* guid_url = reinterpret_cast<char*>(xml_guid); char* guid = g_path_get_basename(guid_url); set_text(row_num, RESULTS_COLUMN_GUID, guid); @@ -1007,7 +1094,12 @@ void ImportDialog::on_entry_search_activated() // Open the RSS feed Glib::RefPtr<Gio::File> xml_file = Gio::File::create_for_uri(xml_uri); - +#ifdef WIN32 + if (!xml_file->query_exists()) { + widget_status->set_error(_("Could not connect to the Open Clip Art Library")); + return; + } +#endif xml_file->load_contents_async( sigc::bind<Glib::RefPtr<Gio::File> , Glib::ustring>( sigc::mem_fun(*this, &ImportDialog::on_xml_file_read), @@ -1035,8 +1127,14 @@ void ImportDialog::on_xml_file_read(const Glib::RefPtr<Gio::AsyncResult>& result xmlDoc *doc = NULL; xmlNode *root_element = NULL; - doc = xmlReadMemory(data, (int) length, xml_uri.c_str(), NULL, - XML_PARSE_RECOVER + XML_PARSE_NOWARNING + XML_PARSE_NOERROR); + int parse_options = XML_PARSE_RECOVER + XML_PARSE_NOWARNING + XML_PARSE_NOERROR; // do not use XML_PARSE_NOENT ! see bug lp:1025185 + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + bool allowNetAccess = prefs->getBool("/options/externalresources/xml/allow_net_access", false); + if (!allowNetAccess) { + parse_options |= XML_PARSE_NONET; + } + + doc = xmlReadMemory(data, (int) length, xml_uri.c_str(), NULL, parse_options); if (doc == NULL) { // If nothing is returned, no results could be found @@ -1068,23 +1166,30 @@ void ImportDialog::on_xml_file_read(const Glib::RefPtr<Gio::AsyncResult>& result // free the document xmlFreeDoc(doc); - // free the global variables that may have been allocated by the parser - xmlCleanupParser(); } void ImportDialog::update_label_no_search_results() { Glib::ustring keywords = Glib::Markup::escape_text(entry_search->get_text()); - Gdk::Color grey = entry_search->get_style()->get_text_aa(entry_search->get_state()); + Glib::ustring msg_one = Glib::ustring::compose( _("No clipart named <b>%1</b> was found."), keywords); Glib::ustring msg_two = _("Please make sure all keywords are spelled correctly," " or try again with different keywords."); + +#if WITH_GTKMM_3_0 + Glib::ustring markup = Glib::ustring::compose( + "<span size=\"large\">%1</span>\n<span>%2</span>", + msg_one, msg_two); +#else + Gdk::Color grey = entry_search->get_style()->get_text_aa(entry_search->get_state()); Glib::ustring markup = Glib::ustring::compose( "<span size=\"large\">%1</span>\n<span color=\"%2\">%3</span>", msg_one, grey.to_string(), msg_two); +#endif + label_not_found->set_markup(markup); } @@ -1104,15 +1209,33 @@ ImportDialog::ImportDialog(Gtk::Window& parent_window, FileDialogType file_types // Creation Gtk::VBox *vbox = new Gtk::VBox(false, 0); + +#if WITH_GTKMM_3_0 + Gtk::ButtonBox *hbuttonbox_bottom = new Gtk::ButtonBox(); +#else Gtk::HButtonBox *hbuttonbox_bottom = new Gtk::HButtonBox(); +#endif + Gtk::HBox *hbox_bottom = new Gtk::HBox(false, 12); BaseBox *basebox_logo = new BaseBox(); BaseBox *basebox_no_search_results = new BaseBox(); label_not_found = new Gtk::Label(); label_description = new Gtk::Label(); + +#if GTK_CHECK_VERSION(3,6,0) + entry_search = new Gtk::SearchEntry(); +#else entry_search = new SearchEntry(); +#endif + button_search = new Gtk::Button(_("Search")); + +#if WITH_GTKMM_3_0 + Gtk::ButtonBox* hbuttonbox_search = new Gtk::ButtonBox(); +#else Gtk::HButtonBox* hbuttonbox_search = new Gtk::HButtonBox(); +#endif + Gtk::ScrolledWindow* scrolledwindow_preview = new Gtk::ScrolledWindow(); preview_files = new PreviewWidget(); /// Add the buttons in the bottom of the dialog @@ -1211,7 +1334,8 @@ ImportDialog::ImportDialog(Gtk::Window& parent_window, FileDialogType file_types */ ImportDialog::~ImportDialog() { - + // free the global variables that may have been allocated by the parser + xmlCleanupParser(); } /** diff --git a/src/ui/dialog/ocaldialogs.h b/src/ui/dialog/ocaldialogs.h index 9e471b7b5..e21030bcd 100644 --- a/src/ui/dialog/ocaldialogs.h +++ b/src/ui/dialog/ocaldialogs.h @@ -13,12 +13,27 @@ #ifndef __OCAL_DIALOG_H__ #define __OCAL_DIALOG_H__ +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + //Gtk includes #include <gtkmm/box.h> #include <gtkmm/eventbox.h> #include <gtkmm/listviewtext.h> #include <gtkmm/scrolledwindow.h> #include <gtkmm/window.h> + +#include <cairomm/refptr.h> + +#if GTK_CHECK_VERSION(3,6,0) +# include <gtkmm/searchentry.h> +#endif + #include <giomm/file.h> //Inkscape includes @@ -62,7 +77,7 @@ public: FileDialogBase(const Glib::ustring &title, Gtk::Window& /*parent*/) : Gtk::Window(Gtk::WINDOW_TOPLEVEL) { set_title(title); - sp_transientize((GtkWidget*) gobj()); + sp_transientize(GTK_WIDGET(gobj())); // Allow shrinking of window so labels wrap correctly set_resizable(true); @@ -272,7 +287,12 @@ private: unsigned int spinner_step; sigc::connection timeout; bool draw_spinner; + +#if !WITH_GTKMM_3_0 bool _on_expose_event(GdkEventExpose* event); +#endif + + bool _on_draw(const Cairo::RefPtr<Cairo::Context>& cr); bool on_timeout(); }; @@ -286,7 +306,6 @@ public: void hide_box_loading(); void set_image(std::string path); void clear(); - bool _on_expose_event(GdkEventExpose* event); private: LoadingBox* box_loading; @@ -295,6 +314,12 @@ private: WrapLabel* label_title; WrapLabel* label_description; WrapLabel* label_time; + +#if !WITH_GTKMM_3_0 + bool _on_expose_event(GdkEventExpose* event); +#endif + + bool _on_draw(const Cairo::RefPtr<Cairo::Context>& cr); }; /** @@ -316,6 +341,7 @@ public: Gtk::Label* label; }; +#if !GTK_CHECK_VERSION(3,6,0) /** * A Gtk::Entry with search & clear icons */ @@ -328,6 +354,7 @@ private: void _on_icon_pressed(Gtk::EntryIconPosition icon_position, const GdkEventButton* event); void _on_changed(); }; +#endif /** * A box which paints an overlay of the OCAL logo @@ -337,7 +364,10 @@ class LogoArea : public Gtk::EventBox public: LogoArea(); private: +#if !WITH_GTKMM_3_0 bool _on_expose_event(GdkEventExpose* event); +#endif + bool _on_draw(const Cairo::RefPtr<Cairo::Context>& cr); bool draw_logo; Cairo::RefPtr<Cairo::ImageSurface> logo_mask; }; @@ -350,7 +380,10 @@ class BaseBox : public Gtk::EventBox public: BaseBox(); private: +#if !WITH_GTKMM_3_0 bool _on_expose_event(GdkEventExpose* event); +#endif + bool _on_draw(const Cairo::RefPtr<Cairo::Context>& cr); }; enum { @@ -431,7 +464,13 @@ protected: private: Glib::ustring filename_image; Glib::ustring filename_thumbnail; + +#if GTK_CHECK_VERSION(3,6,0) + Gtk::SearchEntry *entry_search; +#else SearchEntry *entry_search; +#endif + LogoArea *drawingarea_logo; SearchResultList *list_results; PreviewWidget *preview_files; diff --git a/src/ui/dialog/pixelartdialog.cpp b/src/ui/dialog/pixelartdialog.cpp new file mode 100644 index 000000000..ce5b6584d --- /dev/null +++ b/src/ui/dialog/pixelartdialog.cpp @@ -0,0 +1,512 @@ +/** + * @file + * Pixel art tracing settings dialog - implementation. + */ +/* Authors: + * Bob Jamison <rjamison@titan.com> + * Stéphane Gimenez <dev@gim.name> + * Vinícius dos Santos Oliveira <vini.ipsmaker@gmail.com> + * Other dudes from The Inkscape Organization + * + * Copyright (C) 2004-2013 Authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#include "pixelartdialog.h" +#include <gtkmm/radiobutton.h> +#include <gtkmm/stock.h> +#include <gtkmm/messagedialog.h> + +#include <gtk/gtk.h> //for GTK_RESPONSE* types +#include <glibmm/i18n.h> + +#include "ui/widget/spinbutton.h" +#include "ui/widget/frame.h" + +#include "desktop.h" +#include "desktop-tracker.h" +#include "message-stack.h" +#include "selection.h" +#include "preferences.h" + +#include "sp-image.h" +#include "display/cairo-utils.h" +#include "libdepixelize/kopftracer2011.h" +#include <algorithm> +#include "document.h" +#include "xml/repr.h" +#include "xml/document.h" +#include "svg/svg.h" +#include "svg/svg-color.h" +#include "color.h" +#include "svg/css-ostringstream.h" +#include "document-undo.h" + +#ifdef HAVE_OPENMP +#include <omp.h> +#endif // HAVE_OPENMP + +namespace Inkscape { +namespace UI { +namespace Dialog { + +template<class T> +T move(T &obj) +{ +#ifdef LIBDEPIXELIZE_ENABLE_CPP11 + return std::move(obj); +#else + T ret; + std::swap(obj, ret); + return ret; +#endif // LIBDEPIXELIZE_ENABLE_CPP11 +} + +/** + * A dialog for adjusting pixel art -> vector tracing parameters + */ +class PixelArtDialogImpl : public PixelArtDialog +{ +public: + PixelArtDialogImpl(); + + ~PixelArtDialogImpl(); + +private: + void setDesktop(SPDesktop *desktop); + void setTargetDesktop(SPDesktop *desktop); + + //############ Events + + void responseCallback(int response_id); + + //############ UI Logic + + Tracer::Kopf2011::Options options(); + + void vectorize(); + void processLibdepixelize(SPImage *img); + void setDefaults(); + void updatePreview(); + + bool ignorePreview; + bool pendingPreview; + + //############ UI + + Gtk::HBox buttonsHBox; + + Gtk::Button *mainOkButton; + Gtk::Button *mainCancelButton; + Gtk::Button *mainResetButton; + + Gtk::VBox heuristicsVBox; + UI::Widget::Frame heuristicsFrame; + + Gtk::HBox curvesMultiplierHBox; + Gtk::Label curvesMultiplierLabel; + Inkscape::UI::Widget::SpinButton curvesMultiplierSpinner; + + Gtk::HBox islandsWeightHBox; + Gtk::Label islandsWeightLabel; + Inkscape::UI::Widget::SpinButton islandsWeightSpinner; + + Gtk::HBox sparsePixelsMultiplierHBox; + Gtk::Label sparsePixelsMultiplierLabel; + Inkscape::UI::Widget::SpinButton sparsePixelsMultiplierSpinner; + + Gtk::HBox sparsePixelsRadiusHBox; + Gtk::Label sparsePixelsRadiusLabel; + Inkscape::UI::Widget::SpinButton sparsePixelsRadiusSpinner; + + Gtk::VBox outputVBox; + UI::Widget::Frame outputFrame; + Gtk::RadioButtonGroup outputGroup; + + Gtk::RadioButton voronoiRadioButton; + Gtk::RadioButton noOptimizeRadioButton; +#if LIBDEPIXELIZE_INKSCAPE_ENABLE_SMOOTH + Gtk::RadioButton optimizeRadioButton; +#endif // LIBDEPIXELIZE_INKSCAPE_ENABLE_SMOOTH + + SPDesktop *desktop; + DesktopTracker deskTrack; + sigc::connection desktopChangeConn; +}; + +void PixelArtDialogImpl::setDesktop(SPDesktop *desktop) +{ + Panel::setDesktop(desktop); + deskTrack.setBase(desktop); +} + +void PixelArtDialogImpl::setTargetDesktop(SPDesktop *desktop) +{ + this->desktop = desktop; +} + +PixelArtDialogImpl::PixelArtDialogImpl() : + PixelArtDialog(), + ignorePreview(false), + pendingPreview(false) +{ + + Gtk::Box *contents = _getContents(); + + // Heuristics + { + curvesMultiplierLabel.set_label(_("_Curves (multiplier):")); + curvesMultiplierLabel.set_use_underline(true); + curvesMultiplierLabel.set_mnemonic_widget(curvesMultiplierSpinner); + curvesMultiplierLabel.set_tooltip_text(_("Favors connections that are part of a long curve")); + curvesMultiplierSpinner.set_increments(0.125, 0); + curvesMultiplierSpinner.set_digits(3); + curvesMultiplierSpinner.set_range(-10, 10); + curvesMultiplierSpinner.get_adjustment()->signal_value_changed() + .connect(sigc::mem_fun(*this, &PixelArtDialogImpl::updatePreview)); + + curvesMultiplierHBox.pack_start(curvesMultiplierLabel, false, false); + curvesMultiplierHBox.pack_end(curvesMultiplierSpinner, false, false); + heuristicsVBox.pack_start(curvesMultiplierHBox, false, false); + + islandsWeightLabel.set_label(_("_Islands (weight):")); + islandsWeightLabel.set_use_underline(true); + islandsWeightLabel.set_mnemonic_widget(islandsWeightSpinner); + islandsWeightLabel.set_tooltip_text(_("Avoid single disconnected pixels")); + + islandsWeightSpinner.set_tooltip_text(_("A constant vote value")); + islandsWeightSpinner.set_increments(1, 0); + islandsWeightSpinner.set_range(-20, 20); + islandsWeightSpinner.get_adjustment()->signal_value_changed() + .connect(sigc::mem_fun(*this, &PixelArtDialogImpl::updatePreview)); + + islandsWeightHBox.pack_start(islandsWeightLabel, false, false); + islandsWeightHBox.pack_end(islandsWeightSpinner, false, false); + heuristicsVBox.pack_start(islandsWeightHBox, false, false); + + sparsePixelsRadiusLabel.set_label(_("Sparse pixels (window _radius):")); + sparsePixelsRadiusLabel.set_use_underline(true); + sparsePixelsRadiusLabel.set_mnemonic_widget(sparsePixelsRadiusSpinner); + + sparsePixelsRadiusSpinner.set_increments(1, 0); + sparsePixelsRadiusSpinner.set_range(2, 8); + sparsePixelsRadiusSpinner.get_adjustment()->signal_value_changed() + .connect(sigc::mem_fun(*this, &PixelArtDialogImpl::updatePreview)); + + sparsePixelsRadiusSpinner.set_tooltip_text(_("The radius of the window analyzed")); + sparsePixelsMultiplierLabel.set_label(_("Sparse pixels (_multiplier):")); + sparsePixelsMultiplierLabel.set_use_underline(true); + sparsePixelsMultiplierLabel.set_mnemonic_widget(sparsePixelsMultiplierSpinner); + + sparsePixelsMultiplierSpinner.set_increments(0.125, 0); + sparsePixelsMultiplierSpinner.set_digits(3); + sparsePixelsMultiplierSpinner.set_range(-10, 10); + sparsePixelsMultiplierSpinner.get_adjustment()->signal_value_changed() + .connect(sigc::mem_fun(*this, &PixelArtDialogImpl::updatePreview)); + + { + char const *str = _("Favors connections that are part of foreground color"); + sparsePixelsRadiusLabel.set_tooltip_text(str); + sparsePixelsMultiplierLabel.set_tooltip_text(str); + } + + { + char const *str = _("The heuristic computed vote will be multiplied by this value"); + curvesMultiplierSpinner.set_tooltip_text(str); + sparsePixelsMultiplierSpinner.set_tooltip_text(str); + } + + sparsePixelsRadiusHBox.pack_start(sparsePixelsRadiusLabel, false, false); + sparsePixelsRadiusHBox.pack_end(sparsePixelsRadiusSpinner, false, false); + heuristicsVBox.pack_start(sparsePixelsRadiusHBox, false, false); + + sparsePixelsMultiplierHBox.pack_start(sparsePixelsMultiplierLabel, false, false); + sparsePixelsMultiplierHBox.pack_end(sparsePixelsMultiplierSpinner, false, false); + heuristicsVBox.pack_start(sparsePixelsMultiplierHBox, false, false); + + heuristicsFrame.set_label(_("Heuristics")); + heuristicsFrame.add(heuristicsVBox); + contents->pack_start(heuristicsFrame, false, false); + } + + // Output + { + voronoiRadioButton.set_label(_("_Voronoi diagram")); + voronoiRadioButton.set_tooltip_text(_("Output composed of straight lines")); + voronoiRadioButton.set_use_underline(true); + outputGroup = voronoiRadioButton.get_group(); + + outputVBox.pack_start(voronoiRadioButton, false, false); + + noOptimizeRadioButton.set_label(_("Convert to _B-spline curves")); + noOptimizeRadioButton.set_tooltip_text(_("Preserve staircasing artifacts")); + noOptimizeRadioButton.set_use_underline(true); + noOptimizeRadioButton.set_group(outputGroup); + + outputVBox.pack_start(noOptimizeRadioButton, false, false); + +#if LIBDEPIXELIZE_INKSCAPE_ENABLE_SMOOTH + optimizeRadioButton.set_label(_("_Smooth curves")); + optimizeRadioButton.set_tooltip_text(_("The Kopf-Lischinski algorithm")); + optimizeRadioButton.set_use_underline(true); + optimizeRadioButton.set_group(outputGroup); + + outputVBox.pack_start(optimizeRadioButton, false, false); +#endif // LIBDEPIXELIZE_INKSCAPE_ENABLE_SMOOTH + + outputFrame.set_label(_("Output")); + outputFrame.add(outputVBox); + contents->pack_start(outputFrame, true, false); + } + + // Buttons + { + mainResetButton = addResponseButton(_("Reset"), GTK_RESPONSE_HELP, true); + mainResetButton ->set_tooltip_text(_("Reset all settings to defaults")); + + //## The OK button + mainCancelButton = addResponseButton(Gtk::Stock::STOP, GTK_RESPONSE_CANCEL); + if (mainCancelButton) { + mainCancelButton->set_tooltip_text(_("Abort a trace in progress")); + mainCancelButton->set_sensitive(false); + } + mainOkButton = addResponseButton(Gtk::Stock::OK, GTK_RESPONSE_OK); + mainOkButton->set_tooltip_text(_("Execute the trace")); + + contents->pack_start(buttonsHBox); + } + + setDefaults(); + + show_all_children(); + + desktopChangeConn = deskTrack.connectDesktopChanged( sigc::mem_fun(*this, &PixelArtDialogImpl::setTargetDesktop) ); + deskTrack.connect(GTK_WIDGET(gobj())); + + signalResponse().connect(sigc::mem_fun(*this, &PixelArtDialogImpl::responseCallback)); +} + +void PixelArtDialogImpl::responseCallback(int response_id) +{ + if (response_id == GTK_RESPONSE_OK) { + vectorize(); + } else if (response_id == GTK_RESPONSE_CANCEL) { + // TODO + } else if (response_id == GTK_RESPONSE_HELP) { + setDefaults(); + } else { + hide(); + return; + } +} + +Tracer::Kopf2011::Options PixelArtDialogImpl::options() +{ + Tracer::Kopf2011::Options options; + + options.curvesMultiplier = curvesMultiplierSpinner.get_value(); + options.islandsWeight = islandsWeightSpinner.get_value_as_int(); + options.sparsePixelsMultiplier = sparsePixelsMultiplierSpinner.get_value(); + options.sparsePixelsRadius = sparsePixelsRadiusSpinner.get_value_as_int(); +#if LIBDEPIXELIZE_INKSCAPE_ENABLE_SMOOTH + options.optimize = optimizeRadioButton.get_active(); +#else // LIBDEPIXELIZE_INKSCAPE_ENABLE_SMOOTH + options.optimize = false; +#endif // LIBDEPIXELIZE_INKSCAPE_ENABLE_SMOOTH + + options.nthreads = Inkscape::Preferences::get() + ->getIntLimited("/options/threading/numthreads", +#ifdef HAVE_OPENMP + omp_get_num_procs(), +#else + 1, +#endif // HAVE_OPENMP + 1, 256); + + return options; +} + +void PixelArtDialogImpl::vectorize() +{ + Inkscape::MessageStack *msgStack = desktop->messageStack(); + + if ( !desktop->selection ) { + char *msg = _("Select an <b>image</b> to trace"); + msgStack->flash(Inkscape::ERROR_MESSAGE, msg); + return; + } + + bool found = false; + + for ( GSList const *list = desktop->selection->itemList() ; list + ; list = list->next ) { + if ( !SP_IS_IMAGE(list->data) ) + continue; + + found = true; + + processLibdepixelize(SP_IMAGE(list->data)); + } + + if ( !found ) { + char *msg = _("Select an <b>image</b> to trace"); + msgStack->flash(Inkscape::ERROR_MESSAGE, msg); + return; + } + + DocumentUndo::done(desktop->doc(), SP_VERB_SELECTION_PIXEL_ART, + _("Trace pixel art")); + + // Flush pending updates + desktop->doc()->ensureUpToDate(); +} + +void PixelArtDialogImpl::processLibdepixelize(SPImage *img) +{ + Tracer::Splines out; + + Glib::RefPtr<Gdk::Pixbuf> pixbuf + = Glib::wrap(img->pixbuf->getPixbufRaw(), true); + + if ( pixbuf->get_width() > 256 || pixbuf->get_height() > 256 ) { + char *msg = _("Image looks too big. Process may take a while and it is" + " wise to save your document before continuing." + "\n\nContinue the procedure (without saving)?"); + Gtk::MessageDialog dialog(msg, false, Gtk::MESSAGE_WARNING, + Gtk::BUTTONS_OK_CANCEL, true); + + if ( dialog.run() != Gtk::RESPONSE_OK ) + return; + } + + if ( voronoiRadioButton.get_active() ) { + out = Tracer::Kopf2011::to_voronoi(pixbuf, options()); + } else { + out = Tracer::Kopf2011::to_splines(pixbuf, options()); + } + + Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); + Inkscape::XML::Node *group = xml_doc->createElement("svg:g"); + + for ( Tracer::Splines::iterator it = out.begin(), end = out.end() + ; it != end ; ++it ) { + Inkscape::XML::Node *repr = xml_doc->createElement("svg:path"); + + { + SPCSSAttr *css = sp_repr_css_attr_new(); + + { + gchar b[64]; + sp_svg_write_color(b, sizeof(b), + SP_RGBA32_U_COMPOSE(unsigned(it->rgba[0]), + unsigned(it->rgba[1]), + unsigned(it->rgba[2]), + unsigned(it->rgba[3]))); + + sp_repr_css_set_property(css, "fill", b); + } + + { + Inkscape::CSSOStringStream osalpha; + osalpha << float(it->rgba[3]) / 255.; + sp_repr_css_set_property(css, "fill-opacity", + osalpha.str().c_str()); + } + + sp_repr_css_set(repr, css, "style"); + sp_repr_css_attr_unref(css); + } + + gchar *str = sp_svg_write_path(Dialog::move(it->pathVector)); + repr->setAttribute("d", str); + g_free(str); + + group->appendChild(repr); + + Inkscape::GC::release(repr); + } + + { + group->setAttribute("transform", + (std::string("translate(") + + sp_svg_length_write_with_units(img->x) + + ' ' + sp_svg_length_write_with_units(img->y) + + ')').c_str()); + } + + desktop->currentLayer()->appendChildRepr(group); + + Inkscape::GC::release(group); +} + +void PixelArtDialogImpl::setDefaults() +{ + ignorePreview = true; + + curvesMultiplierSpinner.set_value(Tracer::Kopf2011::Options + ::CURVES_MULTIPLIER); + + islandsWeightSpinner.set_value(Tracer::Kopf2011::Options::ISLANDS_WEIGHT); + + sparsePixelsRadiusSpinner.set_value(Tracer::Kopf2011::Options + ::SPARSE_PIXELS_RADIUS); + + sparsePixelsMultiplierSpinner.set_value(Tracer::Kopf2011::Options + ::SPARSE_PIXELS_MULTIPLIER); + +#if LIBDEPIXELIZE_INKSCAPE_ENABLE_SMOOTH + optimizeRadioButton.set_active(); +#else // LIBDEPIXELIZE_INKSCAPE_ENABLE_SMOOTH + noOptimizeRadioButton.set_active(); +#endif // LIBDEPIXELIZE_INKSCAPE_ENABLE_SMOOTH + + ignorePreview = false; + + if ( pendingPreview ) + updatePreview(); +} + +void PixelArtDialogImpl::updatePreview() +{ + if ( ignorePreview ) { + pendingPreview = true; + return; + } + + // TODO: update preview + pendingPreview = false; +} + +/** + * Factory method. Use this to create a new PixelArtDialog + */ +PixelArtDialog &PixelArtDialog::getInstance() +{ + PixelArtDialog *dialog = new PixelArtDialogImpl(); + return *dialog; +} + +PixelArtDialogImpl::~PixelArtDialogImpl() +{ + desktopChangeConn.disconnect(); +} + + +} //namespace Dialog +} //namespace UI +} //namespace Inkscape + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/dialog/scriptdialog.h b/src/ui/dialog/pixelartdialog.h index d1962bf6f..165cb8699 100644 --- a/src/ui/dialog/scriptdialog.h +++ b/src/ui/dialog/pixelartdialog.h @@ -1,20 +1,17 @@ /** @file - * @brief Script dialog - * - * This dialog is for launching scripts whose main purpose is - * the scripting of Inkscape itself. + * @brief Bitmap tracing settings dialog */ /* Authors: * Bob Jamison + * Vinícius dos Santos Oliveira <vini.ipsmaker@gmail.com> * Other dudes from The Inkscape Organization * * Copyright (C) 2004, 2005 Authors - * * Released under GNU GPL, read the file 'COPYING' for more information */ -#ifndef __SCRIPTDIALOG_H__ -#define __SCRIPTDIALOG_H__ +#ifndef __PIXELARTDIALOG_H__ +#define __PIXELARTDIALOG_H__ #include "ui/widget/panel.h" #include "verbs.h" @@ -25,32 +22,29 @@ namespace Dialog { /** - * A script editor, loader, and executor + * A dialog that displays log messages */ -class ScriptDialog : public UI::Widget::Panel +class PixelArtDialog : public UI::Widget::Panel { - public: - ScriptDialog() : - UI::Widget::Panel("", "/dialogs/script", SP_VERB_DIALOG_SCRIPT) +public: + + PixelArtDialog() : + UI::Widget::Panel("", "/dialogs/pixelart", SP_VERB_SELECTION_PIXEL_ART) {} - /** - * Helper function which returns a new instance of the dialog. - * getInstance is needed by the dialog manager (Inkscape::UI::Dialog::DialogManager). - */ - static ScriptDialog &getInstance(); - virtual ~ScriptDialog() {}; + static PixelArtDialog &getInstance(); -}; // class ScriptDialog + virtual ~PixelArtDialog() {}; +}; } //namespace Dialog } //namespace UI } //namespace Inkscape -#endif /* __DEBUGDIALOG_H__ */ +#endif /* __PIXELARTDIALOGDIALOG_H__ */ /* Local Variables: diff --git a/src/ui/dialog/print.cpp b/src/ui/dialog/print.cpp index e940a3f55..03ac9dc64 100644 --- a/src/ui/dialog/print.cpp +++ b/src/ui/dialog/print.cpp @@ -26,7 +26,7 @@ #include "ui/widget/rendering-options.h" #include "document.h" -#include "unit-constants.h" +#include "util/units.h" #include "helper/png-write.h" #include "svg/svg-color.h" #include "io/sys.h" @@ -49,8 +49,8 @@ static void draw_page( if (junk->_tab->as_bitmap()) { // Render as exported PNG - gdouble width = (junk->_doc)->getWidth(); - gdouble height = (junk->_doc)->getHeight(); + gdouble width = (junk->_doc)->getWidth().value("px"); + gdouble height = (junk->_doc)->getHeight().value("px"); gdouble dpi = junk->_tab->bitmap_dpi(); std::string tmp_png; std::string tmp_base = "inkscape-print-png-XXXXXX"; @@ -72,8 +72,8 @@ static void draw_page( sp_export_png_file(junk->_doc, tmp_png.c_str(), 0.0, 0.0, width, height, - (unsigned long)(width * dpi / PX_PER_IN), - (unsigned long)(height * dpi / PX_PER_IN), + (unsigned long)(Inkscape::Util::Quantity::convert(width, "px", "in") * dpi), + (unsigned long)(Inkscape::Util::Quantity::convert(height, "px", "in") * dpi), dpi, dpi, bgcolor, NULL, NULL, true, NULL); // This doesn't seem to work: @@ -90,7 +90,7 @@ static void draw_page( cairo_t *cr = gtk_print_context_get_cairo_context (context); cairo_matrix_t m; cairo_get_matrix(cr, &m); - cairo_scale(cr, PT_PER_IN / dpi, PT_PER_IN / dpi); + cairo_scale(cr, Inkscape::Util::Quantity::convert(1, "in", "pt") / dpi, Inkscape::Util::Quantity::convert(1, "in", "pt") / dpi); // FIXME: why is the origin offset?? cairo_set_source_surface(cr, png->cobj(), -16.0, -16.0); cairo_paint(cr); @@ -101,7 +101,7 @@ static void draw_page( unlink (tmp_png.c_str()); } else { - g_warning(_("Could not open temporary PNG for bitmap printing")); + g_warning("%s", _("Could not open temporary PNG for bitmap printing")); } } else { @@ -138,17 +138,17 @@ static void draw_page( #endif bool ret = ctx->setSurfaceTarget (surface, true, &ctm); if (ret) { - ret = renderer.setupDocument (ctx, junk->_doc, TRUE, NULL); + ret = renderer.setupDocument (ctx, junk->_doc, TRUE, 0., NULL); if (ret) { renderer.renderItem(ctx, junk->_base); ret = ctx->finish(); } else { - g_warning(_("Could not set up Document")); + g_warning("%s", _("Could not set up Document")); } } else { - g_warning(_("Failed to set CairoRenderContext")); + g_warning("%s", _("Failed to set CairoRenderContext")); } // Clean up @@ -195,8 +195,8 @@ Print::Print(SPDocument *doc, SPItem *base) : // set up paper size to match the document size gtk_print_operation_set_unit (_printop, GTK_UNIT_POINTS); GtkPageSetup *page_setup = gtk_page_setup_new(); - gdouble doc_width = _doc->getWidth() * PT_PER_PX; - gdouble doc_height = _doc->getHeight() * PT_PER_PX; + gdouble doc_width = _doc->getWidth().value("pt"); + gdouble doc_height = _doc->getHeight().value("pt"); GtkPaperSize *paper_size; if (doc_width > doc_height) { gtk_page_setup_set_orientation (page_setup, GTK_PAGE_ORIENTATION_LANDSCAPE); diff --git a/src/ui/dialog/scriptdialog.cpp b/src/ui/dialog/scriptdialog.cpp deleted file mode 100644 index 55bbb7929..000000000 --- a/src/ui/dialog/scriptdialog.cpp +++ /dev/null @@ -1,244 +0,0 @@ -/** - * @file - * Dialog for executing and monitoring script execution. - */ -/* Author: - * Bob Jamison - * - * Copyright (C) 2004-2008 Authors - * - * Released under GNU GPL, read the file 'COPYING' for more information - */ -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include "scriptdialog.h" -#include <glibmm/i18n.h> -#include <gtkmm/menubar.h> -#include <gtkmm/frame.h> -#include <gtkmm/scrolledwindow.h> -#include <gtkmm/textview.h> - -#include <extension/script/InkscapeScript.h> - - - -namespace Inkscape -{ -namespace UI -{ -namespace Dialog -{ - - - -//######################################################################### -//## I M P L E M E N T A T I O N -//######################################################################### - -/** - * A script editor/executor - */ -class ScriptDialogImpl : public ScriptDialog -{ - - public: - ScriptDialogImpl(); - ~ScriptDialogImpl() - {} - - - /** - * Remove all text from the dialog. - */ - void clear(); - - /** - * Execute a script in the dialog. - * - * @param lang language in which the script is programmed - */ - void execute(Inkscape::Extension::Script::InkscapeScript::ScriptLanguage lang); - - /** - * Execute a Javascript script - */ - void executeJavascript(); - - /** - * Execute a Python script - */ - void executePython(); - - /** - * Execute a Ruby script - */ - void executeRuby(); - - - - private: - Gtk::MenuBar menuBar; - Gtk::Menu fileMenu; - - //## Script text - Gtk::Frame scriptTextFrame; - Gtk::ScrolledWindow scriptTextScroll; - Gtk::TextView scriptText; - - //## Output text - Gtk::Frame outputTextFrame; - Gtk::ScrolledWindow outputTextScroll; - Gtk::TextView outputText; - - //## Error text - Gtk::Frame errorTextFrame; - Gtk::ScrolledWindow errorTextScroll; - Gtk::TextView errorText; - - - -}; - -static const char *defaultCodeStr = - "/**\n" - " * This is some example Javascript.\n" - " * Try 'Execute Javascript'\n" - " */\n" - "importPackage(javax.swing);\n" - "function sayHello() {\n" - " JOptionPane.showMessageDialog(null, 'Hello, world!',\n" - " 'Welcome to Inkscape', JOptionPane.WARNING_MESSAGE);\n" - "}\n" - "\n" - "sayHello();\n" - "\n"; - - - - -//######################################################################### -//## E V E N T S -//######################################################################### - -static void textViewClear(Gtk::TextView &view) -{ - Glib::RefPtr<Gtk::TextBuffer> buffer = view.get_buffer(); - buffer->erase(buffer->begin(), buffer->end()); -} - -void ScriptDialogImpl::clear() -{ - textViewClear(scriptText); - textViewClear(outputText); - textViewClear(errorText); -} - -void ScriptDialogImpl::execute(Inkscape::Extension::Script::InkscapeScript::ScriptLanguage lang) -{ - Glib::ustring script = scriptText.get_buffer()->get_text(true); - Glib::ustring output; - Glib::ustring error; - Inkscape::Extension::Script::InkscapeScript engine; - bool ok = engine.interpretScript(script, output, error, lang); - outputText.get_buffer()->set_text(output); - errorText.get_buffer()->set_text(error); - if (!ok) - { - //do we want something here? - } -} - -void ScriptDialogImpl::executeJavascript() -{ - execute(Inkscape::Extension::Script::InkscapeScript::JAVASCRIPT); -} - -void ScriptDialogImpl::executePython() -{ - execute(Inkscape::Extension::Script::InkscapeScript::PYTHON); -} - -void ScriptDialogImpl::executeRuby() -{ - execute(Inkscape::Extension::Script::InkscapeScript::RUBY); -} - - -//######################################################################### -//## C O N S T R U C T O R / D E S T R U C T O R -//######################################################################### -ScriptDialogImpl::ScriptDialogImpl() : - ScriptDialog() -{ - Gtk::Box *contents = _getContents(); - - //## Add a menu for clear() - menuBar.items().push_back( Gtk::Menu_Helpers::MenuElem(_("_File"), fileMenu) ); - fileMenu.items().push_back( Gtk::Menu_Helpers::MenuElem(_("_Clear"), - sigc::mem_fun(*this, &ScriptDialogImpl::clear) ) ); - fileMenu.items().push_back( Gtk::Menu_Helpers::MenuElem(_("_Execute Javascript"), - sigc::mem_fun(*this, &ScriptDialogImpl::executeJavascript) ) ); - fileMenu.items().push_back( Gtk::Menu_Helpers::MenuElem(_("_Execute Python"), - sigc::mem_fun(*this, &ScriptDialogImpl::executePython) ) ); - fileMenu.items().push_back( Gtk::Menu_Helpers::MenuElem(_("_Execute Ruby"), - sigc::mem_fun(*this, &ScriptDialogImpl::executeRuby) ) ); - contents->pack_start(menuBar, Gtk::PACK_SHRINK); - - //### Set up the script field - scriptText.set_editable(true); - scriptText.get_buffer()->set_text(defaultCodeStr); - scriptTextScroll.add(scriptText); - scriptTextScroll.set_policy(Gtk::POLICY_ALWAYS, Gtk::POLICY_ALWAYS); - scriptTextFrame.set_label(_("Script")); - scriptTextFrame.set_shadow_type(Gtk::SHADOW_NONE); - scriptTextFrame.add(scriptTextScroll); - contents->pack_start(scriptTextFrame); - - //### Set up the output field - outputText.set_editable(true); - outputText.get_buffer()->set_text(""); - outputTextScroll.add(outputText); - outputTextScroll.set_policy(Gtk::POLICY_ALWAYS, Gtk::POLICY_ALWAYS); - outputTextFrame.set_label(_("Output")); - outputTextFrame.set_shadow_type(Gtk::SHADOW_NONE); - outputTextFrame.add(outputTextScroll); - contents->pack_start(outputTextFrame); - - //### Set up the error field - errorText.set_editable(true); - errorText.get_buffer()->set_text(""); - errorTextScroll.add(errorText); - errorTextScroll.set_policy(Gtk::POLICY_ALWAYS, Gtk::POLICY_ALWAYS); - errorTextFrame.set_label(_("Errors")); - errorTextFrame.set_shadow_type(Gtk::SHADOW_NONE); - errorTextFrame.add(errorTextScroll); - contents->pack_start(errorTextFrame); - - // sick of this thing shrinking too much - set_size_request(350, 400); - show_all_children(); - -} - -ScriptDialog &ScriptDialog::getInstance() -{ - ScriptDialog *dialog = new ScriptDialogImpl(); - return *dialog; -} - -} //namespace Dialogs -} //namespace UI -} //namespace Inkscape - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/dialog/spellcheck.cpp b/src/ui/dialog/spellcheck.cpp index 85320618b..8a4ddc57e 100644 --- a/src/ui/dialog/spellcheck.cpp +++ b/src/ui/dialog/spellcheck.cpp @@ -24,7 +24,7 @@ #include "desktop.h" #include "desktop-handles.h" #include "tools-switch.h" -#include "text-context.h" +#include "ui/tools/text-tool.h" #include "interface.h" #include "preferences.h" #include "sp-text.h" @@ -109,10 +109,6 @@ SpellCheck::SpellCheck (void) : tree_view.append_column(_("Suggestions:"), tree_columns.suggestions); { -// Backward compatibility fix: The GtkComboBoxText API was introduced with -// GTK+ 2.24. This check should eventually be dropped when we bump our -// GTK dependency. -#if GTK_CHECK_VERSION(2, 24, 0) dictionary_combo = gtk_combo_box_text_new(); gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT (dictionary_combo), _lang.c_str()); if (_lang2 != "") { @@ -121,16 +117,6 @@ SpellCheck::SpellCheck (void) : if (_lang3 != "") { gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT (dictionary_combo), _lang3.c_str()); } -#else - dictionary_combo = gtk_combo_box_new_text(); - gtk_combo_box_append_text (GTK_COMBO_BOX (dictionary_combo), _lang.c_str()); - if (_lang2 != "") { - gtk_combo_box_append_text (GTK_COMBO_BOX (dictionary_combo), _lang2.c_str()); - } - if (_lang3 != "") { - gtk_combo_box_append_text (GTK_COMBO_BOX (dictionary_combo), _lang3.c_str()); - } -#endif gtk_combo_box_set_active (GTK_COMBO_BOX (dictionary_combo), 0); gtk_widget_show_all (dictionary_combo); } @@ -219,8 +205,8 @@ void SpellCheck::setTargetDesktop(SPDesktop *desktop) void SpellCheck::clearRects() { for (GSList *it = _rects; it; it = it->next) { - sp_canvas_item_hide((SPCanvasItem*) it->data); - gtk_object_destroy((SPCanvasItem*) it->data); + sp_canvas_item_hide(SP_CANVAS_ITEM(it->data)); + sp_canvas_item_destroy(SP_CANVAS_ITEM(it->data)); } g_slist_free(_rects); _rects = NULL; @@ -330,8 +316,8 @@ SpellCheck::nextText() _text = getText(_root); if (_text) { - _modified_connection = ((SPObject*) _text)->connectModified(sigc::mem_fun(*this, &SpellCheck::onObjModified)); - _release_connection = ((SPObject*) _text)->connectRelease(sigc::mem_fun(*this, &SpellCheck::onObjReleased)); + _modified_connection = (SP_OBJECT(_text))->connectModified(sigc::mem_fun(*this, &SpellCheck::onObjModified)); + _release_connection = (SP_OBJECT(_text))->connectRelease(sigc::mem_fun(*this, &SpellCheck::onObjReleased)); _layout = te_get_layout (_text); _begin_w = _layout->begin(); @@ -473,7 +459,7 @@ SpellCheck::finished () if (_stops) label = g_strdup_printf(_("<b>Finished</b>, <b>%d</b> words added to dictionary"), _adds); else - label = g_strdup_printf(_("<b>Finished</b>, nothing suspicious found")); + label = g_strdup_printf("%s", _("<b>Finished</b>, nothing suspicious found")); banner_label.set_markup(label); g_free(label); } @@ -604,52 +590,54 @@ SpellCheck::nextWord() // draw rect std::vector<Geom::Point> points = _layout->createSelectionShape(_begin_w, _end_w, _text->i2dt_affine()); - Geom::Point tl, br; - tl = br = points.front(); - for (unsigned i = 0 ; i < points.size() ; i ++) { - if (points[i][Geom::X] < tl[Geom::X]) - tl[Geom::X] = points[i][Geom::X]; - if (points[i][Geom::Y] < tl[Geom::Y]) - tl[Geom::Y] = points[i][Geom::Y]; - if (points[i][Geom::X] > br[Geom::X]) - br[Geom::X] = points[i][Geom::X]; - if (points[i][Geom::Y] > br[Geom::Y]) - br[Geom::Y] = points[i][Geom::Y]; - } + if (points.size() >= 4) { // we may not have a single quad if this is a clipped part of text on path; in that case skip drawing the rect + Geom::Point tl, br; + tl = br = points.front(); + for (unsigned i = 0 ; i < points.size() ; i ++) { + if (points[i][Geom::X] < tl[Geom::X]) + tl[Geom::X] = points[i][Geom::X]; + if (points[i][Geom::Y] < tl[Geom::Y]) + tl[Geom::Y] = points[i][Geom::Y]; + if (points[i][Geom::X] > br[Geom::X]) + br[Geom::X] = points[i][Geom::X]; + if (points[i][Geom::Y] > br[Geom::Y]) + br[Geom::Y] = points[i][Geom::Y]; + } - // expand slightly - Geom::Rect area = Geom::Rect(tl, br); - double mindim = fabs(tl[Geom::Y] - br[Geom::Y]); - if (fabs(tl[Geom::X] - br[Geom::X]) < mindim) - mindim = fabs(tl[Geom::X] - br[Geom::X]); - area.expandBy(MAX(0.05 * mindim, 1)); - - // create canvas path rectangle, red stroke - SPCanvasItem *rect = sp_canvas_bpath_new(sp_desktop_sketch(desktop), NULL); - sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(rect), 0xff0000ff, 3.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); - sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(rect), 0, SP_WIND_RULE_NONZERO); - SPCurve *curve = new SPCurve(); - curve->moveto(area.corner(0)); - curve->lineto(area.corner(1)); - curve->lineto(area.corner(2)); - curve->lineto(area.corner(3)); - curve->lineto(area.corner(0)); - sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(rect), curve); - sp_canvas_item_show(rect); - _rects = g_slist_prepend(_rects, rect); - - // scroll to make it all visible - Geom::Point const center = desktop->get_display_area().midpoint(); - area.expandBy(0.5 * mindim); - Geom::Point scrollto; - double dist = 0; - for (unsigned corner = 0; corner < 4; corner ++) { - if (Geom::L2(area.corner(corner) - center) > dist) { - dist = Geom::L2(area.corner(corner) - center); - scrollto = area.corner(corner); + // expand slightly + Geom::Rect area = Geom::Rect(tl, br); + double mindim = fabs(tl[Geom::Y] - br[Geom::Y]); + if (fabs(tl[Geom::X] - br[Geom::X]) < mindim) + mindim = fabs(tl[Geom::X] - br[Geom::X]); + area.expandBy(MAX(0.05 * mindim, 1)); + + // create canvas path rectangle, red stroke + SPCanvasItem *rect = sp_canvas_bpath_new(sp_desktop_sketch(desktop), NULL); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(rect), 0xff0000ff, 3.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(rect), 0, SP_WIND_RULE_NONZERO); + SPCurve *curve = new SPCurve(); + curve->moveto(area.corner(0)); + curve->lineto(area.corner(1)); + curve->lineto(area.corner(2)); + curve->lineto(area.corner(3)); + curve->lineto(area.corner(0)); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(rect), curve); + sp_canvas_item_show(rect); + _rects = g_slist_prepend(_rects, rect); + + // scroll to make it all visible + Geom::Point const center = desktop->get_display_area().midpoint(); + area.expandBy(0.5 * mindim); + Geom::Point scrollto; + double dist = 0; + for (unsigned corner = 0; corner < 4; corner ++) { + if (Geom::L2(area.corner(corner) - center) > dist) { + dist = Geom::L2(area.corner(corner) - center); + scrollto = area.corner(corner); + } } + desktop->scroll_to_point (scrollto, 1.0); } - desktop->scroll_to_point (scrollto, 1.0); // select text; if in Text tool, position cursor to the beginning of word // unless it is already in the word @@ -729,7 +717,7 @@ SpellCheck::deleteLastRect () { if (_rects) { sp_canvas_item_hide(SP_CANVAS_ITEM(_rects->data)); - gtk_object_destroy(GTK_OBJECT(_rects->data)); + sp_canvas_item_destroy(SP_CANVAS_ITEM(_rects->data)); _rects = _rects->next; // pop latest-prepended rect } } diff --git a/src/ui/dialog/spellcheck.h b/src/ui/dialog/spellcheck.h index 8eb240097..27b89e34e 100644 --- a/src/ui/dialog/spellcheck.h +++ b/src/ui/dialog/spellcheck.h @@ -12,6 +12,14 @@ #ifndef SEEN_SPELLCHECK_H #define SEEN_SPELLCHECK_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> #include <gtkmm/button.h> #include <gtkmm/buttonbox.h> @@ -240,10 +248,20 @@ private: GtkWidget * dictionary_combo; Gtk::HBox dictionary_hbox; +#if WITH_GTKMM_3_0 + Gtk::Separator action_sep; +#else Gtk::HSeparator action_sep; +#endif + Gtk::Button stop_button; Gtk::Button start_button; + +#if WITH_GTKMM_3_0 + Gtk::ButtonBox actionbutton_hbox; +#else Gtk::HButtonBox actionbutton_hbox; +#endif SPDesktop * desktop; DesktopTracker deskTrack; diff --git a/src/ui/dialog/svg-fonts-dialog.cpp b/src/ui/dialog/svg-fonts-dialog.cpp index 2127ef402..56ecfdecc 100644 --- a/src/ui/dialog/svg-fonts-dialog.cpp +++ b/src/ui/dialog/svg-fonts-dialog.cpp @@ -15,14 +15,13 @@ # include <config.h> #endif -#ifdef ENABLE_SVG_FONTS - #include "svg-fonts-dialog.h" #include "document-private.h" #include "document-undo.h" #include <gtkmm/notebook.h> +#include <gtkmm/imagemenuitem.h> +#include <gtkmm/scale.h> #include <gtkmm/stock.h> -#include <glibmm/i18n.h> #include <message-stack.h> #include "selection.h" #include <string.h> @@ -38,6 +37,9 @@ #include "sp-font.h" #include "sp-glyph-kerning.h" +#include <glibmm/i18n.h> +#include <glibmm/stringutils.h> + SvgFontDrawingArea::SvgFontDrawingArea(): _x(0), _y(0), @@ -162,23 +164,14 @@ GlyphComboBox::GlyphComboBox(){ void GlyphComboBox::update(SPFont* spfont){ if (!spfont) return -//TODO: figure out why do we need to append_text("") before clearing items properly... +//TODO: figure out why do we need to append("") before clearing items properly... -#if WITH_GTKMM_2_24 this->append(""); //Gtk is refusing to clear the combobox when I comment out this line this->remove_all(); -#else - this->append_text(""); //Gtk is refusing to clear the combobox when I comment out this line - this->clear_items(); -#endif for(SPObject* node = spfont->children; node; node=node->next){ if (SP_IS_GLYPH(node)){ -#if WITH_GTKMM_2_24 this->append((static_cast<SPGlyph*>(node))->unicode); -#else - this->append_text((static_cast<SPGlyph*>(node))->unicode); -#endif } } } @@ -199,7 +192,7 @@ void SvgFontsDialog::on_kerning_value_changed(){ //slider values increase from right to left so that they match the kerning pair preview //XML Tree being directly used here while it shouldn't be. - this->kerning_pair->getRepr()->setAttribute("k", Glib::Ascii::dtostr(get_selected_spfont()->horiz_adv_x - kerning_slider.get_value()).c_str()); + this->kerning_pair->getRepr()->setAttribute("k", Glib::Ascii::dtostr(get_selected_spfont()->horiz_adv_x - kerning_slider->get_value()).c_str()); DocumentUndo::maybeDone(document, undokey.c_str(), SP_VERB_DIALOG_SVG_FONTS, _("Adjust kerning value")); //populate_kerning_pairs_box(); @@ -277,7 +270,7 @@ void SvgFontsDialog::update_fonts() _model->clear(); for(const GSList *l = fonts; l; l = l->next) { Gtk::TreeModel::Row row = *_model->append(); - SPFont* f = (SPFont*)l->data; + SPFont* f = SP_FONT(l->data); row[_columns.spfont] = f; row[_columns.svgfont] = new SvgFont(f); const gchar* lbl = f->label(); @@ -307,7 +300,7 @@ void SvgFontsDialog::on_kerning_pair_selection_changed(){ this->kerning_pair = kern; //slider values increase from right to left so that they match the kerning pair preview - kerning_slider.set_value(get_selected_spfont()->horiz_adv_x - kern->k); + kerning_slider->set_value(get_selected_spfont()->horiz_adv_x - kern->k); } void SvgFontsDialog::update_global_settings_tab(){ @@ -317,7 +310,7 @@ void SvgFontsDialog::update_global_settings_tab(){ SPObject* obj; for (obj=font->children; obj; obj=obj->next){ if (SP_IS_FONTFACE(obj)){ - _familyname_entry->set_text(((SPFontFace*) obj)->font_family); + _familyname_entry->set_text((SP_FONTFACE(obj))->font_family); } } } @@ -336,9 +329,9 @@ void SvgFontsDialog::on_font_selection_changed(){ double set_width = spfont->horiz_adv_x; setwidth_spin.set_value(set_width); - kerning_slider.set_range(0, set_width); - kerning_slider.set_draw_value(false); - kerning_slider.set_value(0); + kerning_slider->set_range(0, set_width); + kerning_slider->set_draw_value(false); + kerning_slider->set_value(0); update_global_settings_tab(); populate_glyphs_box(); @@ -548,7 +541,9 @@ void SvgFontsDialog::set_glyph_description_from_selected_path(){ Geom::PathVector pathv = sp_svg_read_pathv(node->attribute("d")); //XML Tree being directly used here while it shouldn't be. - glyph->getRepr()->setAttribute("d", (char*) sp_svg_write_path (flip_coordinate_system(pathv))); + gchar *str = sp_svg_write_path (flip_coordinate_system(pathv)); + glyph->getRepr()->setAttribute("d", str); + g_free(str); DocumentUndo::done(doc, SP_VERB_DIALOG_SVG_FONTS, _("Set glyph curves")); update_glyphs(); @@ -585,7 +580,9 @@ void SvgFontsDialog::missing_glyph_description_from_selected_path(){ if (SP_IS_MISSING_GLYPH(obj)){ //XML Tree being directly used here while it shouldn't be. - obj->getRepr()->setAttribute("d", (char*) sp_svg_write_path (flip_coordinate_system(pathv))); + gchar *str = sp_svg_write_path (flip_coordinate_system(pathv)); + obj->getRepr()->setAttribute("d", str); + g_free(str); DocumentUndo::done(doc, SP_VERB_DIALOG_SVG_FONTS, _("Set glyph curves")); } } @@ -787,7 +784,7 @@ Gtk::VBox* SvgFontsDialog::kerning_tab(){ add_kernpair_button.set_label(_("Add pair")); add_kernpair_button.signal_clicked().connect(sigc::mem_fun(*this, &SvgFontsDialog::add_kerning_pair)); _KerningPairsList.get_selection()->signal_changed().connect(sigc::mem_fun(*this, &SvgFontsDialog::on_kerning_pair_selection_changed)); - kerning_slider.signal_value_changed().connect(sigc::mem_fun(*this, &SvgFontsDialog::on_kerning_value_changed)); + kerning_slider->signal_value_changed().connect(sigc::mem_fun(*this, &SvgFontsDialog::on_kerning_value_changed)); kerning_vbox.pack_start(*kerning_selector, false,false); @@ -805,7 +802,7 @@ Gtk::VBox* SvgFontsDialog::kerning_tab(){ Gtk::HBox* kerning_amount_hbox = Gtk::manage(new Gtk::HBox()); kerning_vbox.pack_start(*kerning_amount_hbox, false,false); kerning_amount_hbox->add(*Gtk::manage(new Gtk::Label(_("Kerning value:")))); - kerning_amount_hbox->add(kerning_slider); + kerning_amount_hbox->add(*kerning_slider); kerning_preview.set_size(300 + 20, 150 + 20); _font_da.set_size(150 + 20, 50 + 20); @@ -892,6 +889,12 @@ void SvgFontsDialog::add_font(){ SvgFontsDialog::SvgFontsDialog() : UI::Widget::Panel("", "/dialogs/svgfonts", SP_VERB_DIALOG_SVG_FONTS), _add(Gtk::Stock::NEW) { +#if WITH_GTKMM_3_0 + kerning_slider = Gtk::manage(new Gtk::Scale(Gtk::ORIENTATION_HORIZONTAL)); +#else + kerning_slider = Gtk::manage(new Gtk::HScale); +#endif + _add.signal_clicked().connect(sigc::mem_fun(*this, &SvgFontsDialog::add_font)); Gtk::HBox* hbox = Gtk::manage(new Gtk::HBox()); @@ -946,8 +949,6 @@ SvgFontsDialog::~SvgFontsDialog(){} } // namespace UI } // namespace Inkscape -#endif //#ifdef ENABLE_SVG_FONTS - /* Local Variables: mode:c++ diff --git a/src/ui/dialog/svg-fonts-dialog.h b/src/ui/dialog/svg-fonts-dialog.h index 910f79d4c..e5c4631e4 100644 --- a/src/ui/dialog/svg-fonts-dialog.h +++ b/src/ui/dialog/svg-fonts-dialog.h @@ -20,13 +20,20 @@ #include <gtkmm/drawingarea.h> #include <gtkmm/entry.h> #include <gtkmm/liststore.h> -#include <gtkmm/scale.h> #include <gtkmm/scrolledwindow.h> #include <gtkmm/treeview.h> #include "attributes.h" #include "xml/helper-observer.h" +namespace Gtk { +#if WITH_GTKMM_3_0 +class Scale; +#else +class HScale; +#endif +} + class SPGlyph; class SPGlyphKerning; class SvgFont; @@ -45,7 +52,7 @@ private: bool on_expose_event (GdkEventExpose *event); }; -struct SPFont; +class SPFont; namespace Inkscape { namespace UI { @@ -210,7 +217,12 @@ private: GlyphComboBox first_glyph, second_glyph; SPGlyphKerning* kerning_pair; Inkscape::UI::Widget::SpinButton setwidth_spin; - Gtk::HScale kerning_slider; + +#if WITH_GTKMM_3_0 + Gtk::Scale* kerning_slider; +#else + Gtk::HScale* kerning_slider; +#endif class EntryWidget : public Gtk::HBox { diff --git a/src/ui/dialog/swatches.cpp b/src/ui/dialog/swatches.cpp index 092887541..5e77a28ab 100644 --- a/src/ui/dialog/swatches.cpp +++ b/src/ui/dialog/swatches.cpp @@ -23,6 +23,7 @@ #include <glibmm/i18n.h> #include <glibmm/main.h> +#include <glibmm/timer.h> #include <gdkmm/pixbuf.h> #include "color-item.h" @@ -41,7 +42,6 @@ #include "path-prefix.h" #include "preferences.h" #include "sp-item.h" -#include "sp-gradient-fns.h" #include "sp-gradient.h" #include "sp-gradient-vector.h" #include "style.h" @@ -54,6 +54,9 @@ #include "dialog-manager.h" #include "selection.h" #include "verbs.h" +#include "gradient-chemistry.h" +#include "helper/action.h" +#include "helper/action-context.h" namespace Inkscape { namespace UI { @@ -62,10 +65,10 @@ namespace Dialogs { #define VBLOCK 16 #define PREVIEW_PIXBUF_WIDTH 128 -void _loadPaletteFile( gchar const *filename ); +void _loadPaletteFile( gchar const *filename, gboolean user=FALSE ); - -std::vector<SwatchPage*> possible; +std::list<SwatchPage*> userSwatchPages; +std::list<SwatchPage*> systemSwatchPages; static std::map<SPDocument*, SwatchPage*> docPalettes; static std::vector<DocTrack*> docTrackings; static std::map<SwatchesPanel*, SPDocument*> docPerPanel; @@ -142,8 +145,21 @@ static void editGradientImpl( SPDesktop* desktop, SPGradient* gr ) } if (!shown) { - GtkWidget *dialog = sp_gradient_vector_editor_new( gr ); - gtk_widget_show( dialog ); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/dialogs/gradienteditor/showlegacy", false)) { + // Legacy gradient dialog + GtkWidget *dialog = sp_gradient_vector_editor_new( gr ); + gtk_widget_show( dialog ); + } else { + // Invoke the gradient tool + Inkscape::Verb *verb = Inkscape::Verb::get( SP_VERB_CONTEXT_GRADIENT ); + if ( verb ) { + SPAction *action = verb->get_action( Inkscape::ActionContext( ( Inkscape::UI::View::View * ) SP_ACTIVE_DESKTOP ) ); + if ( action ) { + sp_action_perform( action, NULL ); + } + } + } } } } @@ -197,20 +213,7 @@ void SwatchesPanelHook::deleteGradient( GtkMenuItem */*menuitem*/, gpointer /*us if ( bounceTarget ) { SwatchesPanel* swp = bouncePanel; SPDesktop* desktop = swp ? swp->getDesktop() : 0; - SPDocument *doc = desktop ? desktop->doc() : 0; - if (doc) { - std::string targetName(bounceTarget->def.descr); - const GSList *gradients = doc->getResourceList("gradient"); - for (const GSList *item = gradients; item; item = item->next) { - SPGradient* grad = SP_GRADIENT(item->data); - if ( targetName == grad->getId() ) { - grad->setSwatch(false); - DocumentUndo::done(doc, SP_VERB_CONTEXT_GRADIENT, - _("Delete")); - break; - } - } - } + sp_gradient_unset_swatch(desktop, bounceTarget->def.descr); } } @@ -237,11 +240,14 @@ static void removeit( GtkWidget *widget, gpointer data ) gtk_container_remove( GTK_CONTAINER(data), widget ); } +/* extern'ed from colot-item.cpp */ +gboolean colorItemHandleButtonPress( GtkWidget* widget, GdkEventButton* event, gpointer user_data ); + gboolean colorItemHandleButtonPress( GtkWidget* widget, GdkEventButton* event, gpointer user_data ) { gboolean handled = FALSE; - if ( (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) { + if ( event && (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) { SwatchesPanel* swp = findContainingPanel( widget ); if ( !popupMenu ) { @@ -303,8 +309,8 @@ gboolean colorItemHandleButtonPress( GtkWidget* widget, GdkEventButton* event, g gtk_widget_show_all(popupMenu); } - ColorItem* item = reinterpret_cast<ColorItem*>(user_data); - if ( item ) { + if ( user_data ) { + ColorItem* item = reinterpret_cast<ColorItem*>(user_data); bool show = swp && (swp->getSelectedIndex() == 0); for ( std::vector<GtkWidget*>::iterator it = popupExtras.begin(); it != popupExtras.end(); ++ it) { gtk_widget_set_sensitive(*it, show); @@ -371,13 +377,13 @@ static char* trim( char* str ) { return ret; } -void skipWhitespace( char*& str ) { +static void skipWhitespace( char*& str ) { while ( *str == ' ' || *str == '\t' ) { str++; } } -bool parseNum( char*& str, int& val ) { +static bool parseNum( char*& str, int& val ) { val = 0; while ( '0' <= *str && *str <= '9' ) { val = val * 10 + (*str - '0'); @@ -388,7 +394,7 @@ bool parseNum( char*& str, int& val ) { } -void _loadPaletteFile( gchar const *filename ) +void _loadPaletteFile( gchar const *filename, gboolean user/*=FALSE*/ ) { char block[1024]; FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" ); @@ -490,7 +496,10 @@ void _loadPaletteFile( gchar const *filename ) } } while ( result && !hasErr ); if ( !hasErr ) { - possible.push_back(onceMore); + if (user) + userSwatchPages.push_back(onceMore); + else + systemSwatchPages.push_back(onceMore); #if ENABLE_MAGIC_COLORS ColorItem::_wireMagicColors( onceMore ); #endif // ENABLE_MAGIC_COLORS @@ -504,9 +513,16 @@ void _loadPaletteFile( gchar const *filename ) } } +static bool +compare_swatch_names(SwatchPage const *a, SwatchPage const *b) { + + return g_utf8_collate(a->_name.c_str(), b->_name.c_str()) < 0; +} + static void loadEmUp() { static bool beenHere = false; + gboolean userPalete = true; if ( !beenHere ) { beenHere = true; @@ -518,7 +534,6 @@ static void loadEmUp() // Use this loop to iterate through a list of possible document locations. while (!sources.empty()) { gchar *dirname = sources.front(); - if ( Inkscape::IO::file_test( dirname, G_FILE_TEST_EXISTS ) && Inkscape::IO::file_test( dirname, G_FILE_TEST_IS_DIR )) { GError *err = 0; @@ -532,11 +547,13 @@ static void loadEmUp() while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) { gchar* lower = g_ascii_strdown( filename, -1 ); // if ( g_str_has_suffix(lower, ".gpl") ) { + if ( !g_str_has_suffix(lower, "~") ) { gchar* full = g_build_filename(dirname, filename, NULL); if ( !Inkscape::IO::file_test( full, G_FILE_TEST_IS_DIR ) ) { - _loadPaletteFile(full); + _loadPaletteFile(full, userPalete); } g_free(full); + } // } g_free(lower); } @@ -547,15 +564,15 @@ static void loadEmUp() // toss the dirname g_free(dirname); sources.pop_front(); + userPalete = false; } } -} - - - - + // Sort the list of swatches by name, grouped by user/system + userSwatchPages.sort(compare_swatch_names); + systemSwatchPages.sort(compare_swatch_names); +} @@ -589,7 +606,7 @@ SwatchesPanel::SwatchesPanel(gchar const* prefsPath) : } loadEmUp(); - if ( !possible.empty() ) { + if ( !systemSwatchPages.empty() ) { SwatchPage* first = 0; int index = 0; Glib::ustring targetName; @@ -600,8 +617,9 @@ SwatchesPanel::SwatchesPanel(gchar const* prefsPath) : if (targetName == "Auto") { first = docPalettes[0]; } else { - index++; - for ( std::vector<SwatchPage*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) { + //index++; + std::vector<SwatchPage*> pages = _getSwatchSets(); + for ( std::vector<SwatchPage*>::iterator iter = pages.begin(); iter != pages.end(); ++iter ) { if ( (*iter)->_name == targetName ) { first = *iter; break; @@ -632,10 +650,24 @@ SwatchesPanel::SwatchesPanel(gchar const* prefsPath) : hotItem = single; } _regItem( single, 3, i ); + i++; } } + if (Glib::ustring(prefsPath) == "/dialogs/swatches") { + Gtk::Requisition sreq; +#if WITH_GTKMM_3_0 + Gtk::Requisition sreq_natural; + get_preferred_size(sreq_natural, sreq); +#else + sreq = size_request(); +#endif + int minHeight = 60; + if (sreq.height < minHeight) { + set_size_request(70, minHeight); + } + } _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET); _setTargetFillable(_holder); @@ -713,10 +745,11 @@ void SwatchesPanel::setDesktop( SPDesktop* desktop ) class DocTrack { public: - DocTrack(SPDocument *doc, sigc::connection &gradientRsrcChanged, sigc::connection &defsChanged, sigc::connection &defsModified) : + DocTrack(SPDocument *doc, sigc::connection &docDestroy, sigc::connection &gradientRsrcChanged, sigc::connection &defsChanged, sigc::connection &defsModified) : doc(doc), updatePending(false), lastGradientUpdate(0.0), + docDestroy(docDestroy), gradientRsrcChanged(gradientRsrcChanged), defsChanged(defsChanged), defsModified(defsModified) @@ -741,9 +774,11 @@ public: } } if (doc) { + docDestroy.disconnect(); gradientRsrcChanged.disconnect(); defsChanged.disconnect(); defsModified.disconnect(); + doc = NULL; } } @@ -763,6 +798,7 @@ public: SPDocument *doc; bool updatePending; double lastGradientUpdate; + sigc::connection docDestroy; sigc::connection gradientRsrcChanged; sigc::connection defsChanged; sigc::connection defsModified; @@ -826,7 +862,7 @@ bool DocTrack::queueUpdateIfNeeded( SPDocument *doc ) void SwatchesPanel::_trackDocument( SwatchesPanel *panel, SPDocument *document ) { - SPDocument *oldDoc = 0; + SPDocument *oldDoc = NULL; if (docPerPanel.find(panel) != docPerPanel.end()) { oldDoc = docPerPanel[panel]; if (!oldDoc) { @@ -835,7 +871,7 @@ void SwatchesPanel::_trackDocument( SwatchesPanel *panel, SPDocument *document ) } if (oldDoc != document) { if (oldDoc) { - docPerPanel[panel] = 0; + docPerPanel[panel] = NULL; bool found = false; for (std::map<SwatchesPanel*, SPDocument*>::iterator it = docPerPanel.begin(); (it != docPerPanel.end()) && !found; ++it) { found = (it->second == document); @@ -858,11 +894,12 @@ void SwatchesPanel::_trackDocument( SwatchesPanel *panel, SPDocument *document ) } docPerPanel[panel] = document; if (!found) { + sigc::connection conn0 = document->connectDestroy(sigc::bind(sigc::ptr_fun(&SwatchesPanel::handleDocumentDestroy), document)); sigc::connection conn1 = document->connectResourcesChanged( "gradient", sigc::bind(sigc::ptr_fun(&SwatchesPanel::handleGradientsChange), document) ); sigc::connection conn2 = document->getDefs()->connectRelease( sigc::hide(sigc::bind(sigc::ptr_fun(&SwatchesPanel::handleDefsModified), document)) ); sigc::connection conn3 = document->getDefs()->connectModified( sigc::hide(sigc::hide(sigc::bind(sigc::ptr_fun(&SwatchesPanel::handleDefsModified), document))) ); - DocTrack *dt = new DocTrack(document, conn1, conn2, conn3); + DocTrack *dt = new DocTrack(document, conn0, conn1, conn2, conn3); docTrackings.push_back(dt); if (docPalettes.find(document) == docPalettes.end()) { @@ -873,11 +910,6 @@ void SwatchesPanel::_trackDocument( SwatchesPanel *panel, SPDocument *document ) } } } - - std::set<SPDocument*> docs; - for (std::map<SwatchesPanel*, SPDocument*>::iterator it = docPerPanel.begin(); it != docPerPanel.end(); ++it) { - docs.insert(it->second); - } } void SwatchesPanel::_setDocument( SPDocument *document ) @@ -896,11 +928,13 @@ static void recalcSwatchContents(SPDocument* doc, { std::vector<SPGradient*> newList; - const GSList *gradients = doc->getResourceList("gradient"); - for (const GSList *item = gradients; item; item = item->next) { - SPGradient* grad = SP_GRADIENT(item->data); - if ( grad->isSwatch() ) { - newList.push_back(SP_GRADIENT(item->data)); + if (doc) { + const GSList *gradients = doc->getResourceList("gradient"); + for (const GSList *item = gradients; item; item = item->next) { + SPGradient* grad = SP_GRADIENT(item->data); + if ( grad->isSwatch() ) { + newList.push_back(SP_GRADIENT(item->data)); + } } } @@ -939,6 +973,37 @@ static void recalcSwatchContents(SPDocument* doc, } } +void SwatchesPanel::handleDocumentDestroy(SPDocument *document) +{ + if (document) { + for (std::vector<DocTrack*>::iterator it = docTrackings.begin(); it != docTrackings.end(); ++it){ + if ((*it)->doc == document) { + delete *it; + docTrackings.erase(it); + break; + } + } + + if (docPalettes.find(document) != docPalettes.end()) { + docPalettes.erase(document); + } + + for (std::map<SwatchesPanel*, SPDocument*>::iterator it = docPerPanel.begin(); it != docPerPanel.end(); ++it) { + if (it->second == document) { + SwatchesPanel* swp = it->first; + std::vector<SwatchPage*> pages = swp->_getSwatchSets(); + if ((swp->_currentIndex >= static_cast<int>(pages.size())) && (pages.size() > 0)) + { + swp->_setSelectedIndex(swp->_getSwatchSets().size() - 1); + } + swp->_rebuild(); + docPerPanel.erase(it); + break; + } + } + } +} + void SwatchesPanel::handleGradientsChange(SPDocument *document) { SwatchPage *docPalette = (docPalettes.find(document) != docPalettes.end()) ? docPalettes[document] : 0; @@ -1011,6 +1076,7 @@ void SwatchesPanel::handleDefsModified(SPDocument *document) } } + std::vector<SwatchPage*> SwatchesPanel::_getSwatchSets() const { std::vector<SwatchPage*> tmp; @@ -1018,7 +1084,8 @@ std::vector<SwatchPage*> SwatchesPanel::_getSwatchSets() const tmp.push_back(docPalettes[_currentDocument]); } - tmp.insert(tmp.end(), possible.begin(), possible.end()); + tmp.insert(tmp.end(), userSwatchPages.begin(), userSwatchPages.end()); + tmp.insert(tmp.end(), systemSwatchPages.begin(), systemSwatchPages.end()); return tmp; } @@ -1111,42 +1178,46 @@ void SwatchesPanel::_handleAction( int setId, int itemId ) switch( setId ) { case 3: { - std::vector<SwatchPage*> pages = _getSwatchSets(); - if ( itemId >= 0 && itemId < static_cast<int>(pages.size()) ) { - _currentIndex = itemId; - - if ( !_prefs_path.empty() ) { - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setString(_prefs_path + "/palette", pages[_currentIndex]->_name); - } - - _rebuild(); - } + _setSelectedIndex(itemId); } break; } } -void SwatchesPanel::_rebuild() +void SwatchesPanel::_setSelectedIndex( int index ) { std::vector<SwatchPage*> pages = _getSwatchSets(); - SwatchPage* curr = pages[_currentIndex]; - _holder->clear(); + if ( index >= 0 && index < static_cast<int>(pages.size()) ) { + _currentIndex = index; - if ( curr->_prefWidth > 0 ) { - _holder->setColumnPref( curr->_prefWidth ); - } - _holder->freezeUpdates(); - // TODO restore once 'clear' works _holder->addPreview(_clear); - _holder->addPreview(_remove); - for ( boost::ptr_vector<ColorItem>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); ++it) { - _holder->addPreview(&*it); + if ( !_prefs_path.empty() ) { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + prefs->setString(_prefs_path + "/palette", pages[_currentIndex]->_name); + } + + _rebuild(); } - _holder->thawUpdates(); } +void SwatchesPanel::_rebuild() +{ + std::vector<SwatchPage*> pages = _getSwatchSets(); + if (_currentIndex < static_cast<int>(pages.size())) { + SwatchPage* curr = pages[_currentIndex]; + _holder->clear(); - + if ( curr->_prefWidth > 0 ) { + _holder->setColumnPref( curr->_prefWidth ); + } + _holder->freezeUpdates(); + // TODO restore once 'clear' works _holder->addPreview(_clear); + _holder->addPreview(_remove); + for ( boost::ptr_vector<ColorItem>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); ++it) { + _holder->addPreview(&*it); + } + _holder->thawUpdates(); + } +} } //namespace Dialogs } //namespace UI diff --git a/src/ui/dialog/swatches.h b/src/ui/dialog/swatches.h index ca4c1687d..3abb81d98 100644 --- a/src/ui/dialog/swatches.h +++ b/src/ui/dialog/swatches.h @@ -43,11 +43,13 @@ public: virtual int getSelectedIndex() {return _currentIndex;} // temporary protected: + static void handleDocumentDestroy(SPDocument *document); static void handleGradientsChange(SPDocument *document); virtual void _updateFromSelection(); virtual void _handleAction( int setId, int itemId ); virtual void _setDocument( SPDocument *document ); + virtual void _setSelectedIndex( int index ); virtual void _rebuild(); virtual std::vector<SwatchPage*> _getSwatchSets() const; diff --git a/src/ui/dialog/symbols.cpp b/src/ui/dialog/symbols.cpp new file mode 100644 index 000000000..8e0d085a4 --- /dev/null +++ b/src/ui/dialog/symbols.cpp @@ -0,0 +1,835 @@ +/** + * @file + * Symbols dialog. + */ +/* Authors: + * Copyright (C) 2012 Tavmjong Bah + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include <iostream> +#include <algorithm> +#include <locale> +#include <functional> +#include <sstream> + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + +#include <gtkmm/buttonbox.h> +#include <gtkmm/label.h> + +#if WITH_GTKMM_3_0 +# include <gtkmm/togglebutton.h> +# include <gtkmm/grid.h> +#else +# include <gtkmm/table.h> +#endif + +#include <gtkmm/scrolledwindow.h> +#include <gtkmm/comboboxtext.h> +#include <gtkmm/iconview.h> +#include <gtkmm/liststore.h> +#include <gtkmm/treemodelcolumn.h> +#include <gtkmm/clipboard.h> +#include <glibmm/stringutils.h> +#include <glibmm/markup.h> +#include <glibmm/i18n.h> +#include "path-prefix.h" +#include "io/sys.h" + +#include "ui/cache/svg_preview_cache.h" +#include "ui/clipboard.h" +#include "ui/icon-names.h" + +#include "symbols.h" + +#include "selection.h" +#include "desktop.h" +#include "desktop-handles.h" +#include "document.h" +#include "inkscape.h" +#include "sp-root.h" +#include "sp-use.h" +#include "sp-defs.h" +#include "sp-symbol.h" +#include "widgets/icon.h" + +#ifdef WITH_LIBVISIO +#include <libvisio/libvisio.h> +#include <libwpd-stream/libwpd-stream.h> +#endif + +#include "verbs.h" +#include "helper/action.h" +#include "helper/action-context.h" +#include "xml/repr.h" + +namespace Inkscape { +namespace UI { + +namespace Dialog { + +// See: http://developer.gnome.org/gtkmm/stable/classGtk_1_1TreeModelColumnRecord.html +class SymbolColumns : public Gtk::TreeModel::ColumnRecord +{ +public: + + Gtk::TreeModelColumn<Glib::ustring> symbol_id; + Gtk::TreeModelColumn<Glib::ustring> symbol_title; + Gtk::TreeModelColumn< Glib::RefPtr<Gdk::Pixbuf> > symbol_image; + + SymbolColumns() { + add(symbol_id); + add(symbol_title); + add(symbol_image); + } +}; + +SymbolColumns* SymbolsDialog::getColumns() +{ + SymbolColumns* columns = new SymbolColumns(); + return columns; +} + +/** + * Constructor + */ +SymbolsDialog::SymbolsDialog( gchar const* prefsPath ) : + UI::Widget::Panel("", prefsPath, SP_VERB_DIALOG_SYMBOLS), + store(Gtk::ListStore::create(*getColumns())), + iconView(0), + currentDesktop(0), + deskTrack(), + currentDocument(0), + previewDocument(0), + instanceConns() +{ + + /******************** Table *************************/ +#if WITH_GTKMM_3_0 + Gtk::Grid *table = new Gtk::Grid(); +#else + Gtk::Table *table = new Gtk::Table(2, 4, false); +#endif + + // panel is a cloked Gtk::VBox + _getContents()->pack_start(*Gtk::manage(table), Gtk::PACK_EXPAND_WIDGET); + guint row = 0; + + /******************** Symbol Sets *************************/ + Gtk::Label* labelSet = new Gtk::Label(_("Symbol set: ")); + +#if WITH_GTKMM_3_0 + table->attach(*Gtk::manage(labelSet),0,row,1,1); +#else + table->attach(*Gtk::manage(labelSet),0,1,row,row+1,Gtk::SHRINK,Gtk::SHRINK); +#endif + + symbolSet = new Gtk::ComboBoxText(); // Fill in later + symbolSet->append(_("Current Document")); + symbolSet->set_active_text(_("Current Document")); + +#if WITH_GTKMM_3_0 + symbolSet->set_hexpand(); + table->attach(*Gtk::manage(symbolSet),1,row,1,1); +#else + table->attach(*Gtk::manage(symbolSet),1,2,row,row+1,Gtk::FILL|Gtk::EXPAND,Gtk::SHRINK); +#endif + + sigc::connection connSet = symbolSet->signal_changed().connect( + sigc::mem_fun(*this, &SymbolsDialog::rebuild)); + instanceConns.push_back(connSet); + + ++row; + + /********************* Icon View **************************/ + SymbolColumns* columns = getColumns(); + + iconView = new Gtk::IconView(static_cast<Glib::RefPtr<Gtk::TreeModel> >(store)); + //iconView->set_text_column( columns->symbol_id ); + iconView->set_tooltip_column( 1 ); + iconView->set_pixbuf_column( columns->symbol_image ); + // Giving the iconview a small minimum size will help users understand + // What the dialog does. + iconView->set_size_request( 100, 200 ); + + std::vector< Gtk::TargetEntry > targets; + targets.push_back(Gtk::TargetEntry( "application/x-inkscape-paste")); + + iconView->enable_model_drag_source (targets, Gdk::BUTTON1_MASK, Gdk::ACTION_COPY); + iconView->signal_drag_data_get().connect( + sigc::mem_fun(*this, &SymbolsDialog::iconDragDataGet)); + + sigc::connection connIconChanged; + connIconChanged = iconView->signal_selection_changed().connect( + sigc::mem_fun(*this, &SymbolsDialog::iconChanged)); + instanceConns.push_back(connIconChanged); + + Gtk::ScrolledWindow *scroller = new Gtk::ScrolledWindow(); + scroller->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_ALWAYS); + scroller->add(*Gtk::manage(iconView)); + +#if WITH_GTKMM_3_0 + scroller->set_hexpand(); + scroller->set_vexpand(); + table->attach(*Gtk::manage(scroller),0,row,2,1); +#else + table->attach(*Gtk::manage(scroller),0,2,row,row+1,Gtk::EXPAND|Gtk::FILL,Gtk::EXPAND|Gtk::FILL); +#endif + + ++row; + + /******************** Tools *******************************/ + Gtk::Button* button; + Gtk::HBox* tools = new Gtk::HBox(); + + //tools->set_layout( Gtk::BUTTONBOX_END ); +#if WITH_GTKMM_3_0 + scroller->set_hexpand(); + table->attach(*Gtk::manage(tools),0,row,2,1); +#else + table->attach(*Gtk::manage(tools),0,2,row,row+1,Gtk::EXPAND|Gtk::FILL,Gtk::FILL); +#endif + + addSymbol = Gtk::manage(new Gtk::Button()); + addSymbol->add(*Gtk::manage(Glib::wrap( + sp_icon_new (Inkscape::ICON_SIZE_SMALL_TOOLBAR, INKSCAPE_ICON("symbol-add")))) ); + addSymbol->set_tooltip_text(_("Add Symbol from the current document.")); + addSymbol->set_relief( Gtk::RELIEF_NONE ); + addSymbol->set_focus_on_click( false ); + addSymbol->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::insertSymbol)); + tools->pack_start(* addSymbol, Gtk::PACK_SHRINK); + + removeSymbol = Gtk::manage(new Gtk::Button()); + removeSymbol->add(*Gtk::manage(Glib::wrap( + sp_icon_new (Inkscape::ICON_SIZE_SMALL_TOOLBAR, INKSCAPE_ICON("symbol-remove")))) ); + removeSymbol->set_tooltip_text(_("Remove Symbol from the current document.")); + removeSymbol->set_relief( Gtk::RELIEF_NONE ); + removeSymbol->set_focus_on_click( false ); + removeSymbol->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::revertSymbol)); + tools->pack_start(* removeSymbol, Gtk::PACK_SHRINK); + + Gtk::Label* spacer = Gtk::manage(new Gtk::Label("")); + tools->pack_start(* Gtk::manage(spacer)); + + in_sizes = 2; // Default 32px + button = Gtk::manage(new Gtk::Button()); + button->add(*Gtk::manage(Glib::wrap( + sp_icon_new (Inkscape::ICON_SIZE_SMALL_TOOLBAR, INKSCAPE_ICON("symbol-bigger")))) ); + button->set_tooltip_text(_("Make Icons bigger by zooming in.")); + button->set_relief( Gtk::RELIEF_NONE ); + button->set_focus_on_click( false ); + button->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::zoomin)); + tools->pack_start(* button, Gtk::PACK_SHRINK); + + button = Gtk::manage(new Gtk::Button()); + button->add(*Gtk::manage(Glib::wrap( + sp_icon_new (Inkscape::ICON_SIZE_SMALL_TOOLBAR, INKSCAPE_ICON("symbol-smaller")))) ); + button->set_tooltip_text(_("Make Icons smaller by zooming out.")); + button->set_relief( Gtk::RELIEF_NONE ); + button->set_focus_on_click( false ); + button->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::zoomout)); + tools->pack_start(* button, Gtk::PACK_SHRINK); + + fitSymbol = Gtk::manage(new Gtk::ToggleButton()); + fitSymbol->add(*Gtk::manage(Glib::wrap( + sp_icon_new (Inkscape::ICON_SIZE_SMALL_TOOLBAR, INKSCAPE_ICON("symbol-fit")))) ); + fitSymbol->set_tooltip_text(_("Toggle 'fit' symbols in icon space.")); + fitSymbol->set_relief( Gtk::RELIEF_NONE ); + fitSymbol->set_focus_on_click( false ); + fitSymbol->set_active( true ); + fitSymbol->signal_clicked().connect(sigc::mem_fun(*this, &SymbolsDialog::rebuild)); + tools->pack_start(* fitSymbol, Gtk::PACK_SHRINK); + + ++row; + + /**********************************************************/ + currentDesktop = inkscape_active_desktop(); + currentDocument = sp_desktop_document(currentDesktop); + + previewDocument = symbols_preview_doc(); /* Template to render symbols in */ + previewDocument->ensureUpToDate(); /* Necessary? */ + + key = SPItem::display_key_new(1); + renderDrawing.setRoot(previewDocument->getRoot()->invoke_show(renderDrawing, key, SP_ITEM_SHOW_DISPLAY )); + + // This might need to be a global variable so setTargetDesktop can modify it + SPDefs *defs = currentDocument->getDefs(); + sigc::connection defsModifiedConn = (SP_OBJECT(defs))->connectModified( + sigc::mem_fun(*this, &SymbolsDialog::defsModified)); + instanceConns.push_back(defsModifiedConn); + + sigc::connection selectionChangedConn = currentDesktop->selection->connectChanged( + sigc::mem_fun(*this, &SymbolsDialog::selectionChanged)); + instanceConns.push_back(selectionChangedConn); + + sigc::connection documentReplacedConn = currentDesktop->connectDocumentReplaced( + sigc::mem_fun(*this, &SymbolsDialog::documentReplaced)); + instanceConns.push_back(documentReplacedConn); + + get_symbols(); + add_symbols( currentDocument ); /* Defaults to current document */ + + sigc::connection desktopChangeConn = + deskTrack.connectDesktopChanged( sigc::mem_fun(*this, &SymbolsDialog::setTargetDesktop) ); + instanceConns.push_back( desktopChangeConn ); + + deskTrack.connect(GTK_WIDGET(gobj())); +} + +SymbolsDialog::~SymbolsDialog() +{ + for (std::vector<sigc::connection>::iterator it = instanceConns.begin(); it != instanceConns.end(); ++it) { + it->disconnect(); + } + instanceConns.clear(); + deskTrack.disconnect(); +} + +SymbolsDialog& SymbolsDialog::getInstance() +{ + return *new SymbolsDialog(); +} + +void SymbolsDialog::zoomin() { + if(in_sizes < 4) { + in_sizes++; + rebuild(); + } +} + +void SymbolsDialog::zoomout() { + if(in_sizes > 0) { + in_sizes--; + rebuild(); + } +} + +void SymbolsDialog::rebuild() { + + store->clear(); + Glib::ustring symbolSetString = symbolSet->get_active_text(); + + SPDocument* symbolDocument = symbolSets[symbolSetString]; + if( !symbolDocument ) { + // Symbol must be from Current Document (this method of + // checking should be language independent). + symbolDocument = currentDocument; + addSymbol->set_sensitive( true ); + removeSymbol->set_sensitive( true ); + } else { + addSymbol->set_sensitive( false ); + removeSymbol->set_sensitive( false ); + } + add_symbols( symbolDocument ); +} + +void SymbolsDialog::insertSymbol() { + Inkscape::Verb *verb = Inkscape::Verb::get( SP_VERB_EDIT_SYMBOL ); + SPAction *action = verb->get_action(Inkscape::ActionContext( (Inkscape::UI::View::View *) this->currentDesktop) ); + sp_action_perform (action, NULL); +} + +void SymbolsDialog::revertSymbol() { + Inkscape::Verb *verb = Inkscape::Verb::get( SP_VERB_EDIT_UNSYMBOL ); + SPAction *action = verb->get_action(Inkscape::ActionContext( (Inkscape::UI::View::View *) this->currentDesktop ) ); + sp_action_perform (action, NULL); +} + +void SymbolsDialog::iconDragDataGet(const Glib::RefPtr<Gdk::DragContext>& /*context*/, Gtk::SelectionData& data, guint /*info*/, guint /*time*/) +{ +#if WITH_GTKMM_3_0 + std::vector<Gtk::TreePath> iconArray = iconView->get_selected_items(); +#else + Gtk::IconView::ArrayHandle_TreePaths iconArray = iconView->get_selected_items(); +#endif + + if( iconArray.empty() ) { + //std::cout << " iconArray empty: huh? " << std::endl; + } else { + Gtk::TreeModel::Path const & path = *iconArray.begin(); + Gtk::ListStore::iterator row = store->get_iter(path); + Glib::ustring symbol_id = (*row)[getColumns()->symbol_id]; + + GdkAtom dataAtom = gdk_atom_intern( "application/x-inkscape-paste", FALSE ); + gtk_selection_data_set( data.gobj(), dataAtom, 9, (guchar*)symbol_id.c_str(), symbol_id.length() ); + } + +} + +void SymbolsDialog::defsModified(SPObject * /*object*/, guint /*flags*/) +{ + if ( !symbolSets[symbolSet->get_active_text()] ) { + rebuild(); + } +} + +void SymbolsDialog::selectionChanged(Inkscape::Selection *selection) { + Glib::ustring symbol_id = selectedSymbolId(); + SPDocument* symbolDocument = selectedSymbols(); + SPObject* symbol = symbolDocument->getObjectById(symbol_id); + + if(symbol && !selection->includes(symbol)) { + iconView->unselect_all(); + } +} + +void SymbolsDialog::documentReplaced(SPDesktop *desktop, SPDocument *document) +{ + currentDesktop = desktop; + currentDocument = document; + rebuild(); +} + +SPDocument* SymbolsDialog::selectedSymbols() { + /* OK, we know symbol name... now we need to copy it to clipboard, bon chance! */ + Glib::ustring symbolSetString = symbolSet->get_active_text(); + + SPDocument* symbolDocument = symbolSets[symbolSetString]; + if( !symbolDocument ) { + // Symbol must be from Current Document (this method of checking should be language independent). + return currentDocument; + } + return symbolDocument; +} + +Glib::ustring SymbolsDialog::selectedSymbolId() { + +#if WITH_GTKMM_3_0 + std::vector<Gtk::TreePath> iconArray = iconView->get_selected_items(); +#else + Gtk::IconView::ArrayHandle_TreePaths iconArray = iconView->get_selected_items(); +#endif + + if( !iconArray.empty() ) { + Gtk::TreeModel::Path const & path = *iconArray.begin(); + Gtk::ListStore::iterator row = store->get_iter(path); + return (*row)[getColumns()->symbol_id]; + } + return Glib::ustring(""); +} + +void SymbolsDialog::iconChanged() { + + Glib::ustring symbol_id = selectedSymbolId(); + SPDocument* symbolDocument = selectedSymbols(); + SPObject* symbol = symbolDocument->getObjectById(symbol_id); + + if( symbol ) { + if( symbolDocument == currentDocument ) { + // Select the symbol on the canvas so it can be manipulated + currentDesktop->selection->set( symbol, false ); + } + + // Find style for use in <use> + // First look for default style stored in <symbol> + gchar const* style = symbol->getAttribute("inkscape:symbol-style"); + if( !style ) { + // If no default style in <symbol>, look in documents. + if( symbolDocument == currentDocument ) { + style = style_from_use( symbol_id.c_str(), currentDocument ); + } else { + style = symbolDocument->getReprRoot()->attribute("style"); + } + } + + ClipboardManager *cm = ClipboardManager::get(); + cm->copySymbol(symbol->getRepr(), style); + } +} + +#ifdef WITH_LIBVISIO +// Read Visio stencil files +SPDocument* read_vss( gchar* fullname, gchar* filename ) { + + WPXFileStream input(fullname); + + if (!libvisio::VisioDocument::isSupported(&input)) { + return NULL; + } + + libvisio::VSDStringVector output; + if (!libvisio::VisioDocument::generateSVGStencils(&input, output)) { + return NULL; + } + + if (output.empty()) { + return NULL; + } + + Glib::ustring tmpSVGOutput; + tmpSVGOutput += "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"; + tmpSVGOutput += "<svg\n"; + tmpSVGOutput += " xmlns=\"http://www.w3.org/2000/svg\"\n"; + tmpSVGOutput += " xmlns:svg=\"http://www.w3.org/2000/svg\"\n"; + tmpSVGOutput += " xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"; + tmpSVGOutput += " version=\"1.1\"\n"; + tmpSVGOutput += " style=\"fill:none;stroke:#000000;stroke-width:2\">\n"; + tmpSVGOutput += " <title>"; + tmpSVGOutput += filename; + tmpSVGOutput += "</title>\n"; + tmpSVGOutput += " <defs>\n"; + + // Create a string we can use for the symbol id (libvisio doesn't give us a name) + std::string sanitized( filename ); + sanitized.erase( sanitized.find_last_of(".vss")-3 ); + sanitized.erase( std::remove_if( sanitized.begin(), sanitized.end(), ispunct ), sanitized.end() ); + std::replace( sanitized.begin(), sanitized.end(), ' ', '_' ); + // std::cout << filename << " |" << sanitized << "|" << std::endl; + + // Each "symbol" is in it's own SVG file, we wrap with <symbol> and merge into one file. + for (unsigned i=0; i<output.size(); ++i) { + + std::stringstream ss; + ss << i; + + tmpSVGOutput += " <symbol id=\""; + tmpSVGOutput += sanitized; + tmpSVGOutput += "_"; + tmpSVGOutput += ss.str(); + tmpSVGOutput += "\">\n"; + + std::istringstream iss( output[i].cstr() ); + std::string line; + while( std::getline( iss, line ) ) { + // std::cout << line << std::endl; + if( line.find( "svg:svg" ) == std::string::npos ) { + tmpSVGOutput += line; + tmpSVGOutput += "\n"; + } + } + + tmpSVGOutput += " </symbol>\n"; + } + + tmpSVGOutput += " </defs>\n"; + tmpSVGOutput += "</svg>\n"; + + return SPDocument::createNewDocFromMem( tmpSVGOutput.c_str(), strlen( tmpSVGOutput.c_str()), 0 ); + +} +#endif + +/* Hunts preference directories for symbol files */ +void SymbolsDialog::get_symbols() { + + std::list<Glib::ustring> directories; + + if( Inkscape::IO::file_test( INKSCAPE_SYMBOLSDIR, G_FILE_TEST_EXISTS ) && + Inkscape::IO::file_test( INKSCAPE_SYMBOLSDIR, G_FILE_TEST_IS_DIR ) ) { + directories.push_back( INKSCAPE_SYMBOLSDIR ); + } + if( Inkscape::IO::file_test( profile_path("symbols"), G_FILE_TEST_EXISTS ) && + Inkscape::IO::file_test( profile_path("symbols"), G_FILE_TEST_IS_DIR ) ) { + directories.push_back( profile_path("symbols") ); + } + + std::list<Glib::ustring>::iterator it; + for( it = directories.begin(); it != directories.end(); ++it ) { + + GError *err = 0; + GDir *dir = g_dir_open( (*it).c_str(), 0, &err ); + if( dir ) { + + gchar *filename = 0; + while( (filename = (gchar *)g_dir_read_name( dir ) ) != NULL) { + + gchar *fullname = g_build_filename((*it).c_str(), filename, NULL); + + if ( !Inkscape::IO::file_test( fullname, G_FILE_TEST_IS_DIR ) + && ( Glib::str_has_suffix(fullname, ".svg") || Glib::str_has_suffix(fullname, ".vss") ) ) { + + Glib::ustring fn( filename ); + Glib::ustring tag = fn.substr( fn.find_last_of(".") + 1 ); + + SPDocument* symbol_doc = NULL; + +#ifdef WITH_LIBVISIO + if( tag.compare( "vss" ) == 0 ) { + + symbol_doc = read_vss( fullname, filename ); + if( symbol_doc ) { + symbolSets[Glib::ustring(filename)]= symbol_doc; + symbolSet->append(filename); + } + } +#endif + // Try to read all remaining files as SVG + if( !symbol_doc ) { + + symbol_doc = SPDocument::createNewDoc( fullname, FALSE ); + if( symbol_doc ) { + + const gchar *title = symbol_doc->getRoot()->title(); + + // A user provided file may not have a title + if( title != NULL ) { + title = g_dpgettext2(NULL, "Symbol", title); // Translate + } else { + title = _("Unnamed Symbols"); + } + + symbolSets[Glib::ustring(title)] = symbol_doc; + symbolSet->append(title); + } + } + + } + g_free( fullname ); + } + g_dir_close( dir ); + } + } +} + +GSList* SymbolsDialog::symbols_in_doc_recursive (SPObject *r, GSList *l) +{ + g_return_val_if_fail(r != NULL, l); + + // Stop multiple counting of same symbol + if( SP_IS_USE(r) ) { + return l; + } + + if( SP_IS_SYMBOL(r) ) { + l = g_slist_prepend (l, r); + } + + for (SPObject *child = r->firstChild(); child; child = child->getNext()) { + l = symbols_in_doc_recursive( child, l ); + } + + return l; +} + +GSList* SymbolsDialog::symbols_in_doc( SPDocument* symbolDocument ) { + + GSList *l = NULL; + l = symbols_in_doc_recursive (symbolDocument->getRoot(), l ); + return l; +} + +GSList* SymbolsDialog::use_in_doc_recursive (SPObject *r, GSList *l) +{ + + if( SP_IS_USE(r) ) { + l = g_slist_prepend (l, r); + } + + for (SPObject *child = r->firstChild(); child; child = child->getNext()) { + l = use_in_doc_recursive( child, l ); + } + + return l; +} + +GSList* SymbolsDialog::use_in_doc( SPDocument* useDocument ) { + + GSList *l = NULL; + l = use_in_doc_recursive (useDocument->getRoot(), l ); + return l; +} + +// Returns style from first <use> element found that references id. +// This is a last ditch effort to find a style. +gchar const* SymbolsDialog::style_from_use( gchar const* id, SPDocument* document) { + + gchar const* style = 0; + GSList* l = use_in_doc( document ); + for( ; l != NULL; l = l->next ) { + SPObject* use = SP_OBJECT(l->data); + if( SP_IS_USE( use ) ) { + gchar const *href = use->getRepr()->attribute("xlink:href"); + if( href ) { + Glib::ustring href2(href); + Glib::ustring id2(id); + id2 = "#" + id2; + if( !href2.compare(id2) ) { + style = use->getRepr()->attribute("style"); + break; + } + } + } + } + return style; +} + +void SymbolsDialog::add_symbols( SPDocument* symbolDocument ) { + + GSList* l = symbols_in_doc( symbolDocument ); + for( ; l != NULL; l = l->next ) { + SPObject* symbol = SP_OBJECT(l->data); + if (SP_IS_SYMBOL(symbol)) { + add_symbol( symbol ); + } + } +} + +void SymbolsDialog::add_symbol( SPObject* symbol ) { + + SymbolColumns* columns = getColumns(); + + gchar const *id = symbol->getRepr()->attribute("id"); + gchar const *title = symbol->title(); // From title element + if( !title ) { + title = id; + } + + Glib::RefPtr<Gdk::Pixbuf> pixbuf = draw_symbol( symbol ); + + if( pixbuf ) { + Gtk::ListStore::iterator row = store->append(); + (*row)[columns->symbol_id] = Glib::ustring( id ); + (*row)[columns->symbol_title] = Glib::Markup::escape_text(Glib::ustring( g_dpgettext2(NULL, "Symbol", title) )); + (*row)[columns->symbol_image] = pixbuf; + } + + delete columns; +} + +/* + * Returns image of symbol. + * + * Symbols normally are not visible. They must be referenced by a + * <use> element. A temporary document is created with a dummy + * <symbol> element and a <use> element that references the symbol + * element. Each real symbol is swapped in for the dummy symbol and + * the temporary document is rendered. + */ +Glib::RefPtr<Gdk::Pixbuf> +SymbolsDialog::draw_symbol(SPObject *symbol) +{ + // Create a copy repr of the symbol with id="the_symbol" + Inkscape::XML::Document *xml_doc = previewDocument->getReprDoc(); + Inkscape::XML::Node *repr = symbol->getRepr()->duplicate(xml_doc); + repr->setAttribute("id", "the_symbol"); + + // Replace old "the_symbol" in previewDocument by new. + Inkscape::XML::Node *root = previewDocument->getReprRoot(); + SPObject *symbol_old = previewDocument->getObjectById("the_symbol"); + if (symbol_old) { + symbol_old->deleteObject(false); + } + + // First look for default style stored in <symbol> + gchar const* style = repr->attribute("inkscape:symbol-style"); + if( !style ) { + // If no default style in <symbol>, look in documents. + if( symbol->document == currentDocument ) { + gchar const *id = symbol->getRepr()->attribute("id"); + style = style_from_use( id, symbol->document ); + } else { + style = symbol->document->getReprRoot()->attribute("style"); + } + } + // Last ditch effort to provide some default styling + if( !style ) style = "fill:#bbbbbb;stroke:#808080"; + + // This is for display in Symbols dialog only + if( style ) repr->setAttribute( "style", style ); + + // BUG: Symbols don't work if defined outside of <defs>. Causes Inkscape + // crash when trying to read in such a file. + root->appendChild(repr); + //defsrepr->appendChild(repr); + Inkscape::GC::release(repr); + + // Uncomment this to get the previewDocument documents saved (useful for debugging) + // FILE *fp = fopen (g_strconcat(id, ".svg", NULL), "w"); + // sp_repr_save_stream(previewDocument->getReprDoc(), fp); + // fclose (fp); + + // Make sure previewDocument is up-to-date. + previewDocument->getRoot()->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + previewDocument->ensureUpToDate(); + + // Make sure we have symbol in previewDocument + SPObject *object_temp = previewDocument->getObjectById( "the_use" ); + previewDocument->getRoot()->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); + previewDocument->ensureUpToDate(); + + SPItem *item = SP_ITEM(object_temp); + unsigned psize = SYMBOL_ICON_SIZES[in_sizes]; + + Glib::RefPtr<Gdk::Pixbuf> pixbuf(NULL); + // We could use cache here, but it doesn't really work with the structure + // of this user interface and we've already cached the pixbuf in the gtklist + + // Find object's bbox in document. + // Note symbols can have own viewport... ignore for now. + //Geom::OptRect dbox = item->geometricBounds(); + Geom::OptRect dbox = item->documentVisualBounds(); + + if (dbox) { + /* Scale symbols to fit */ + double scale = 1.0; + double width = dbox->width(); + double height = dbox->height(); + + if( width == 0.0 ) width = 1.0; + if( height == 0.0 ) height = 1.0; + + if( fitSymbol->get_active() ) + scale = psize / std::max(width, height); + + pixbuf = Glib::wrap(render_pixbuf(renderDrawing, scale, *dbox, psize)); + } + + return pixbuf; +} + +/* + * Return empty doc to render symbols in. + * Symbols are by default not rendered so a <use> element is + * provided. + */ +SPDocument* SymbolsDialog::symbols_preview_doc() +{ + // BUG: <symbol> must be inside <defs> + gchar const *buffer = +"<svg xmlns=\"http://www.w3.org/2000/svg\"" +" xmlns:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"" +" xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\"" +" xmlns:xlink=\"http://www.w3.org/1999/xlink\">" +" <defs id=\"defs\">" +" <symbol id=\"the_symbol\"/>" +" </defs>" +" <use id=\"the_use\" xlink:href=\"#the_symbol\"/>" +"</svg>"; + + return SPDocument::createNewDocFromMem( buffer, strlen(buffer), FALSE ); +} + +void SymbolsDialog::setTargetDesktop(SPDesktop *desktop) +{ + if (this->currentDesktop != desktop) { + this->currentDesktop = desktop; + if( !symbolSets[symbolSet->get_active_text()] ) { + // Symbol set is from Current document, update + rebuild(); + } + } +} + +} //namespace Dialogs +} //namespace UI +} //namespace Inkscape + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-basic-offset:2 + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=2:tabstop=8:softtabstop=2:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/dialog/symbols.h b/src/ui/dialog/symbols.h new file mode 100644 index 000000000..8021fb0c1 --- /dev/null +++ b/src/ui/dialog/symbols.h @@ -0,0 +1,136 @@ +/** @file + * @brief Symbols dialog + */ +/* Authors: + * Tavmjong Bah, Martin Owens + * + * Copyright (C) 2012 Tavmjong Bah + * 2013 Martin Owens + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifndef INKSCAPE_UI_DIALOG_SYMBOLS_H +#define INKSCAPE_UI_DIALOG_SYMBOLS_H + +#include "display/drawing.h" + +#include "ui/dialog/desktop-tracker.h" + +#include "ui/widget/panel.h" + +#include <vector> + +class SPObject; + +namespace Inkscape { +namespace UI { +namespace Dialog { + +class SymbolColumns; // For Gtk::ListStore + +/** + * A dialog that displays selectable symbols and allows users to drag or paste + * those symbols from the dialog into the document. + * + * Symbol documents are loaded from the preferences paths and displayed in a + * drop-down list to the user. The user then selects which of the symbols + * documents they want to get symbols from. The first document in the list is + * always the current document. + * + * This then updates an icon-view with all the symbols available. Selecting one + * puts it onto the clipboard. Dragging it or pasting it onto the canvas copies + * the symbol from the symbol document, into the current document and places a + * new <use element at the correct location on the canvas. + * + * Selected groups on the canvas can be added to the current document's symbols + * table, and symbols can be removed from the current document. This allows + * new symbols documents to be constructed and if saved in the prefs folder will + * make those symbols available for all future documents. + */ + +const int SYMBOL_ICON_SIZES[] = {16, 24, 32, 48, 64}; + +class SymbolsDialog : public UI::Widget::Panel { + +public: + SymbolsDialog( gchar const* prefsPath = "/dialogs/symbols" ); + virtual ~SymbolsDialog(); + + static SymbolsDialog& getInstance(); + +private: + SymbolsDialog(SymbolsDialog const &); // no copy + SymbolsDialog &operator=(SymbolsDialog const &); // no assign + + static SymbolColumns *getColumns(); + + void zoomin(); + void zoomout(); + void rebuild(); + void insertSymbol(); + void revertSymbol(); + void defsModified(SPObject *object, guint flags); + void selectionChanged(Inkscape::Selection *selection); + void documentReplaced(SPDesktop *desktop, SPDocument *document); + SPDocument* selectedSymbols(); + Glib::ustring selectedSymbolId(); + void iconChanged(); + void iconDragDataGet(const Glib::RefPtr<Gdk::DragContext>& context, Gtk::SelectionData& selection_data, guint info, guint time); + + void get_symbols(); + void add_symbols( SPDocument* symbol_document ); + void add_symbol( SPObject* symbol_document ); + SPDocument* symbols_preview_doc(); + + GSList* symbols_in_doc_recursive(SPObject *r, GSList *l); + GSList* symbols_in_doc( SPDocument* document ); + GSList* use_in_doc_recursive(SPObject *r, GSList *l); + GSList* use_in_doc( SPDocument* document ); + gchar const* style_from_use( gchar const* id, SPDocument* document); + + Glib::RefPtr<Gdk::Pixbuf> draw_symbol(SPObject *symbol); + + /* Keep track of all symbol template documents */ + std::map<Glib::ustring, SPDocument*> symbolSets; + + // Index into sizes which is selected + int in_sizes; + + Glib::RefPtr<Gtk::ListStore> store; + Gtk::ComboBoxText* symbolSet; + Gtk::IconView* iconView; + Gtk::Button* addSymbol; + Gtk::Button* removeSymbol; + Gtk::ToggleButton* fitSymbol; + + void setTargetDesktop(SPDesktop *desktop); + SPDesktop* currentDesktop; + DesktopTracker deskTrack; + SPDocument* currentDocument; + SPDocument* previewDocument; /* Document to render single symbol */ + + /* For rendering the template drawing */ + unsigned key; + Inkscape::Drawing renderDrawing; + + std::vector<sigc::connection> instanceConns; +}; + +} //namespace Dialogs +} //namespace UI +} //namespace Inkscape + + +#endif // INKSCAPE_UI_DIALOG_SYMBOLS_H + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/dialog/template-load-tab.cpp b/src/ui/dialog/template-load-tab.cpp new file mode 100644 index 000000000..6b1f4542f --- /dev/null +++ b/src/ui/dialog/template-load-tab.cpp @@ -0,0 +1,322 @@ +/** @file + * @brief New From Template abstract tab implementation + */ +/* Authors: + * Jan Darowski <jan.darowski@gmail.com>, supervised by Krzysztof Kosiński + * + * Copyright (C) 2013 Authors + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "template-widget.h" +#include "template-load-tab.h" +#include "new-from-template.h" + +#include <gtkmm/messagedialog.h> +#include <gtkmm/scrolledwindow.h> +#include <glibmm/i18n.h> +#include <glibmm/fileutils.h> +#include <glibmm/miscutils.h> +#include <glibmm/stringutils.h> +#include <iostream> +#include <list> + +#include "extension/db.h" +#include "extension/effect.h" +#include "inkscape.h" +#include "interface.h" +#include "file.h" +#include "path-prefix.h" +#include "preferences.h" +#include "xml/repr.h" +#include "xml/document.h" +#include "xml/node.h" + +namespace Inkscape { +namespace UI { + +TemplateLoadTab::TemplateLoadTab() + : _current_keyword("") + , _keywords_combo(true) + , _current_search_type(ALL) +{ + set_border_width(10); + + _info_widget = manage(new TemplateWidget()); + + Gtk::Label *title; + title = manage(new Gtk::Label(_("Search:"))); + _search_box.pack_start(*title, Gtk::PACK_SHRINK); + _search_box.pack_start(_keywords_combo, Gtk::PACK_SHRINK, 5); + + _tlist_box.pack_start(_search_box, Gtk::PACK_SHRINK, 10); + + pack_start(_tlist_box, Gtk::PACK_SHRINK); + pack_start(*_info_widget, Gtk::PACK_EXPAND_WIDGET, 5); + + Gtk::ScrolledWindow *scrolled; + scrolled = manage(new Gtk::ScrolledWindow()); + scrolled->set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); + scrolled->add(_tlist_view); + _tlist_box.pack_start(*scrolled, Gtk::PACK_EXPAND_WIDGET, 5); + + _keywords_combo.signal_changed().connect( + sigc::mem_fun(*this, &TemplateLoadTab::_keywordSelected)); + this->show_all(); + + _loading_path = ""; + _loadTemplates(); + _initLists(); +} + + +TemplateLoadTab::~TemplateLoadTab() +{ +} + + +void TemplateLoadTab::createTemplate() +{ + _info_widget->create(); +} + + +void TemplateLoadTab::_onRowActivated(const Gtk::TreeModel::Path &, Gtk::TreeViewColumn*) +{ + createTemplate(); + NewFromTemplate* parent = static_cast<NewFromTemplate*> (this->get_toplevel()); + parent->_onClose(); +} + +void TemplateLoadTab::_displayTemplateInfo() +{ + Glib::RefPtr<Gtk::TreeSelection> templateSelectionRef = _tlist_view.get_selection(); + if (templateSelectionRef->get_selected()) { + _current_template = (*templateSelectionRef->get_selected())[_columns.textValue]; + + _info_widget->display(_tdata[_current_template]); + } + +} + + +void TemplateLoadTab::_initKeywordsList() +{ + _keywords_combo.append(_("All")); + + for (std::set<Glib::ustring>::iterator it = _keywords.begin() ; it != _keywords.end() ; ++it){ + _keywords_combo.append(*it); + } +} + + +void TemplateLoadTab::_initLists() +{ + _tlist_store = Gtk::ListStore::create(_columns); + _tlist_view.set_model(_tlist_store); + _tlist_view.append_column("", _columns.textValue); + _tlist_view.set_headers_visible(false); + + _initKeywordsList(); + _refreshTemplatesList(); + + Glib::RefPtr<Gtk::TreeSelection> templateSelectionRef = + _tlist_view.get_selection(); + templateSelectionRef->signal_changed().connect( + sigc::mem_fun(*this, &TemplateLoadTab::_displayTemplateInfo)); + + _tlist_view.signal_row_activated().connect( + sigc::mem_fun(*this, &TemplateLoadTab::_onRowActivated)); +} + +void TemplateLoadTab::_keywordSelected() +{ + _current_keyword = _keywords_combo.get_active_text(); + if (_current_keyword == ""){ + _current_keyword = _keywords_combo.get_entry_text(); + _current_search_type = USER_SPECIFIED; + } + else + _current_search_type = LIST_KEYWORD; + + if (_current_keyword == "" || _current_keyword == _("All")) + _current_search_type = ALL; + + _refreshTemplatesList(); +} + + +void TemplateLoadTab::_refreshTemplatesList() +{ + _tlist_store->clear(); + + switch (_current_search_type){ + case ALL :{ + + for (std::map<Glib::ustring, TemplateData>::iterator it = _tdata.begin() ; it != _tdata.end() ; ++it) { + Gtk::TreeModel::iterator iter = _tlist_store->append(); + Gtk::TreeModel::Row row = *iter; + row[_columns.textValue] = it->first; + } + break; + } + + case LIST_KEYWORD: { + for (std::map<Glib::ustring, TemplateData>::iterator it = _tdata.begin() ; it != _tdata.end() ; ++it) { + if (it->second.keywords.count(_current_keyword.lowercase()) != 0){ + Gtk::TreeModel::iterator iter = _tlist_store->append(); + Gtk::TreeModel::Row row = *iter; + row[_columns.textValue] = it->first; + } + } + break; + } + + case USER_SPECIFIED : { + for (std::map<Glib::ustring, TemplateData>::iterator it = _tdata.begin() ; it != _tdata.end() ; ++it) { + if (it->second.keywords.count(_current_keyword.lowercase()) != 0 || + it->second.display_name.lowercase().find(_current_keyword.lowercase()) != Glib::ustring::npos || + it->second.author.lowercase().find(_current_keyword.lowercase()) != Glib::ustring::npos || + it->second.short_description.lowercase().find(_current_keyword.lowercase()) != Glib::ustring::npos || + it->second.long_description.lowercase().find(_current_keyword.lowercase()) != Glib::ustring::npos ) + { + Gtk::TreeModel::iterator iter = _tlist_store->append(); + Gtk::TreeModel::Row row = *iter; + row[_columns.textValue] = it->first; + } + } + break; + } + } +} + + +void TemplateLoadTab::_loadTemplates() +{ + // user's local dir + _getTemplatesFromDir(profile_path("templates") + _loading_path); + + // system templates dir + _getTemplatesFromDir(INKSCAPE_TEMPLATESDIR + _loading_path); + + // procedural templates + _getProceduralTemplates(); +} + + +TemplateLoadTab::TemplateData TemplateLoadTab::_processTemplateFile(const std::string &path) +{ + TemplateData result; + result.path = path; + result.is_procedural = false; + result.preview_name = ""; + + // convert path into valid template name + result.display_name = Glib::path_get_basename(path); + gsize n = 0; + while ((n = result.display_name.find_first_of("_", 0)) < Glib::ustring::npos){ + result.display_name.replace(n, 1, 1, ' '); + } + n = result.display_name.rfind(".svg"); + result.display_name.replace(n, 4, 1, ' '); + + Inkscape::XML::Document *rdoc = sp_repr_read_file(path.data(), SP_SVG_NS_URI); + if (rdoc){ + Inkscape::XML::Node *myRoot = rdoc->root(); + if (strcmp(myRoot->name(), "svg:svg") != 0){ // Wrong file format + return result; + } + + myRoot = sp_repr_lookup_name(myRoot, "inkscape:_templateinfo"); + + if (myRoot == NULL) // No template info + return result; + _getDataFromNode(myRoot, result); + } + + return result; +} + + +void TemplateLoadTab::_getTemplatesFromDir(const std::string &path) +{ + if ( !Glib::file_test(path, Glib::FILE_TEST_EXISTS) || + !Glib::file_test(path, Glib::FILE_TEST_IS_DIR)) + return; + + Glib::Dir dir(path); + + std::string file = Glib::build_filename(path, dir.read_name()); + while (file != path){ + if (Glib::str_has_suffix(file, ".svg") && !Glib::str_has_prefix(Glib::path_get_basename(file), "default.")){ + TemplateData tmp = _processTemplateFile(file); + if (tmp.display_name != "") + _tdata[tmp.display_name] = tmp; + } + file = Glib::build_filename(path, dir.read_name()); + } +} + + +void TemplateLoadTab::_getProceduralTemplates() +{ + std::list<Inkscape::Extension::Effect *> effects; + Inkscape::Extension::db.get_effect_list(effects); + + std::list<Inkscape::Extension::Effect *>::iterator it = effects.begin(); + while (it != effects.end()){ + Inkscape::XML::Node *myRoot; + myRoot = (*it)->get_repr(); + myRoot = sp_repr_lookup_name(myRoot, "inkscape:_templateinfo"); + + if (myRoot){ + TemplateData result; + result.display_name = (*it)->get_name(); + result.is_procedural = true; + result.path = ""; + result.tpl_effect = *it; + + _getDataFromNode(myRoot, result); + _tdata[result.display_name] = result; + } + ++it; + } +} + + +void TemplateLoadTab::_getDataFromNode(Inkscape::XML::Node *dataNode, TemplateData &data) +{ + Inkscape::XML::Node *currentData; + if ((currentData = sp_repr_lookup_name(dataNode, "inkscape:_name")) != NULL) + data.display_name = _(currentData->firstChild()->content()); + if ((currentData = sp_repr_lookup_name(dataNode, "inkscape:author")) != NULL) + data.author = currentData->firstChild()->content(); + if ((currentData = sp_repr_lookup_name(dataNode, "inkscape:_shortdesc")) != NULL) + data.short_description = _( currentData->firstChild()->content()); + if ((currentData = sp_repr_lookup_name(dataNode, "inkscape:_long") )!= NULL) + data.long_description = _(currentData->firstChild()->content()); + if ((currentData = sp_repr_lookup_name(dataNode, "inkscape:preview")) != NULL) + data.preview_name = currentData->firstChild()->content(); + if ((currentData = sp_repr_lookup_name(dataNode, "inkscape:date")) != NULL) + data.creation_date = currentData->firstChild()->content(); + + if ((currentData = sp_repr_lookup_name(dataNode, "inkscape:_keywords")) != NULL){ + Glib::ustring tplKeywords = _(currentData->firstChild()->content()); + while (!tplKeywords.empty()){ + std::size_t pos = tplKeywords.find_first_of(" "); + if (pos == Glib::ustring::npos) + pos = tplKeywords.size(); + + Glib::ustring keyword = tplKeywords.substr(0, pos).data(); + data.keywords.insert(keyword.lowercase()); + _keywords.insert(keyword.lowercase()); + + if (pos == tplKeywords.size()) + break; + tplKeywords.erase(0, pos+1); + } + } +} + +} +} diff --git a/src/ui/dialog/template-load-tab.h b/src/ui/dialog/template-load-tab.h new file mode 100644 index 000000000..920ae6ca2 --- /dev/null +++ b/src/ui/dialog/template-load-tab.h @@ -0,0 +1,111 @@ +/** @file + * @brief New From Template abstract tab class + */ +/* Authors: + * Jan Darowski <jan.darowski@gmail.com>, supervised by Krzysztof Kosiński + * + * Copyright (C) 2013 Authors + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifndef INKSCAPE_SEEN_UI_DIALOG_TEMPLATE_LOAD_TAB_H +#define INKSCAPE_SEEN_UI_DIALOG_TEMPLATE_LOAD_TAB_H + +#include <gtkmm/box.h> +#include <gtkmm/comboboxtext.h> +#include <gtkmm/frame.h> +#include <gtkmm/liststore.h> +#include <gtkmm/treeview.h> +#include <map> +#include <set> +#include <string> + +#include "xml/node.h" +#include "extension/effect.h" + + +namespace Inkscape { +namespace UI { + +class TemplateWidget; + +class TemplateLoadTab : public Gtk::HBox +{ + +public: + struct TemplateData + { + bool is_procedural; + std::string path; + Glib::ustring display_name; + Glib::ustring author; + Glib::ustring short_description; + Glib::ustring long_description; + Glib::ustring preview_name; + Glib::ustring creation_date; + std::set<Glib::ustring> keywords; + Inkscape::Extension::Effect *tpl_effect; + }; + + TemplateLoadTab(); + virtual ~TemplateLoadTab(); + virtual void createTemplate(); + +protected: + class StringModelColumns : public Gtk::TreeModelColumnRecord + { + public: + StringModelColumns() + { + add(textValue); + } + + Gtk::TreeModelColumn<Glib::ustring> textValue; + }; + + Glib::ustring _current_keyword; + Glib::ustring _current_template; + std::string _loading_path; + std::map<Glib::ustring, TemplateData> _tdata; + std::set<Glib::ustring> _keywords; + + + virtual void _displayTemplateInfo(); + virtual void _initKeywordsList(); + virtual void _refreshTemplatesList(); + void _loadTemplates(); + void _initLists(); + + Gtk::VBox _tlist_box; + Gtk::HBox _search_box; + TemplateWidget *_info_widget; + + Gtk::ComboBoxText _keywords_combo; + + Gtk::TreeView _tlist_view; + Glib::RefPtr<Gtk::ListStore> _tlist_store; + StringModelColumns _columns; + +private: + enum SearchType + { + LIST_KEYWORD, + USER_SPECIFIED, + ALL + }; + + SearchType _current_search_type; + + void _getDataFromNode(Inkscape::XML::Node *, TemplateData &); + void _getProceduralTemplates(); + void _getTemplatesFromDir(const std::string &); + void _keywordSelected(); + TemplateData _processTemplateFile(const std::string &); + + void _onRowActivated(const Gtk::TreeModel::Path &, Gtk::TreeViewColumn*); +}; + +} +} + +#endif diff --git a/src/ui/dialog/template-widget.cpp b/src/ui/dialog/template-widget.cpp new file mode 100644 index 000000000..d8e6f9b4f --- /dev/null +++ b/src/ui/dialog/template-widget.cpp @@ -0,0 +1,138 @@ +/** @file + * @brief New From Template - templates widget - implementation + */ +/* Authors: + * Jan Darowski <jan.darowski@gmail.com>, supervised by Krzysztof Kosiński + * + * Copyright (C) 2013 Authors + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "template-widget.h" + +#include <gtkmm/alignment.h> +#include <gtkmm/button.h> +#include <gtkmm/label.h> +#include <gtkmm/messagedialog.h> + +#include <glibmm/i18n.h> +#include <glibmm/miscutils.h> + +#include "template-load-tab.h" +#include "desktop.h" +#include "desktop-handles.h" +#include "document.h" +#include "document-undo.h" +#include "file.h" +#include "extension/implementation/implementation.h" +#include "inkscape.h" + + +namespace Inkscape { +namespace UI { + + +TemplateWidget::TemplateWidget() + : _more_info_button(_("More info")) + , _short_description_label(" ") + , _template_name_label(_("no template selected")) + , _effect_prefs(NULL) +{ + pack_start(_template_name_label, Gtk::PACK_SHRINK, 10); + pack_start(_preview_box, Gtk::PACK_SHRINK, 0); + + _preview_box.pack_start(_preview_image, Gtk::PACK_EXPAND_PADDING, 15); + _preview_box.pack_start(_preview_render, Gtk::PACK_EXPAND_PADDING, 10); + + _short_description_label.set_line_wrap(true); + + Gtk::Alignment *align; + align = manage(new Gtk::Alignment(Gtk::ALIGN_END, Gtk::ALIGN_CENTER, 0.0, 0.0)); + pack_end(*align, Gtk::PACK_SHRINK); + align->add(_more_info_button); + + pack_end(_short_description_label, Gtk::PACK_SHRINK, 5); + + _more_info_button.signal_clicked().connect( + sigc::mem_fun(*this, &TemplateWidget::_displayTemplateDetails)); +} + + +void TemplateWidget::create() +{ + if (_current_template.display_name == "") + return; + + if (_current_template.is_procedural){ + SPDesktop *desktop = SP_ACTIVE_DESKTOP; + SPDesktop *desc = sp_file_new_default(); + _current_template.tpl_effect->effect(desc); + DocumentUndo::clearUndo(sp_desktop_document(desc)); + sp_desktop_document(desc)->setModifiedSinceSave(false); + + if (desktop) + desktop->clearWaitingCursor(); + } + else { + sp_file_new(_current_template.path); + } +} + + +void TemplateWidget::display(TemplateLoadTab::TemplateData data) +{ + _current_template = data; + + _template_name_label.set_text(_current_template.display_name); + _short_description_label.set_text(_current_template.short_description); + + _preview_render.hide(); + _preview_image.hide(); + + std::string imagePath = Glib::build_filename(Glib::path_get_dirname(_current_template.path), _current_template.preview_name); + if (data.preview_name != ""){ + _preview_image.set(imagePath); + _preview_image.show(); + } + else if (!data.is_procedural){ + Glib::ustring gPath = data.path.c_str(); + _preview_render.showImage(gPath); + _preview_render.show(); + } + + if (_effect_prefs != NULL){ + remove (*_effect_prefs); + _effect_prefs = NULL; + } + if (data.is_procedural){ + _effect_prefs = data.tpl_effect->get_imp()->prefs_effect(data.tpl_effect, SP_ACTIVE_DESKTOP, NULL, NULL); + pack_start(*_effect_prefs); + } +} + + +void TemplateWidget::_displayTemplateDetails() +{ + Glib::ustring message = _current_template.display_name + "\n\n"; + + if (_current_template.path != "") + message += _("Path: ") + _current_template.path + "\n\n"; + + if (_current_template.long_description != "") + message += _("Description: ") + _current_template.long_description + "\n\n"; + if (~_current_template.keywords.empty()){ + message += _("Keywords: "); + for (std::set<Glib::ustring>::iterator it = _current_template.keywords.begin(); it != _current_template.keywords.end(); ++it) + message += *it + " "; + message += "\n\n"; + } + + if (_current_template.author != "") + message += _("By: ") + _current_template.author + " " + _current_template.creation_date + "\n\n"; + + Gtk::MessageDialog dl(message, false, Gtk::MESSAGE_OTHER); + dl.run(); +} + +} +} diff --git a/src/ui/dialog/template-widget.h b/src/ui/dialog/template-widget.h new file mode 100644 index 000000000..bb35d26a0 --- /dev/null +++ b/src/ui/dialog/template-widget.h @@ -0,0 +1,49 @@ +/** @file + * @brief New From Template - template widget + */ +/* Authors: + * Jan Darowski <jan.darowski@gmail.com>, supervised by Krzysztof Kosiński + * + * Copyright (C) 2013 Authors + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifndef INKSCAPE_SEEN_UI_DIALOG_TEMPLATE_WIDGET_H +#define INKSCAPE_SEEN_UI_DIALOG_TEMPLATE_WIDGET_H + +#include "filedialogimpl-gtkmm.h" + +#include <gtkmm/box.h> + +#include "template-load-tab.h" + + +namespace Inkscape { +namespace UI { + + +class TemplateWidget : public Gtk::VBox +{ +public: + TemplateWidget (); + void create(); + void display(TemplateLoadTab::TemplateData); + +private: + TemplateLoadTab::TemplateData _current_template; + + Gtk::Button _more_info_button; + Gtk::HBox _preview_box; + Gtk::Image _preview_image; + Dialog::SVGPreview _preview_render; + Gtk::Label _short_description_label; + Gtk::Label _template_name_label; + Gtk::Widget *_effect_prefs; + + void _displayTemplateDetails(); +}; + +} +} + +#endif diff --git a/src/ui/dialog/text-edit.cpp b/src/ui/dialog/text-edit.cpp index 791b49af9..17c29c69f 100644 --- a/src/ui/dialog/text-edit.cpp +++ b/src/ui/dialog/text-edit.cpp @@ -8,8 +8,9 @@ * Johan Engelen <goejendaagh@zonnet.nl> * Abhishek Sharma * John Smith + * Tavmjong Bah * - * Copyright (C) 1999-2012 Authors + * Copyright (C) 1999-2013 Authors * Copyright (C) 2000-2001 Ximian, Inc. * * Released under GNU GPL, read the file 'COPYING' for more information @@ -32,6 +33,7 @@ extern "C" { #include <gtkmm/stock.h> #include <libnrtype/font-instance.h> #include <libnrtype/font-style-to-pos.h> +#include <libnrtype/font-lister.h> #include <xml/repr.h> #include "macros.h" @@ -55,7 +57,9 @@ extern "C" { #include "widgets/icon.h" #include "widgets/font-selector.h" #include <glibmm/i18n.h> - +#include <glibmm/markup.h> +#include "util/units.h" +#include "sp-textpath.h" namespace Inkscape { namespace UI { @@ -90,45 +94,37 @@ TextEdit::TextEdit() fontsel_hbox.pack_start(*Gtk::manage(Glib::wrap(fontsel)), true, true); /* Align buttons */ - styleButton(&align_left, _("Align left"), GTK_STOCK_JUSTIFY_LEFT, NULL); - styleButton(&align_center, _("Align center"), GTK_STOCK_JUSTIFY_CENTER, &align_left); - styleButton(&align_right, _("Align right"), GTK_STOCK_JUSTIFY_RIGHT, &align_left); - styleButton(&align_justify, _("Justify (only flowed text)"), GTK_STOCK_JUSTIFY_FILL, &align_left); + styleButton(&align_left, _("Align left"), INKSCAPE_ICON("format-justify-left"), NULL); + styleButton(&align_center, _("Align center"), INKSCAPE_ICON("format-justify-center"), &align_left); + styleButton(&align_right, _("Align right"), INKSCAPE_ICON("format-justify-right"), &align_left); + styleButton(&align_justify, _("Justify (only flowed text)"), INKSCAPE_ICON("format-justify-fill"), &align_left); + +#if WITH_GTKMM_3_0 + align_sep.set_orientation(Gtk::ORIENTATION_VERTICAL); +#endif + layout_hbox.pack_start(align_sep, false, false, 10); /* Direction buttons */ styleButton(&text_horizontal, _("Horizontal text"), INKSCAPE_ICON("format-text-direction-horizontal"), NULL); styleButton(&text_vertical, _("Vertical text"), INKSCAPE_ICON("format-text-direction-vertical"), &text_horizontal); + +#if WITH_GTKMM_3_0 + text_sep.set_orientation(Gtk::ORIENTATION_VERTICAL); +#endif + layout_hbox.pack_start(text_sep, false, false, 10); /* Line Spacing */ GtkWidget *px = sp_icon_new( Inkscape::ICON_SIZE_SMALL_TOOLBAR, INKSCAPE_ICON("text_line_spacing") ); layout_hbox.pack_start(*Gtk::manage(Glib::wrap(px)), false, false); -/* -This would introduce dependency on gtk version 2.24 which is currently not available in -Trisquel GNU/Linux 4.5.1 (released on May 25th, 2011) -This conditional and its #else block can be deleted in the future. -*/ -#if GTK_CHECK_VERSION(2, 24,0) spacing_combo = gtk_combo_box_text_new_with_entry (); -#else - spacing_combo = gtk_combo_box_entry_new_text (); -#endif gtk_widget_set_size_request (spacing_combo, 90, -1); const gchar *spacings[] = {"50%", "80%", "90%", "100%", "110%", "120%", "130%", "140%", "150%", "200%", "300%", NULL}; for (int i = 0; spacings[i]; i++) { -/* -This would introduce dependency on gtk version 2.24 which is currently not available in -Trisquel GNU/Linux 4.5.1 (released on May 25th, 2011) -This conditional and its #else block can be deleted in the future. -*/ -#if GTK_CHECK_VERSION(2, 24,0) gtk_combo_box_text_append_text((GtkComboBoxText *) spacing_combo, spacings[i]); -#else - gtk_combo_box_append_text((GtkComboBox *) spacing_combo, spacings[i]); -#endif } gtk_widget_set_tooltip_text (px, _("Spacing between lines (percent of font size)")); @@ -137,6 +133,30 @@ This conditional and its #else block can be deleted in the future. layout_frame.set_padding(4,4,4,4); layout_frame.add(layout_hbox); + // Text start Offset + { + startOffset = gtk_combo_box_text_new_with_entry (); + gtk_widget_set_size_request(startOffset, 90, -1); + + const gchar *spacings[] = {"0%", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%", NULL}; + for (int i = 0; spacings[i]; i++) { + gtk_combo_box_text_append_text(reinterpret_cast<GtkComboBoxText *>(startOffset), spacings[i]); + } + gtk_entry_set_text(reinterpret_cast<GtkEntry *>(gtk_bin_get_child(reinterpret_cast<GtkBin *>(startOffset))), "0%"); + + gtk_widget_set_tooltip_text(startOffset, _("Text path offset")); + +#if WITH_GTKMM_3_0 + Gtk::Separator *sep = Gtk::manage(new Gtk::Separator()); + sep->set_orientation(Gtk::ORIENTATION_VERTICAL); +#else + Gtk::VSeparator *sep = Gtk::manage(new Gtk::VSeparator); +#endif + layout_hbox.pack_start(*sep, false, false, 10); + + layout_hbox.pack_start(*Gtk::manage(Glib::wrap(startOffset)), false, false); + } + /* Font preview */ preview_label.set_ellipsize(Pango::ELLIPSIZE_END); preview_label.set_justify(Gtk::JUSTIFY_CENTER); @@ -193,6 +213,7 @@ This conditional and its #else block can be deleted in the future. g_signal_connect ( G_OBJECT (fontsel), "font_set", G_CALLBACK (onFontChange), this ); g_signal_connect ( G_OBJECT (spacing_combo), "changed", G_CALLBACK (onLineSpacingChange), this ); g_signal_connect ( G_OBJECT (text_buffer), "changed", G_CALLBACK (onTextChange), this ); + g_signal_connect(startOffset, "changed", G_CALLBACK(onStartOffsetChange), this); setasdefault_button.signal_clicked().connect(sigc::mem_fun(*this, &TextEdit::onSetDefault)); apply_button.signal_clicked().connect(sigc::mem_fun(*this, &TextEdit::onApply)); close_button.signal_clicked().connect(sigc::bind(_signal_response.make_slot(), GTK_RESPONSE_CLOSE)); @@ -216,7 +237,7 @@ void TextEdit::styleButton(Gtk::RadioButton *button, gchar const *tooltip, gchar { GtkWidget *icon = sp_icon_new( Inkscape::ICON_SIZE_SMALL_TOOLBAR, icon_name ); if (!GTK_IS_IMAGE(icon)) { - icon = gtk_image_new_from_stock ( icon_name, GTK_ICON_SIZE_SMALL_TOOLBAR ); + icon = gtk_image_new_from_icon_name ( icon_name, GTK_ICON_SIZE_SMALL_TOOLBAR ); } if (group_button) { @@ -267,8 +288,16 @@ void TextEdit::onReadSelection ( gboolean dostyle, gboolean /*docontent*/ ) guint items = getSelectedTextCount (); if (items == 1) { gtk_widget_set_sensitive (text_view, TRUE); + gtk_widget_set_sensitive( startOffset, SP_IS_TEXT_TEXTPATH(text) ); + if (SP_IS_TEXT_TEXTPATH(text)) { + SPTextPath *tp = SP_TEXTPATH(text->firstChild()); + if (tp->getAttribute("startOffset")) { + gtk_entry_set_text(reinterpret_cast<GtkEntry *>(gtk_bin_get_child(reinterpret_cast<GtkBin *>(startOffset))), tp->getAttribute("startOffset")); + } + } } else { gtk_widget_set_sensitive (text_view, FALSE); + gtk_widget_set_sensitive( startOffset, FALSE ); } apply_button.set_sensitive ( false ); setasdefault_button.set_sensitive ( true ); @@ -290,6 +319,7 @@ void TextEdit::onReadSelection ( gboolean dostyle, gboolean /*docontent*/ ) text->getRepr(); // was being called but result ignored. Check this. } else { gtk_widget_set_sensitive (text_view, FALSE); + gtk_widget_set_sensitive( startOffset, FALSE ); apply_button.set_sensitive ( false ); setasdefault_button.set_sensitive ( false ); } @@ -312,15 +342,20 @@ void TextEdit::onReadSelection ( gboolean dostyle, gboolean /*docontent*/ ) // FIXME: process result_family/style == QUERY_STYLE_MULTIPLE_DIFFERENT by showing "Many" in the lists - // Get a font_instance using the font-specification attribute stored in SPStyle if available - font_instance *font = font_factory::Default()->FaceFromStyle(query); + Inkscape::FontLister* fontlister = Inkscape::FontLister::get_instance(); - if (font) { - sp_font_selector_set_font (fsel, font, query->font_size.computed); - setPreviewText(font, phrase); - font->Unref(); - font=NULL; - } + // This is done for us by text-toolbar. No need to do it twice. + // fontlister->update_font_list( sp_desktop_document( SP_ACTIVE_DESKTOP )); + // fontlister->selection_update(); + + Glib::ustring fontspec = fontlister->get_fontspec(); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int unit = prefs->getInt("/options/font/unitType", SP_CSS_UNIT_PT); + double size = sp_style_css_size_px_to_units(query->font_size.computed, unit); + sp_font_selector_set_fontspec(fsel, fontspec, size ); + + setPreviewText (fontspec, phrase); if (query->text_anchor.computed == SP_CSS_TEXT_ANCHOR_START) { if (query->text_align.computed == SP_CSS_TEXT_ALIGN_JUSTIFY) { @@ -355,28 +390,31 @@ void TextEdit::onReadSelection ( gboolean dostyle, gboolean /*docontent*/ ) blocked = false; } -void TextEdit::setPreviewText (font_instance *font, Glib::ustring phrase) + +void TextEdit::setPreviewText (Glib::ustring font_spec, Glib::ustring phrase) { - if (!font) { + if (font_spec.empty()) { return; } - char *desc = pango_font_description_to_string(font->descr); - double size = sp_font_selector_get_size(fsel); + Glib::ustring phrase_escaped = Glib::Markup::escape_text( phrase ); - gchar *const phrase_escaped = g_markup_escape_text(phrase.c_str(), -1); - - gchar *markup = g_strdup_printf("<span font=\"%s\" size=\"%d\">%s</span>", - desc, (int) (size * PANGO_SCALE), phrase_escaped); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int unit = prefs->getInt("/options/font/unitType", SP_CSS_UNIT_PT); + double pt_size = Inkscape::Util::Quantity::convert(sp_style_css_size_units_to_px(sp_font_selector_get_size(fsel), unit), "px", "pt"); + // Pango font size is in 1024ths of a point + // C++11: Glib::ustring size = std::to_string( pt_size * PANGO_SCALE ); + std::ostringstream size_st; + size_st << pt_size * PANGO_SCALE; - preview_label.set_markup(markup); + Glib::ustring markup = "<span font=\"" + font_spec + + "\" size=\"" + size_st.str() + "\">" + phrase_escaped + "</span>"; - g_free(desc); - g_free(phrase_escaped); - g_free(markup); + preview_label.set_markup(markup.c_str()); } + SPItem *TextEdit::getSelectedTextItem (void) { if (!SP_ACTIVE_DESKTOP) @@ -420,52 +458,38 @@ void TextEdit::onSelectionChange() void TextEdit::updateObjectText ( SPItem *text ) { GtkTextIter start, end; - gchar *str; // write text if (gtk_text_buffer_get_modified (text_buffer)) { gtk_text_buffer_get_bounds (text_buffer, &start, &end); - str = gtk_text_buffer_get_text (text_buffer, &start, &end, TRUE); + gchar *str = gtk_text_buffer_get_text (text_buffer, &start, &end, TRUE); sp_te_set_repr_text_multiline (text, str); g_free (str); gtk_text_buffer_set_modified (text_buffer, FALSE); } } -SPCSSAttr *TextEdit::getTextStyle () +SPCSSAttr *TextEdit::fillTextStyle () { SPCSSAttr *css = sp_repr_css_attr_new (); - // font - font_instance *font = sp_font_selector_get_font (fsel); - - if ( font ) { - Glib::ustring fontName = font_factory::Default()->ConstructFontSpecification(font); - sp_repr_css_set_property (css, "-inkscape-font-specification", fontName.c_str()); + Glib::ustring fontspec = sp_font_selector_get_fontspec (fsel); - gchar c[256]; + if( !fontspec.empty() ) { - font->Family(c, 256); - sp_repr_css_set_property (css, "font-family", c); - - font->Attribute( "weight", c, 256); - sp_repr_css_set_property (css, "font-weight", c); - - font->Attribute("style", c, 256); - sp_repr_css_set_property (css, "font-style", c); - - font->Attribute("stretch", c, 256); - sp_repr_css_set_property (css, "font-stretch", c); - - font->Attribute("variant", c, 256); - sp_repr_css_set_property (css, "font-variant", c); + Inkscape::FontLister *fontlister = Inkscape::FontLister::get_instance(); + fontlister->fill_css( css, fontspec ); + // TODO, possibly move this to FontLister::set_css to be shared. Inkscape::CSSOStringStream os; - os << sp_font_selector_get_size (fsel) << "px"; // must specify px, see inkscape bug 1221626 and 1610103 + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int unit = prefs->getInt("/options/font/unitType", SP_CSS_UNIT_PT); + if (prefs->getBool("/options/font/textOutputPx", true)) { + os << sp_style_css_size_units_to_px(sp_font_selector_get_size (fsel), unit) << sp_style_get_css_unit_string(SP_CSS_UNIT_PX); + } else { + os << sp_font_selector_get_size (fsel) << sp_style_get_css_unit_string(unit); + } sp_repr_css_set_property (css, "font-size", os.str().c_str()); - - font->Unref(); - font=NULL; } // Layout @@ -493,16 +517,7 @@ SPCSSAttr *TextEdit::getTextStyle () // Note that CSS 1.1 does not support line-height; we set it for consistency, but also set // sodipodi:linespacing for backwards compatibility; in 1.2 we use line-height for flowtext -/* -This would introduce dependency on gtk version 2.24 which is currently not available in -Trisquel GNU/Linux 4.5.1 (released on May 25th, 2011) -This conditional and its #else block can be deleted in the future. -*/ -#if GTK_CHECK_VERSION(2, 24,0) const gchar *sstr = gtk_combo_box_text_get_active_text ((GtkComboBoxText *) spacing_combo); -#else - const gchar *sstr = gtk_entry_get_text ((GtkEntry *) (gtk_bin_get_child (GTK_BIN (spacing_combo)))); -#endif sp_repr_css_set_property (css, "line-height", sstr); return css; @@ -510,7 +525,7 @@ This conditional and its #else block can be deleted in the future. void TextEdit::onSetDefault() { - SPCSSAttr *css = getTextStyle (); + SPCSSAttr *css = fillTextStyle (); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); blocked = true; @@ -530,7 +545,7 @@ void TextEdit::onApply() unsigned items = 0; const GSList *item_list = sp_desktop_selection(desktop)->itemList(); - SPCSSAttr *css = getTextStyle (); + SPCSSAttr *css = fillTextStyle (); sp_desktop_set_style(desktop, css, true); for (; item_list != NULL; item_list = item_list->next) { @@ -561,6 +576,13 @@ void TextEdit::onApply() } } + // Update FontLister + Glib::ustring fontspec = sp_font_selector_get_fontspec (fsel); + if( !fontspec.empty() ) { + Inkscape::FontLister *fontlister = Inkscape::FontLister::get_instance(); + fontlister->set_fontspec( fontspec, false ); + } + // complete the transaction DocumentUndo::done(sp_desktop_document(SP_ACTIVE_DESKTOP), SP_VERB_CONTEXT_TEXT, _("Set text style")); @@ -582,11 +604,11 @@ void TextEdit::onTextChange (GtkTextBuffer *text_buffer, TextEdit *self) GtkTextIter end; gtk_text_buffer_get_bounds (text_buffer, &start, &end); gchar *str = gtk_text_buffer_get_text(text_buffer, &start, &end, TRUE); - font_instance *font = sp_font_selector_get_font(self->fsel); + Glib::ustring fontspec = sp_font_selector_get_fontspec(self->fsel); - if (font) { + if( !fontspec.empty() ) { const gchar *phrase = str && *str ? str : self->samplephrase.c_str(); - self->setPreviewText(font, phrase); + self->setPreviewText(fontspec, phrase); } else { self->preview_label.set_markup(""); } @@ -599,7 +621,7 @@ void TextEdit::onTextChange (GtkTextBuffer *text_buffer, TextEdit *self) self->setasdefault_button.set_sensitive ( true); } -void TextEdit::onFontChange(SPFontSelector * /*fontsel*/, font_instance * font, TextEdit *self) +void TextEdit::onFontChange(SPFontSelector * /*fontsel*/, gchar* fontspec, TextEdit *self) { GtkTextIter start, end; gchar *str; @@ -612,9 +634,9 @@ void TextEdit::onFontChange(SPFontSelector * /*fontsel*/, font_instance * font, gtk_text_buffer_get_bounds (self->text_buffer, &start, &end); str = gtk_text_buffer_get_text (self->text_buffer, &start, &end, TRUE); - if (font) { + if (fontspec) { const gchar *phrase = str && *str ? str : self->samplephrase.c_str(); - self->setPreviewText(font, phrase); + self->setPreviewText(fontspec, phrase); } else { self->preview_label.set_markup(""); } @@ -628,6 +650,19 @@ void TextEdit::onFontChange(SPFontSelector * /*fontsel*/, font_instance * font, } +void TextEdit::onStartOffsetChange(GtkTextBuffer * /*text_buffer*/, TextEdit *self) +{ + SPItem *text = self->getSelectedTextItem(); + if (text && SP_IS_TEXT_TEXTPATH(text)) + { + SPTextPath *tp = SP_TEXTPATH(text->firstChild()); + const gchar *sstr = gtk_combo_box_text_get_active_text(reinterpret_cast<GtkComboBoxText *>(self->startOffset)); + tp->setAttribute("startOffset", sstr); + + DocumentUndo::maybeDone(sp_desktop_document(SP_ACTIVE_DESKTOP), "startOffset", SP_VERB_CONTEXT_TEXT, _("Set text style")); + } +} + void TextEdit::onToggle() { if (blocked) @@ -640,7 +675,6 @@ void TextEdit::onToggle() //onApply(); } setasdefault_button.set_sensitive ( true ); - } diff --git a/src/ui/dialog/text-edit.h b/src/ui/dialog/text-edit.h index 9fd9baa30..8683d80a3 100644 --- a/src/ui/dialog/text-edit.h +++ b/src/ui/dialog/text-edit.h @@ -7,8 +7,9 @@ * Johan Engelen <goejendaagh@zonnet.nl> * John Smith * Kris De Gussem <Kris.DeGussem@gmail.com> + * Tavmjong Bah * - * Copyright (C) 1999-2012 Authors + * Copyright (C) 1999-2013 Authors * Copyright (C) 2000-2001 Ximian, Inc. * * Released under GNU GPL, read the file 'COPYING' for more information @@ -17,6 +18,14 @@ #ifndef INKSCAPE_UI_DIALOG_TEXT_EDIT_H #define INKSCAPE_UI_DIALOG_TEXT_EDIT_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> #include <gtkmm/notebook.h> #include <gtkmm/button.h> @@ -29,7 +38,7 @@ #include "ui/dialog/desktop-tracker.h" class SPItem; -class SPFontSelector; +struct SPFontSelector; class font_instance; class SPCSSAttr; @@ -100,10 +109,18 @@ protected: * onFontChange updates the dialog UI. The subfunction setPreviewText updates the preview label. * * @param fontsel pointer to SPFontSelector (currently not used). - * @param font pointer to the font instance for the text to be previewed + * @param fontspec for the text to be previewed. + * @param self pointer to the current instance of the dialog. + */ + static void onFontChange (SPFontSelector *fontsel, gchar* fontspec, TextEdit *self); + + /** + * Callback invoked when the user modifies the startOffset of text on a path. + * + * @param text_buffer pointer to the GtkTextBuffer with the text of the selected text object. * @param self pointer to the current instance of the dialog. */ - static void onFontChange (SPFontSelector *fontsel, font_instance *font, TextEdit *self); + static void onStartOffsetChange(GtkTextBuffer *text_buffer, TextEdit *self); /** * Get the selected text off the main canvas. @@ -118,15 +135,15 @@ protected: unsigned getSelectedTextCount (void); /** - * Helper function to create markup from a font definition and display in the preview label. + * Helper function to create markup from a fontspec and display in the preview label. * - * @param font pointer to the font instance for the text to be previewed + * @param fontspec for the text to be previewed * @param phrase text to be shown */ - void setPreviewText (font_instance *font, Glib::ustring phrase); + void setPreviewText (Glib::ustring font_spec, Glib::ustring phrase); void updateObjectText ( SPItem *text ); - SPCSSAttr *getTextStyle (); + SPCSSAttr *fillTextStyle (); /** * Helper function to style radio buttons with icons, tooltips. @@ -172,12 +189,26 @@ private: Gtk::RadioButton align_center; Gtk::RadioButton align_right; Gtk::RadioButton align_justify; + +#if WITH_GTKMM_3_0 + Gtk::Separator align_sep; +#else Gtk::VSeparator align_sep; +#endif + Gtk::RadioButton text_vertical; Gtk::RadioButton text_horizontal; + +#if WITH_GTKMM_3_0 + Gtk::Separator text_sep; +#else Gtk::VSeparator text_sep; +#endif + GtkWidget *spacing_combo; + GtkWidget *startOffset; + Gtk::Label preview_label; Gtk::Label text_label; diff --git a/src/ui/dialog/tile.h b/src/ui/dialog/tile.h index 8d4e9584b..2f75a8922 100644 --- a/src/ui/dialog/tile.h +++ b/src/ui/dialog/tile.h @@ -16,6 +16,14 @@ #ifndef SEEN_UI_DIALOG_TILE_H #define SEEN_UI_DIALOG_TILE_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> #include <gtkmm/notebook.h> #include <gtkmm/checkbutton.h> @@ -25,6 +33,12 @@ namespace Gtk { class Button; + +#if WITH_GTKMM_3_0 +class Grid; +#else +class Table; +#endif } namespace Inkscape { diff --git a/src/ui/dialog/tracedialog.cpp b/src/ui/dialog/tracedialog.cpp index a6495c205..bd467555e 100644 --- a/src/ui/dialog/tracedialog.cpp +++ b/src/ui/dialog/tracedialog.cpp @@ -20,12 +20,15 @@ #include <gtkmm/frame.h> #include "ui/widget/spinbutton.h" #include "ui/widget/frame.h" +#include <gtkmm/radiobutton.h> #include <gtkmm/stock.h> #include <gtk/gtk.h> //for GTK_RESPONSE* types #include <glibmm/i18n.h> #include "desktop.h" +#include "desktop-tracker.h" +#include "selection.h" #include "trace/potrace/inkscape-potrace.h" #include "inkscape.h" @@ -83,6 +86,13 @@ class TraceDialogImpl : public TraceDialog void abort(); void previewCallback(); + void previewLiveCallback(); + void onSettingsChange(); + void onSelectionModified( guint flags ); + void onSetDefaults(); + + void setDesktop(SPDesktop *desktop); + void setTargetDesktop(SPDesktop *desktop); //############ General items @@ -90,6 +100,7 @@ class TraceDialogImpl : public TraceDialog Gtk::Button *mainOkButton; Gtk::Button *mainCancelButton; + Gtk::Button *mainResetButton; //######## Left pannel @@ -194,11 +205,40 @@ class TraceDialogImpl : public TraceDialog UI::Widget::Frame previewFrame; Gtk::VBox previewVBox; Gtk::Button previewButton; + Gtk::CheckButton previewLiveButton; + gboolean previewLive; Gtk::Image previewImage; + SPDesktop *desktop; + DesktopTracker deskTrack; + sigc::connection desktopChangeConn; + sigc::connection selectChangedConn; + sigc::connection selectModifiedConn; + }; +void TraceDialogImpl::setDesktop(SPDesktop *desktop) +{ + Panel::setDesktop(desktop); + deskTrack.setBase(desktop); +} +void TraceDialogImpl::setTargetDesktop(SPDesktop *desktop) +{ + if (this->desktop != desktop) { + if (this->desktop) { + selectChangedConn.disconnect(); + selectModifiedConn.disconnect(); + } + this->desktop = desktop; + if (desktop && desktop->selection) { + selectChangedConn = desktop->selection->connectChanged(sigc::hide(sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange))); + selectModifiedConn = desktop->selection->connectModified(sigc::hide<0>(sigc::mem_fun(*this, &TraceDialogImpl::onSelectionModified))); + + } + onSettingsChange(); + } +} //######################################################################### //## E V E N T S @@ -294,8 +334,9 @@ void TraceDialogImpl::potraceProcess(bool do_i_trace) { int width = preview->get_width(); int height = preview->get_height(); - double scaleFX = 200.0 / (double)width; - double scaleFY = 200.0 / (double)height; + const Gtk::Allocation& vboxAlloc = previewImage.get_allocation(); + double scaleFX = vboxAlloc.get_width() / (double)width; + double scaleFY = vboxAlloc.get_height() / (double)height; double scaleFactor = scaleFX > scaleFY ? scaleFY : scaleFX; int newWidth = (int) (((double)width) * scaleFactor); int newHeight = (int) (((double)height) * scaleFactor); @@ -351,6 +392,58 @@ void TraceDialogImpl::abort() //######################################################################### /** + * Callback for when any setting changes + */ +void TraceDialogImpl::onSettingsChange() +{ + if (previewLive) { + previewCallback(); + } +} + +void TraceDialogImpl::onSelectionModified( guint flags ) +{ + if (flags & ( SP_OBJECT_MODIFIED_FLAG | + SP_OBJECT_PARENT_MODIFIED_FLAG | + SP_OBJECT_STYLE_MODIFIED_FLAG) ) { + onSettingsChange(); + } +} + +/** + * Callback for when users resets defaults + */ +void TraceDialogImpl::onSetDefaults() +{ + + // temporarily disable live update + gboolean wasLive = previewLive; + previewLive = false; + + modeBrightnessRadioButton.set_active(true); + modeBrightnessSpinner.set_value(0.45); + modeCannyHiSpinner.set_value(0.65); + modeMultiScanNrColorSpinner.set_value(8.0); + modeMultiScanNrColorSpinner.set_value(8.0); + optionsSpecklesSizeSpinner.set_value(2); + optionsCornersThresholdSpinner.set_value(1.0); + optionsOptimToleranceSpinner.set_value(0.2); + + modeInvertButton.set_active(false); + modeMultiScanSmoothButton.set_active(true); + modeMultiScanStackButton.set_active(true); + modeMultiScanBackgroundButton.set_active(false); + optionsSpecklesButton.set_active(true); + optionsCornersButton.set_active(true); + optionsOptimButton.set_active(true); + sioxButton.set_active(false); + + previewLive = wasLive; + onSettingsChange(); + +} + +/** * Callback from the Preview button. Can be called from elsewhere. */ void TraceDialogImpl::previewCallback() @@ -359,24 +452,31 @@ void TraceDialogImpl::previewCallback() } /** + * Callback from the Preview Live button. + */ +void TraceDialogImpl::previewLiveCallback() +{ + previewLive = previewLiveButton.get_active(); + previewButton.set_sensitive(!previewLive); + onSettingsChange(); +} + +/** * Default response from the dialog. Let's intercept it */ void TraceDialogImpl::responseCallback(int response_id) { - if (response_id == GTK_RESPONSE_OK) - { - // for now, we assume potrace, as it's the only one we have - potraceProcess(true); - } - else if (response_id == GTK_RESPONSE_CANCEL) - { + if (response_id == GTK_RESPONSE_OK) { + // for now, we assume potrace, as it's the only one we have + potraceProcess(true); + } else if (response_id == GTK_RESPONSE_CANCEL) { abort(); - } - else - { + } else if (response_id == GTK_RESPONSE_HELP) { + onSetDefaults(); + } else { hide(); return; - } + } } @@ -417,6 +517,7 @@ TraceDialogImpl::TraceDialogImpl() : modeBrightnessSpinner.set_value(0.45); modeBrightnessBox.pack_end(modeBrightnessSpinner, false, false, MARGIN); modeBrightnessSpinner.set_tooltip_text(_("Brightness cutoff for black/white")); + modeBrightnessSpinner.get_adjustment()->signal_value_changed().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); modeBrightnessSpinnerLabel.set_label(_("_Threshold:")); modeBrightnessSpinnerLabel.set_use_underline(true); @@ -435,6 +536,8 @@ TraceDialogImpl::TraceDialogImpl() : modeCannyRadioButton.set_use_underline(true); modeCannyBox.pack_start(modeCannyRadioButton, false, false, MARGIN); modeCannyRadioButton.set_tooltip_text(_("Trace with optimal edge detection by J. Canny's algorithm")); + modeCannyRadioButton.signal_clicked().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); + /* modeCannyBox.pack_start(modeCannySeparator); modeCannyLoSpinnerLabel.set_label(_("Low")); @@ -451,6 +554,7 @@ TraceDialogImpl::TraceDialogImpl() : modeCannyHiSpinner.set_value(0.65); modeCannyBox.pack_end(modeCannyHiSpinner, false, false, MARGIN); modeCannyHiSpinner.set_tooltip_text(_("Brightness cutoff for adjacent pixels (determines edge thickness)")); + modeCannyHiSpinner.get_adjustment()->signal_value_changed().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); modeCannyHiSpinnerLabel.set_label(_("T_hreshold:")); modeCannyHiSpinnerLabel.set_use_underline(true); @@ -469,6 +573,7 @@ TraceDialogImpl::TraceDialogImpl() : modeQuantRadioButton.set_use_underline(true); modeQuantBox.pack_start(modeQuantRadioButton, false, false, MARGIN); modeQuantRadioButton.set_tooltip_text(_("Trace along the boundaries of reduced colors")); + modeQuantRadioButton.signal_clicked().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); modeQuantNrColorSpinner.set_digits(0); modeQuantNrColorSpinner.set_increments(1.0, 0); @@ -476,6 +581,7 @@ TraceDialogImpl::TraceDialogImpl() : modeQuantNrColorSpinner.set_value(8.0); modeQuantBox.pack_end(modeQuantNrColorSpinner, false, false, MARGIN); modeQuantNrColorSpinner.set_tooltip_text(_("The number of reduced colors")); + modeQuantNrColorSpinner.get_adjustment()->signal_value_changed().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); modeQuantNrColorLabel.set_label(_("_Colors:")); modeQuantNrColorLabel.set_mnemonic_widget(modeQuantNrColorSpinner); @@ -491,6 +597,7 @@ TraceDialogImpl::TraceDialogImpl() : modeInvertBox.pack_start(modeInvertButton, false, false, MARGIN); modeBrightnessVBox.pack_start(modeInvertBox, false, false, MARGIN); modeInvertButton.set_tooltip_text(_("Invert black and white regions")); + modeInvertButton.signal_clicked().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); modeBrightnessFrame.add(modeBrightnessVBox); modePageBox.pack_start(modeBrightnessFrame, false, false, 0); @@ -504,6 +611,7 @@ TraceDialogImpl::TraceDialogImpl() : modeMultiScanBrightnessRadioButton.set_use_underline(true); modeMultiScanHBox1.pack_start(modeMultiScanBrightnessRadioButton, false, false, MARGIN); modeMultiScanBrightnessRadioButton.set_tooltip_text(_("Trace the given number of brightness levels")); + modeMultiScanBrightnessRadioButton.signal_clicked().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); modeMultiScanNrColorSpinner.set_digits(0); modeMultiScanNrColorSpinner.set_increments(1.0, 0); @@ -515,6 +623,7 @@ TraceDialogImpl::TraceDialogImpl() : modeMultiScanNrColorLabel.set_mnemonic_widget(modeMultiScanNrColorSpinner); modeMultiScanHBox1.pack_end(modeMultiScanNrColorLabel, false, false, MARGIN); modeMultiScanNrColorSpinner.set_tooltip_text(_("The desired number of scans")); + modeMultiScanNrColorSpinner.get_adjustment()->signal_value_changed().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); modeMultiScanVBox.pack_start(modeMultiScanHBox1, false, false, MARGIN); @@ -523,6 +632,7 @@ TraceDialogImpl::TraceDialogImpl() : modeMultiScanColorRadioButton.set_use_underline(true); modeMultiScanHBox2.pack_start(modeMultiScanColorRadioButton, false, false, MARGIN); modeMultiScanColorRadioButton.set_tooltip_text(_("Trace the given number of reduced colors")); + modeMultiScanColorRadioButton.signal_clicked().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); modeMultiScanVBox.pack_start(modeMultiScanHBox2, false, false, MARGIN); @@ -531,6 +641,7 @@ TraceDialogImpl::TraceDialogImpl() : modeMultiScanMonoRadioButton.set_use_underline(true); modeMultiScanHBox3.pack_start(modeMultiScanMonoRadioButton, false, false, MARGIN); modeMultiScanMonoRadioButton.set_tooltip_text(_("Same as Colors, but the result is converted to grayscale")); + modeMultiScanMonoRadioButton.signal_clicked().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); modeMultiScanVBox.pack_start(modeMultiScanHBox3, false, false, MARGIN); @@ -540,6 +651,7 @@ TraceDialogImpl::TraceDialogImpl() : modeMultiScanSmoothButton.set_active(true); modeMultiScanHBox4.pack_start(modeMultiScanSmoothButton, false, false, MARGIN); modeMultiScanSmoothButton.set_tooltip_text(_("Apply Gaussian blur to the bitmap before tracing")); + modeMultiScanSmoothButton.signal_clicked().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); // TRANSLATORS: "Stack" is a verb here modeMultiScanStackButton.set_label(_("Stac_k scans")); @@ -547,6 +659,7 @@ TraceDialogImpl::TraceDialogImpl() : modeMultiScanStackButton.set_active(true); modeMultiScanHBox4.pack_start(modeMultiScanStackButton, false, false, MARGIN); modeMultiScanStackButton.set_tooltip_text(_("Stack scans on top of one another (no gaps) instead of tiling (usually with gaps)")); + modeMultiScanStackButton.signal_clicked().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); modeMultiScanBackgroundButton.set_label(_("Remo_ve background")); @@ -555,6 +668,7 @@ TraceDialogImpl::TraceDialogImpl() : modeMultiScanHBox4.pack_start(modeMultiScanBackgroundButton, false, false, MARGIN); // TRANSLATORS: "Layer" refers to one of the stacked paths in the multiscan modeMultiScanBackgroundButton.set_tooltip_text(_("Remove bottom (background) layer when done")); + modeMultiScanBackgroundButton.signal_clicked().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); modeMultiScanVBox.pack_start(modeMultiScanHBox4, false, false, MARGIN); @@ -577,12 +691,14 @@ TraceDialogImpl::TraceDialogImpl() : optionsSpecklesButton.set_use_underline(true); optionsSpecklesButton.set_tooltip_text(_("Ignore small spots (speckles) in the bitmap")); optionsSpecklesButton.set_active(true); + optionsSpecklesButton.signal_clicked().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); optionsSpecklesBox.pack_start(optionsSpecklesButton, false, false, MARGIN); optionsSpecklesSizeSpinner.set_digits(0); optionsSpecklesSizeSpinner.set_increments(1, 0); optionsSpecklesSizeSpinner.set_range(0, 1000); optionsSpecklesSizeSpinner.set_value(2); optionsSpecklesSizeSpinner.set_tooltip_text(_("Speckles of up to this many pixels will be suppressed")); + optionsSpecklesSizeSpinner.get_adjustment()->signal_value_changed().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); optionsSpecklesBox.pack_end(optionsSpecklesSizeSpinner, false, false, MARGIN); optionsSpecklesSizeLabel.set_label(_("S_ize:")); optionsSpecklesSizeLabel.set_use_underline(true); @@ -593,6 +709,7 @@ TraceDialogImpl::TraceDialogImpl() : optionsCornersButton.set_use_underline(true); optionsCornersButton.set_tooltip_text(_("Smooth out sharp corners of the trace")); optionsCornersButton.set_active(true); + optionsCornersButton.signal_clicked().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); optionsCornersBox.pack_start(optionsCornersButton, false, false, MARGIN); optionsCornersThresholdSpinner.set_digits(2); optionsCornersThresholdSpinner.set_increments(0.01, 0); @@ -600,6 +717,7 @@ TraceDialogImpl::TraceDialogImpl() : optionsCornersThresholdSpinner.set_value(1.0); optionsCornersBox.pack_end(optionsCornersThresholdSpinner, false, false, MARGIN); optionsCornersThresholdSpinner.set_tooltip_text(_("Increase this to smooth corners more")); + optionsCornersThresholdSpinner.get_adjustment()->signal_value_changed().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); optionsCornersThresholdLabel.set_label(_("_Threshold:")); optionsCornersThresholdLabel.set_use_underline(true); optionsCornersThresholdLabel.set_mnemonic_widget(optionsCornersThresholdSpinner); @@ -609,6 +727,7 @@ TraceDialogImpl::TraceDialogImpl() : optionsOptimButton.set_use_underline(true); optionsOptimButton.set_active(true); optionsOptimButton.set_tooltip_text(_("Try to optimize paths by joining adjacent Bezier curve segments")); + optionsOptimButton.signal_clicked().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); optionsOptimBox.pack_start(optionsOptimButton, false, false, MARGIN); optionsOptimToleranceSpinner.set_digits(2); optionsOptimToleranceSpinner.set_increments(0.05, 0); @@ -616,6 +735,7 @@ TraceDialogImpl::TraceDialogImpl() : optionsOptimToleranceSpinner.set_value(0.2); optionsOptimBox.pack_end(optionsOptimToleranceSpinner, false, false, MARGIN); optionsOptimToleranceSpinner.set_tooltip_text(_("Increase this to reduce the number of nodes in the trace by more aggressive optimization")); + optionsOptimToleranceSpinner.get_adjustment()->signal_value_changed().connect( sigc::mem_fun(*this, &TraceDialogImpl::onSettingsChange) ); optionsOptimToleranceLabel.set_label(_("To_lerance:")); optionsOptimToleranceLabel.set_use_underline(true); optionsOptimToleranceLabel.set_mnemonic_widget(optionsOptimToleranceSpinner); @@ -645,7 +765,7 @@ TraceDialogImpl::TraceDialogImpl() : //#### end left panel - mainHBox.pack_start(leftVBox); + mainHBox.pack_start(leftVBox, false, false, 0); //#### begin right panel @@ -658,12 +778,20 @@ TraceDialogImpl::TraceDialogImpl() : rightVBox.pack_start(sioxBox, false, false, 0); //## preview + Gtk::HBox *previewButtonHBox = manage(new Gtk::HBox(false, MARGIN )); + previewLiveButton.set_label(_("Live Preview")); + previewLiveButton.set_use_underline(true); + previewLiveCallback(); + previewLiveButton.signal_clicked().connect( + sigc::mem_fun(*this, &TraceDialogImpl::previewLiveCallback) ); previewButton.set_label(_("_Update")); previewButton.set_use_underline(true); previewButton.signal_clicked().connect( sigc::mem_fun(*this, &TraceDialogImpl::previewCallback) ); - previewVBox.pack_end(previewButton, false, false, 0); + previewButtonHBox->pack_start(previewLiveButton, false, false, 0); + previewButtonHBox->pack_end(previewButton, true, true, 0); + previewVBox.pack_end(*previewButtonHBox, false, false, 0); // I guess it's correct to call the "intermediate bitmap" a preview of the trace previewButton.set_tooltip_text(_("Preview the intermediate bitmap with the current settings, without actual tracing")); previewImage.set_size_request(200,200); @@ -677,11 +805,13 @@ TraceDialogImpl::TraceDialogImpl() : //#### end right panel - mainHBox.pack_start(rightVBox); + mainHBox.pack_start(rightVBox, true, true, 0); //#### Global stuff contents->pack_start(mainHBox); + mainResetButton = addResponseButton(_("Reset"), GTK_RESPONSE_HELP, true); + mainResetButton ->set_tooltip_text(_("Reset all settings to defaults")); //## The OK button mainCancelButton = addResponseButton(Gtk::Stock::STOP, GTK_RESPONSE_CANCEL); @@ -694,6 +824,9 @@ TraceDialogImpl::TraceDialogImpl() : show_all_children(); + desktopChangeConn = deskTrack.connectDesktopChanged( sigc::mem_fun(*this, &TraceDialogImpl::setTargetDesktop) ); + deskTrack.connect(GTK_WIDGET(gobj())); + //## Connect the signal signalResponse().connect( sigc::mem_fun(*this, &TraceDialogImpl::responseCallback)); @@ -714,6 +847,9 @@ TraceDialog &TraceDialog::getInstance() */ TraceDialogImpl::~TraceDialogImpl() { + selectChangedConn.disconnect(); + selectModifiedConn.disconnect(); + desktopChangeConn.disconnect(); } diff --git a/src/ui/dialog/transformation.cpp b/src/ui/dialog/transformation.cpp index 1951dc92a..a7f0b068e 100644 --- a/src/ui/dialog/transformation.cpp +++ b/src/ui/dialog/transformation.cpp @@ -15,6 +15,10 @@ # include <config.h> #endif +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/dialog.h> #include <gtkmm/stock.h> #include <2geom/transforms.h> @@ -27,6 +31,7 @@ #include "inkscape.h" #include "selection.h" #include "selection-chemistry.h" +#include "message-stack.h" #include "verbs.h" #include "preferences.h" #include "sp-namedview.h" @@ -34,21 +39,24 @@ #include "macros.h" #include "sp-item.h" #include "util/glib-list-iterators.h" +#include "ui/icon-names.h" +#include "widgets/icon.h" + namespace Inkscape { namespace UI { namespace Dialog { -void on_selection_changed(Inkscape::Application */*inkscape*/, Inkscape::Selection *selection, Transformation *daad) +static void on_selection_changed(Inkscape::Application */*inkscape*/, Inkscape::Selection *selection, Transformation *daad) { int page = daad->getCurrentPage(); daad->updateSelection((Inkscape::UI::Dialog::Transformation::PageType)page, selection); } -void on_selection_modified( Inkscape::Application */*inkscape*/, - Inkscape::Selection *selection, - guint /*flags*/, - Transformation *daad ) +static void on_selection_modified( Inkscape::Application */*inkscape*/, + Inkscape::Selection *selection, + guint /*flags*/, + Transformation *daad ) { int page = daad->getCurrentPage(); daad->updateSelection((Inkscape::UI::Dialog::Transformation::PageType)page, selection); @@ -87,6 +95,9 @@ Transformation::Transformation() _scalar_transform_e ("_E:", _("Transformation matrix element E")), _scalar_transform_f ("_F:", _("Transformation matrix element F")), + _counterclockwise_rotate (), + _clockwise_rotate (), + _check_move_relative (_("Rela_tive move"), _("Add the specified relative displacement to the current position; otherwise, edit the current absolute position directly")), _check_scale_proportional (_("_Scale proportionally"), _("Preserve the width/height ratio of the scaled objects")), _check_apply_separately (_("Apply to each _object separately"), _("Apply the scale/rotate/skew to each selected object separately; otherwise, transform the selection as a whole")), @@ -151,14 +162,25 @@ Transformation::Transformation() g_signal_connect (G_OBJECT (INKSCAPE), "change_selection", G_CALLBACK (on_selection_changed), this); g_signal_connect (G_OBJECT (INKSCAPE), "modify_selection", G_CALLBACK (on_selection_modified), this); + _desktopChangeConn = _deskTrack.connectDesktopChanged( sigc::mem_fun(*this, &Transformation::setDesktop) ); + _deskTrack.connect(GTK_WIDGET(gobj())); + show_all_children(); } Transformation::~Transformation() { sp_signal_disconnect_by_data (G_OBJECT (INKSCAPE), this); + _desktopChangeConn.disconnect(); + _deskTrack.disconnect(); } +void Transformation::setTargetDesktop(SPDesktop *desktop) +{ + if (_desktop != desktop) { + _desktop = desktop; + } +} /*######################################################################## # U T I L I T Y @@ -199,25 +221,40 @@ void Transformation::layoutPageMove() _scalar_move_vertical.setIncrements(0.1, 1.0); //_scalar_move_vertical.set_label_image( INKSCAPE_STOCK_ARROWS_HOR ); + +#if WITH_GTKMM_3_0 + _page_move.table().attach(_scalar_move_horizontal, 0, 0, 2, 1); + _page_move.table().attach(_units_move, 2, 0, 1, 1); +#else _page_move.table() .attach(_scalar_move_horizontal, 0, 2, 0, 1, Gtk::FILL, Gtk::SHRINK); _page_move.table() .attach(_units_move, 2, 3, 0, 1, Gtk::SHRINK, Gtk::SHRINK); +#endif _scalar_move_horizontal.signal_value_changed() .connect(sigc::mem_fun(*this, &Transformation::onMoveValueChanged)); //_scalar_move_vertical.set_label_image( INKSCAPE_STOCK_ARROWS_VER ); +#if WITH_GTKMM_3_0 + _page_move.table().attach(_scalar_move_vertical, 0, 1, 2, 1); +#else _page_move.table() .attach(_scalar_move_vertical, 0, 2, 1, 2, Gtk::FILL, Gtk::SHRINK); +#endif _scalar_move_vertical.signal_value_changed() .connect(sigc::mem_fun(*this, &Transformation::onMoveValueChanged)); // Relative moves +#if WITH_GTKMM_3_0 + _page_move.table().attach(_check_move_relative, 0, 2, 2, 1); +#else _page_move.table() .attach(_check_move_relative, 0, 2, 2, 3, Gtk::FILL, Gtk::SHRINK); +#endif + _check_move_relative.set_active(true); _check_move_relative.signal_toggled() .connect(sigc::mem_fun(*this, &Transformation::onMoveRelativeToggled)); @@ -242,21 +279,37 @@ void Transformation::layoutPageScale() _scalar_scale_vertical.setAbsoluteIsIncrement(true); _scalar_scale_vertical.setPercentageIsIncrement(true); +#if WITH_GTKMM_3_0 + _page_scale.table().attach(_scalar_scale_horizontal, 0, 0, 2, 1); +#else _page_scale.table() .attach(_scalar_scale_horizontal, 0, 2, 0, 1, Gtk::FILL, Gtk::SHRINK); +#endif + _scalar_scale_horizontal.signal_value_changed() .connect(sigc::mem_fun(*this, &Transformation::onScaleXValueChanged)); +#if WITH_GTKMM_3_0 + _page_scale.table().attach(_units_scale, 2, 0, 1, 1); + _page_scale.table().attach(_scalar_scale_vertical, 0, 1, 2, 1); +#else _page_scale.table() .attach(_units_scale, 2, 3, 0, 1, Gtk::SHRINK, Gtk::SHRINK); _page_scale.table() .attach(_scalar_scale_vertical, 0, 2, 1, 2, Gtk::FILL, Gtk::SHRINK); +#endif + _scalar_scale_vertical.signal_value_changed() .connect(sigc::mem_fun(*this, &Transformation::onScaleYValueChanged)); +#if WITH_GTKMM_3_0 + _page_scale.table().attach(_check_scale_proportional, 0, 2, 2, 1); +#else _page_scale.table() .attach(_check_scale_proportional, 0, 2, 2, 3, Gtk::FILL, Gtk::SHRINK); +#endif + _check_scale_proportional.set_active(false); _check_scale_proportional.signal_toggled() .connect(sigc::mem_fun(*this, &Transformation::onScaleProportionalToggled)); @@ -272,15 +325,55 @@ void Transformation::layoutPageRotate() _scalar_rotate.setDigits(3); _scalar_rotate.setIncrements(0.1, 1.0); + _counterclockwise_rotate.add(*manage( Glib::wrap( + sp_icon_new(Inkscape::ICON_SIZE_SMALL_TOOLBAR, INKSCAPE_ICON("object-rotate-left"))))); + _counterclockwise_rotate.set_mode(false); + _counterclockwise_rotate.set_relief(Gtk::RELIEF_NONE); + _counterclockwise_rotate.set_tooltip_text(_("Rotate in a counterclockwise direction")); + + _clockwise_rotate.add(*manage( Glib::wrap( + sp_icon_new(Inkscape::ICON_SIZE_SMALL_TOOLBAR, INKSCAPE_ICON("object-rotate-right"))))); + _clockwise_rotate.set_mode(false); + _clockwise_rotate.set_relief(Gtk::RELIEF_NONE); + _clockwise_rotate.set_tooltip_text(_("Rotate in a clockwise direction")); + + Gtk::RadioButton::Group group = _counterclockwise_rotate.get_group(); + _clockwise_rotate.set_group(group); + +#if WITH_GTKMM_3_0 + _page_rotate.table().attach(_scalar_rotate, 0, 0, 2, 1); + _page_rotate.table().attach(_units_rotate, 2, 0, 1, 1); + _page_rotate.table().attach(_counterclockwise_rotate, 3, 0, 1, 1); + _page_rotate.table().attach(_clockwise_rotate, 4, 0, 1, 1); +#else _page_rotate.table() .attach(_scalar_rotate, 0, 2, 0, 1, Gtk::FILL, Gtk::SHRINK); _page_rotate.table() .attach(_units_rotate, 2, 3, 0, 1, Gtk::SHRINK, Gtk::SHRINK); + _page_rotate.table() + .attach(_counterclockwise_rotate, 3, 4, 0, 1, Gtk::SHRINK, Gtk::SHRINK); + + _page_rotate.table() + .attach(_clockwise_rotate, 4, 5, 0, 1, Gtk::SHRINK, Gtk::SHRINK); +#endif + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/dialogs/transformation/rotateCounterClockwise", TRUE)) { + _counterclockwise_rotate.set_active(); + onRotateCounterclockwiseClicked(); + } else { + _clockwise_rotate.set_active(); + onRotateClockwiseClicked(); + } + _scalar_rotate.signal_value_changed() .connect(sigc::mem_fun(*this, &Transformation::onRotateValueChanged)); + _counterclockwise_rotate.signal_clicked().connect(sigc::mem_fun(*this, &Transformation::onRotateCounterclockwiseClicked)); + _clockwise_rotate.signal_clicked().connect(sigc::mem_fun(*this, &Transformation::onRotateClockwiseClicked)); + //TODO: honour rotation center? } @@ -298,16 +391,27 @@ void Transformation::layoutPageSkew() _scalar_skew_vertical.setDigits(3); _scalar_skew_vertical.setIncrements(0.1, 1.0); +#if WITH_GTKMM_3_0 + _page_skew.table().attach(_scalar_skew_horizontal, 0, 0, 2, 1); +#else _page_skew.table() .attach(_scalar_skew_horizontal, 0, 2, 0, 1, Gtk::FILL, Gtk::SHRINK); +#endif + _scalar_skew_horizontal.signal_value_changed() .connect(sigc::mem_fun(*this, &Transformation::onSkewValueChanged)); +#if WITH_GTKMM_3_0 + _page_skew.table().attach(_units_skew, 2, 0, 1, 1); + _page_skew.table().attach(_scalar_skew_vertical, 0, 1, 2, 1); +#else _page_skew.table() .attach(_units_skew, 2, 3, 0, 1, Gtk::SHRINK, Gtk::SHRINK); _page_skew.table() .attach(_scalar_skew_vertical, 0, 2, 1, 2, Gtk::FILL, Gtk::SHRINK); +#endif + _scalar_skew_vertical.signal_value_changed() .connect(sigc::mem_fun(*this, &Transformation::onSkewValueChanged)); @@ -323,30 +427,46 @@ void Transformation::layoutPageTransform() _scalar_transform_a.setDigits(3); _scalar_transform_a.setIncrements(0.1, 1.0); _scalar_transform_a.setValue(1.0); + +#if WITH_GTKMM_3_0 + _page_transform.table().attach(_scalar_transform_a, 0, 0, 1, 1); +#else _page_transform.table() .attach(_scalar_transform_a, 0, 1, 0, 1, Gtk::SHRINK, Gtk::SHRINK); +#endif + _scalar_transform_a.signal_value_changed() .connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); - _scalar_transform_b.setWidgetSizeRequest(65, -1); _scalar_transform_b.setRange(-1e10, 1e10); _scalar_transform_b.setDigits(3); _scalar_transform_b.setIncrements(0.1, 1.0); _scalar_transform_b.setValue(0.0); + +#if WITH_GTKMM_3_0 + _page_transform.table().attach(_scalar_transform_b, 0, 1, 1, 1); +#else _page_transform.table() .attach(_scalar_transform_b, 0, 1, 1, 2, Gtk::SHRINK, Gtk::SHRINK); +#endif + _scalar_transform_b.signal_value_changed() .connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); - _scalar_transform_c.setWidgetSizeRequest(65, -1); _scalar_transform_c.setRange(-1e10, 1e10); _scalar_transform_c.setDigits(3); _scalar_transform_c.setIncrements(0.1, 1.0); _scalar_transform_c.setValue(0.0); + +#if WITH_GTKMM_3_0 + _page_transform.table().attach(_scalar_transform_c, 1, 0, 1, 1); +#else _page_transform.table() .attach(_scalar_transform_c, 1, 2, 0, 1, Gtk::SHRINK, Gtk::SHRINK); +#endif + _scalar_transform_c.signal_value_changed() .connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); @@ -356,8 +476,14 @@ void Transformation::layoutPageTransform() _scalar_transform_d.setDigits(3); _scalar_transform_d.setIncrements(0.1, 1.0); _scalar_transform_d.setValue(1.0); + +#if WITH_GTKMM_3_0 + _page_transform.table().attach(_scalar_transform_d, 1, 1, 1, 1); +#else _page_transform.table() .attach(_scalar_transform_d, 1, 2, 1, 2, Gtk::SHRINK, Gtk::SHRINK); +#endif + _scalar_transform_d.signal_value_changed() .connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); @@ -367,8 +493,14 @@ void Transformation::layoutPageTransform() _scalar_transform_e.setDigits(3); _scalar_transform_e.setIncrements(0.1, 1.0); _scalar_transform_e.setValue(0.0); + +#if WITH_GTKMM_3_0 + _page_transform.table().attach(_scalar_transform_e, 2, 0, 1, 1); +#else _page_transform.table() .attach(_scalar_transform_e, 2, 3, 0, 1, Gtk::SHRINK, Gtk::SHRINK); +#endif + _scalar_transform_e.signal_value_changed() .connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); @@ -378,14 +510,25 @@ void Transformation::layoutPageTransform() _scalar_transform_f.setDigits(3); _scalar_transform_f.setIncrements(0.1, 1.0); _scalar_transform_f.setValue(0.0); + +#if WITH_GTKMM_3_0 + _page_transform.table().attach(_scalar_transform_f, 2, 1, 1, 1); +#else _page_transform.table() .attach(_scalar_transform_f, 2, 3, 1, 2, Gtk::SHRINK, Gtk::SHRINK); +#endif + _scalar_transform_f.signal_value_changed() .connect(sigc::mem_fun(*this, &Transformation::onTransformValueChanged)); // Edit existing matrix +#if WITH_GTKMM_3_0 + _page_transform.table().attach(_check_replace_matrix, 0, 2, 2, 1); +#else _page_transform.table() .attach(_check_replace_matrix, 0, 2, 2, 3, Gtk::FILL, Gtk::SHRINK); +#endif + _check_replace_matrix.set_active(false); _check_replace_matrix.signal_toggled() .connect(sigc::mem_fun(*this, &Transformation::onReplaceMatrixToggled)); @@ -431,8 +574,11 @@ void Transformation::updateSelection(PageType page, Inkscape::Selection *selecti selection && !selection->isEmpty()); } -void Transformation::onSwitchPage(GtkNotebookPage */*page*/, - guint pagenum) +#if WITH_GTKMM_3_0 +void Transformation::onSwitchPage(Gtk::Widget * /*page*/, guint pagenum) +#else +void Transformation::onSwitchPage(GtkNotebookPage * /*page*/, guint pagenum) +#endif { updateSelection((PageType)pagenum, sp_desktop_selection(getDesktop())); } @@ -617,7 +763,7 @@ void Transformation::applyPageMove(Inkscape::Selection *selection) double move = x; for ( std::vector<BBoxSort> ::iterator it (sorted.begin()); it < sorted.end(); - it ++ ) + ++it ) { sp_item_move_rel(it->item, Geom::Translate(move, 0)); // move each next object by x relative to previous @@ -641,7 +787,7 @@ void Transformation::applyPageMove(Inkscape::Selection *selection) double move = y; for ( std::vector<BBoxSort> ::iterator it (sorted.begin()); it < sorted.end(); - it ++ ) + ++it ) { sp_item_move_rel(it->item, Geom::Translate(0, move)); // move each next object by x relative to previous @@ -667,7 +813,8 @@ void Transformation::applyPageScale(Inkscape::Selection *selection) double scaleY = _scalar_scale_vertical.getValue("px"); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - int transform_stroke = prefs->getBool("/options/transform/stroke", true) ? 1 : 0; + bool transform_stroke = prefs->getBool("/options/transform/stroke", true); + bool preserve = prefs->getBool("/options/preservetransform/value", false); if (prefs->getBool("/dialogs/transformation/applyseparately")) { for (GSList const *l = selection->itemList(); l != NULL; l = l->next) { SPItem *item = SP_ITEM(l->data); @@ -689,7 +836,7 @@ void Transformation::applyPageScale(Inkscape::Selection *selection) double x1 = bbox_pref->midpoint()[Geom::X] + new_width/2; double y1 = bbox_pref->midpoint()[Geom::Y] + new_height/2; - Geom::Affine scaler = get_scale_transform_for_variable_stroke (*bbox_pref, *bbox_geom, transform_stroke, x0, y0, x1, y1); + Geom::Affine scaler = get_scale_transform_for_variable_stroke (*bbox_pref, *bbox_geom, transform_stroke, preserve, x0, y0, x1, y1); item->set_i2d_affine(item->i2dt_affine() * scaler); item->doWriteTransform(item->getRepr(), item->transform); } @@ -712,7 +859,7 @@ void Transformation::applyPageScale(Inkscape::Selection *selection) double y0 = bbox_pref->midpoint()[Geom::Y] - new_height/2; double x1 = bbox_pref->midpoint()[Geom::X] + new_width/2; double y1 = bbox_pref->midpoint()[Geom::Y] + new_height/2; - Geom::Affine scaler = get_scale_transform_for_variable_stroke (*bbox_pref, *bbox_geom, transform_stroke, x0, y0, x1, y1); + Geom::Affine scaler = get_scale_transform_for_variable_stroke (*bbox_pref, *bbox_geom, transform_stroke, preserve, x0, y0, x1, y1); sp_selection_apply_affine(selection, scaler); } @@ -727,6 +874,10 @@ void Transformation::applyPageRotate(Inkscape::Selection *selection) double angle = _scalar_rotate.getValue(DEG); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (!prefs->getBool("/dialogs/transformation/rotateCounterClockwise", TRUE)) { + angle *= -1; + } + if (prefs->getBool("/dialogs/transformation/applyseparately")) { for (GSList const *l = selection->itemList(); l != NULL; l = l->next) { SPItem *item = SP_ITEM(l->data); @@ -753,10 +904,21 @@ void Transformation::applyPageSkew(Inkscape::Selection *selection) if (!_units_skew.isAbsolute()) { // percentage double skewX = _scalar_skew_horizontal.getValue("%"); double skewY = _scalar_skew_vertical.getValue("%"); + if (fabs(0.01*skewX*0.01*skewY - 1.0) < Geom::EPSILON) { + sp_desktop_message_stack(getDesktop())->flash(Inkscape::WARNING_MESSAGE, _("Transform matrix is singular, <b>not used</b>.")); + return; + } sp_item_skew_rel (item, 0.01*skewX, 0.01*skewY); } else if (_units_skew.isRadial()) { //deg or rad double angleX = _scalar_skew_horizontal.getValue("rad"); double angleY = _scalar_skew_vertical.getValue("rad"); + if ((fabs(angleX - angleY + M_PI/2) < Geom::EPSILON) + || (fabs(angleX - angleY - M_PI/2) < Geom::EPSILON) + || (fabs((angleX - angleY)/3 + M_PI/2) < Geom::EPSILON) + || (fabs((angleX - angleY)/3 - M_PI/2) < Geom::EPSILON)) { + sp_desktop_message_stack(getDesktop())->flash(Inkscape::WARNING_MESSAGE, _("Transform matrix is singular, <b>not used</b>.")); + return; + } double skewX = tan(-angleX); double skewY = tan(angleY); sp_item_skew_rel (item, skewX, skewY); @@ -767,6 +929,10 @@ void Transformation::applyPageSkew(Inkscape::Selection *selection) if (bbox) { double width = bbox->dimensions()[Geom::X]; double height = bbox->dimensions()[Geom::Y]; + if (fabs(skewX*skewY - width*height) < Geom::EPSILON) { + sp_desktop_message_stack(getDesktop())->flash(Inkscape::WARNING_MESSAGE, _("Transform matrix is singular, <b>not used</b>.")); + return; + } sp_item_skew_rel (item, skewX/height, skewY/width); } } @@ -782,16 +948,31 @@ void Transformation::applyPageSkew(Inkscape::Selection *selection) if (!_units_skew.isAbsolute()) { // percentage double skewX = _scalar_skew_horizontal.getValue("%"); double skewY = _scalar_skew_vertical.getValue("%"); + if (fabs(0.01*skewX*0.01*skewY - 1.0) < Geom::EPSILON) { + sp_desktop_message_stack(getDesktop())->flash(Inkscape::WARNING_MESSAGE, _("Transform matrix is singular, <b>not used</b>.")); + return; + } sp_selection_skew_relative(selection, *center, 0.01*skewX, 0.01*skewY); } else if (_units_skew.isRadial()) { //deg or rad double angleX = _scalar_skew_horizontal.getValue("rad"); double angleY = _scalar_skew_vertical.getValue("rad"); + if ((fabs(angleX - angleY + M_PI/2) < Geom::EPSILON) + || (fabs(angleX - angleY - M_PI/2) < Geom::EPSILON) + || (fabs((angleX - angleY)/3 + M_PI/2) < Geom::EPSILON) + || (fabs((angleX - angleY)/3 - M_PI/2) < Geom::EPSILON)) { + sp_desktop_message_stack(getDesktop())->flash(Inkscape::WARNING_MESSAGE, _("Transform matrix is singular, <b>not used</b>.")); + return; + } double skewX = tan(-angleX); double skewY = tan(angleY); sp_selection_skew_relative(selection, *center, skewX, skewY); } else { // absolute displacement double skewX = _scalar_skew_horizontal.getValue("px"); double skewY = _scalar_skew_vertical.getValue("px"); + if (fabs(skewX*skewY - width*height) < Geom::EPSILON) { + sp_desktop_message_stack(getDesktop())->flash(Inkscape::WARNING_MESSAGE, _("Transform matrix is singular, <b>not used</b>.")); + return; + } sp_selection_skew_relative(selection, *center, skewX/height, skewY/width); } } @@ -812,6 +993,10 @@ void Transformation::applyPageTransform(Inkscape::Selection *selection) double f = _scalar_transform_f.getValue(); Geom::Affine displayed(a, b, c, d, e, f); + if (displayed.isSingular()) { + sp_desktop_message_stack(getDesktop())->flash(Inkscape::WARNING_MESSAGE, _("Transform matrix is singular, <b>not used</b>.")); + return; + } if (_check_replace_matrix.get_active()) { for (GSList const *l = selection->itemList(); l != NULL; l = l->next) { @@ -914,6 +1099,20 @@ void Transformation::onRotateValueChanged() setResponseSensitive(Gtk::RESPONSE_APPLY, true); } +void Transformation::onRotateCounterclockwiseClicked() +{ + _scalar_rotate.setTooltipText(_("Rotation angle (positive = counterclockwise)")); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + prefs->setBool("/dialogs/transformation/rotateCounterClockwise", TRUE); +} + +void Transformation::onRotateClockwiseClicked() +{ + _scalar_rotate.setTooltipText(_("Rotation angle (positive = clockwise)")); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + prefs->setBool("/dialogs/transformation/rotateCounterClockwise", FALSE); +} + void Transformation::onSkewValueChanged() { setResponseSensitive(Gtk::RESPONSE_APPLY, true); diff --git a/src/ui/dialog/transformation.h b/src/ui/dialog/transformation.h index 901a807a5..1d24a0c94 100644 --- a/src/ui/dialog/transformation.h +++ b/src/ui/dialog/transformation.h @@ -12,19 +12,15 @@ #define INKSCAPE_UI_DIALOG_TRANSFORMATION_H - #include <gtkmm/notebook.h> #include <glibmm/i18n.h> - - #include "ui/widget/panel.h" #include "ui/widget/notebook-page.h" #include "ui/widget/scalar-unit.h" #include "ui/widget/imageicon.h" #include "ui/widget/button.h" - - +#include "ui/dialog/desktop-tracker.h" namespace Inkscape { @@ -32,8 +28,6 @@ namespace UI { namespace Dialog { - - /** * Transformation dialog. * @@ -151,11 +145,18 @@ protected: UI::Widget::Scalar _scalar_transform_e; UI::Widget::Scalar _scalar_transform_f; + Gtk::RadioButton _counterclockwise_rotate; + Gtk::RadioButton _clockwise_rotate; + UI::Widget::CheckButton _check_move_relative; UI::Widget::CheckButton _check_scale_proportional; UI::Widget::CheckButton _check_apply_separately; UI::Widget::CheckButton _check_replace_matrix; + SPDesktop *_desktop; + DesktopTracker _deskTrack; + sigc::connection _desktopChangeConn; + /** * Layout the GUI components, and prepare for use */ @@ -167,8 +168,12 @@ protected: virtual void _apply(); void presentPage(PageType page); - void onSwitchPage(GtkNotebookPage *page, - guint pagenum); + +#if WITH_GTKMM_3_0 + void onSwitchPage(Gtk::Widget *page, guint pagenum); +#else + void onSwitchPage(GtkNotebookPage *page, guint pagenum); +#endif /** * Callbacks for when a user changes values on the panels @@ -178,6 +183,8 @@ protected: void onScaleXValueChanged(); void onScaleYValueChanged(); void onRotateValueChanged(); + void onRotateCounterclockwiseClicked(); + void onRotateClockwiseClicked(); void onSkewValueChanged(); void onTransformValueChanged(); void onReplaceMatrixToggled(); @@ -208,6 +215,8 @@ protected: void applyPageSkew(Inkscape::Selection *); void applyPageTransform(Inkscape::Selection *); + void setTargetDesktop(SPDesktop* desktop); + private: /** diff --git a/src/ui/dialog/undo-history.cpp b/src/ui/dialog/undo-history.cpp index 9cc4b39cd..53691cd37 100644 --- a/src/ui/dialog/undo-history.cpp +++ b/src/ui/dialog/undo-history.cpp @@ -5,8 +5,9 @@ /* Author: * Gustav Broberg <broberg@kth.se> * Abhishek Sharma + * Jon A. Cruz <jon@joncruz.org> * - * Copyright (C) 2006 Authors + * Copyright (C) 2014 Authors * Released under GNU GPL. Read the file 'COPYING' for more information. */ @@ -14,16 +15,17 @@ # include <config.h> #endif +#include "undo-history.h" #include <glibmm/i18n.h> #include <stddef.h> #include <sigc++/sigc++.h> -#include "undo-history.h" #include "document.h" #include "document-undo.h" #include "inkscape.h" #include "verbs.h" #include "desktop-handles.h" +#include "util/signal-blocker.h" #include "desktop.h" #include <gtkmm/invisible.h> @@ -33,14 +35,20 @@ namespace UI { namespace Dialog { /* Rendering functions for custom cell renderers */ - -void -CellRendererSPIcon::render_vfunc(const Glib::RefPtr<Gdk::Drawable>& window, - Gtk::Widget& widget, - const Gdk::Rectangle& background_area, - const Gdk::Rectangle& cell_area, - const Gdk::Rectangle& expose_area, - Gtk::CellRendererState flags) +#if WITH_GTKMM_3_0 +void CellRendererSPIcon::render_vfunc(const Cairo::RefPtr<Cairo::Context>& cr, + Gtk::Widget& widget, + const Gdk::Rectangle& background_area, + const Gdk::Rectangle& cell_area, + Gtk::CellRendererState flags) +#else +void CellRendererSPIcon::render_vfunc(const Glib::RefPtr<Gdk::Drawable>& window, + Gtk::Widget& widget, + const Gdk::Rectangle& background_area, + const Gdk::Rectangle& cell_area, + const Gdk::Rectangle& expose_area, + Gtk::CellRendererState flags) +#endif { // if this event type doesn't have an icon... if ( !Inkscape::Verb::get(_property_event_type)->get_image() ) return; @@ -59,8 +67,13 @@ CellRendererSPIcon::render_vfunc(const Glib::RefPtr<Gdk::Drawable>& window, sp_icon_fetch_pixbuf(sp_icon); _property_icon = Glib::wrap(sp_icon->pb, true); } else if ( GTK_IS_IMAGE(icon->gobj()) ) { +#if WITH_GTKMM_3_0 + _property_icon = Gtk::Invisible().render_icon_pixbuf(Gtk::StockID(image), + Gtk::ICON_SIZE_MENU); +#else _property_icon = Gtk::Invisible().render_icon(Gtk::StockID(image), Gtk::ICON_SIZE_MENU); +#endif } else { delete icon; return; @@ -74,25 +87,42 @@ CellRendererSPIcon::render_vfunc(const Glib::RefPtr<Gdk::Drawable>& window, property_pixbuf() = _icon_cache[_property_event_type]; } +#if WITH_GTKMM_3_0 + Gtk::CellRendererPixbuf::render_vfunc(cr, widget, background_area, + cell_area, flags); +#else Gtk::CellRendererPixbuf::render_vfunc(window, widget, background_area, cell_area, expose_area, flags); +#endif } -void -CellRendererInt::render_vfunc(const Glib::RefPtr<Gdk::Drawable>& window, - Gtk::Widget& widget, - const Gdk::Rectangle& background_area, - const Gdk::Rectangle& cell_area, - const Gdk::Rectangle& expose_area, - Gtk::CellRendererState flags) +#if WITH_GTKMM_3_0 +void CellRendererInt::render_vfunc(const Cairo::RefPtr<Cairo::Context>& cr, + Gtk::Widget& widget, + const Gdk::Rectangle& background_area, + const Gdk::Rectangle& cell_area, + Gtk::CellRendererState flags) +#else +void CellRendererInt::render_vfunc(const Glib::RefPtr<Gdk::Drawable>& window, + Gtk::Widget& widget, + const Gdk::Rectangle& background_area, + const Gdk::Rectangle& cell_area, + const Gdk::Rectangle& expose_area, + Gtk::CellRendererState flags) +#endif { if( _filter(_property_number) ) { std::ostringstream s; s << _property_number << std::flush; property_text() = s.str(); +#if WITH_GTKMM_3_0 + Gtk::CellRendererText::render_vfunc(cr, widget, background_area, + cell_area, flags); +#else Gtk::CellRendererText::render_vfunc(window, widget, background_area, cell_area, expose_area, flags); +#endif } } @@ -103,76 +133,64 @@ UndoHistory& UndoHistory::getInstance() return *new UndoHistory(); } -void -UndoHistory::setDesktop(SPDesktop* desktop) -{ - Panel::setDesktop(desktop); - - if (!desktop) return; - - _document = sp_desktop_document(desktop); - - _event_log = desktop->event_log; - - _callback_connections[EventLog::CALLB_SELECTION_CHANGE].block(); - - _event_list_store = _event_log->getEventListStore(); - _event_list_view.set_model(_event_list_store); - _event_list_selection = _event_list_view.get_selection(); - - _event_log->connectWithDialog(&_event_list_view, &_callback_connections); - _event_list_view.scroll_to_row(_event_list_store->get_path(_event_list_selection->get_selected())); - - _callback_connections[EventLog::CALLB_SELECTION_CHANGE].block(false); -} - UndoHistory::UndoHistory() : UI::Widget::Panel ("", "/dialogs/undo-history", SP_VERB_DIALOG_UNDO_HISTORY), - _document (sp_desktop_document(getDesktop())), - _event_log (getDesktop() ? getDesktop()->event_log : NULL), - _columns (_event_log ? &_event_log->getColumns() : NULL), - _event_list_selection (_event_list_view.get_selection()) + _document_replaced_connection(), + _desktop(getDesktop()), + _document(_desktop ? _desktop->doc() : NULL), + _event_log(_desktop ? _desktop->event_log : NULL), + _columns(_event_log ? &_event_log->getColumns() : NULL), + _scrolled_window(), + _event_list_store(), + _event_list_selection(_event_list_view.get_selection()), + _deskTrack(), + _desktopChangeConn(), + _callback_connections() { if ( !_document || !_event_log || !_columns ) return; - set_size_request(300, 95); + set_size_request(-1, 95); _getContents()->pack_start(_scrolled_window); _scrolled_window.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); - _event_list_store = _event_log->getEventListStore(); + // connect with the EventLog + _connectEventLog(); - _event_list_view.set_model(_event_list_store); _event_list_view.set_rules_hint(false); _event_list_view.set_enable_search(false); _event_list_view.set_headers_visible(false); CellRendererSPIcon* icon_renderer = Gtk::manage(new CellRendererSPIcon()); - icon_renderer->property_xpad() = 8; - icon_renderer->property_width() = 36; + icon_renderer->property_xpad() = 2; + icon_renderer->property_width() = 24; int cols_count = _event_list_view.append_column("Icon", *icon_renderer); Gtk::TreeView::Column* icon_column = _event_list_view.get_column(cols_count-1); icon_column->add_attribute(icon_renderer->property_event_type(), _columns->type); + CellRendererInt* children_renderer = Gtk::manage(new CellRendererInt(greater_than_1)); + children_renderer->property_weight() = 600; // =Pango::WEIGHT_SEMIBOLD (not defined in old versions of pangomm) + children_renderer->property_xalign() = 1.0; + children_renderer->property_xpad() = 2; + children_renderer->property_width() = 24; + + cols_count = _event_list_view.append_column("Children", *children_renderer); + Gtk::TreeView::Column* children_column = _event_list_view.get_column(cols_count-1); + children_column->add_attribute(children_renderer->property_number(), _columns->child_count); + Gtk::CellRendererText* description_renderer = Gtk::manage(new Gtk::CellRendererText()); + description_renderer->property_ellipsize() = Pango::ELLIPSIZE_END; cols_count = _event_list_view.append_column("Description", *description_renderer); Gtk::TreeView::Column* description_column = _event_list_view.get_column(cols_count-1); description_column->add_attribute(description_renderer->property_text(), _columns->description); description_column->set_resizable(); + description_column->set_sizing(Gtk::TREE_VIEW_COLUMN_AUTOSIZE); + description_column->set_min_width (150); _event_list_view.set_expander_column( *_event_list_view.get_column(cols_count-1) ); - CellRendererInt* children_renderer = Gtk::manage(new CellRendererInt(greater_than_1)); - children_renderer->property_weight() = 600; // =Pango::WEIGHT_SEMIBOLD (not defined in old versions of pangomm) - children_renderer->property_xalign() = 1.0; - children_renderer->property_xpad() = 20; - - cols_count = _event_list_view.append_column("Children", *children_renderer); - Gtk::TreeView::Column* children_column = _event_list_view.get_column(cols_count-1); - children_column->add_attribute(children_renderer->property_number(), _columns->child_count); - _scrolled_window.add(_event_list_view); // connect EventLog callbacks @@ -185,8 +203,11 @@ UndoHistory::UndoHistory() _callback_connections[EventLog::CALLB_COLLAPSE] = _event_list_view.signal_row_collapsed().connect(sigc::mem_fun(*this, &Inkscape::UI::Dialog::UndoHistory::_onCollapseEvent)); - // connect with the EventLog - _event_log->connectWithDialog(&_event_list_view, &_callback_connections); + _desktopChangeConn = _deskTrack.connectDesktopChanged( sigc::mem_fun(*this, &UndoHistory::setDesktop) ); + _deskTrack.connect(GTK_WIDGET(gobj())); + + // connect to be informed of document changes + signalDocumentReplaced().connect(sigc::mem_fun(*this, &UndoHistory::_handleDocumentReplaced)); show_all_children(); @@ -196,6 +217,84 @@ UndoHistory::UndoHistory() UndoHistory::~UndoHistory() { + _desktopChangeConn.disconnect(); +} + + +void UndoHistory::setDesktop(SPDesktop* desktop) +{ + Panel::setDesktop(desktop); + + EventLog *newEventLog = desktop ? desktop->event_log : NULL; + if ((_desktop == desktop) && (_event_log == newEventLog)) { + // same desktop set + } + else + { + _connectDocument(desktop, desktop ? desktop->doc() : NULL); + } +} + +void UndoHistory::_connectDocument(SPDesktop* desktop, SPDocument * /*document*/) +{ + // disconnect from prior + if (_event_log) { + _event_log->removeDialogConnection(&_event_list_view, &_callback_connections); + } + + SignalBlocker blocker(&_callback_connections[EventLog::CALLB_SELECTION_CHANGE]); + + _event_list_view.unset_model(); + + // connect to new EventLog/Desktop + _desktop = desktop; + _event_log = desktop ? desktop->event_log : NULL; + _document = desktop ? desktop->doc() : NULL; + _connectEventLog(); +} + +void UndoHistory::_connectEventLog() +{ + if (_event_log) { + _event_log->add_destroy_notify_callback(this, &_handleEventLogDestroyCB); + _event_list_store = _event_log->getEventListStore(); + + _event_list_view.set_model(_event_list_store); + + _event_log->addDialogConnection(&_event_list_view, &_callback_connections); + _event_list_view.scroll_to_row(_event_list_store->get_path(_event_list_selection->get_selected())); + } +} + +void UndoHistory::_handleDocumentReplaced(SPDesktop* desktop, SPDocument *document) +{ + if ((desktop != _desktop) || (document != _document)) { + _connectDocument(desktop, document); + } +} + +void *UndoHistory::_handleEventLogDestroyCB(void *data) +{ + void *result = NULL; + if (data) { + UndoHistory *self = reinterpret_cast<UndoHistory*>(data); + result = self->_handleEventLogDestroy(); + } + return result; +} + +// called *after* _event_log has been destroyed. +void *UndoHistory::_handleEventLogDestroy() +{ + if (_event_log) { + SignalBlocker blocker(&_callback_connections[EventLog::CALLB_SELECTION_CHANGE]); + + _event_list_view.unset_model(); + _event_list_store.reset(); + _event_log = NULL; + } + + return NULL; } void diff --git a/src/ui/dialog/undo-history.h b/src/ui/dialog/undo-history.h index ee7941580..b0cc283cf 100644 --- a/src/ui/dialog/undo-history.h +++ b/src/ui/dialog/undo-history.h @@ -3,8 +3,9 @@ */ /* Author: * Gustav Broberg <broberg@kth.se> + * Jon A. Cruz <jon@joncruz.org> * - * Copyright (C) 2006 Authors + * Copyright (C) 2014 Authors * Released under GNU GPL. Read the file 'COPYING' for more information. */ @@ -24,6 +25,7 @@ #include "event-log.h" #include "widgets/icon.h" +#include "ui/dialog/desktop-tracker.h" class SPDesktop; @@ -48,19 +50,26 @@ public: property_event_type() { return _property_event_type.get_proxy(); } protected: - - virtual void - render_vfunc(const Glib::RefPtr<Gdk::Drawable>& window, - Gtk::Widget& widget, - const Gdk::Rectangle& background_area, - const Gdk::Rectangle& cell_area, - const Gdk::Rectangle& expose_area, - Gtk::CellRendererState flags); +#if WITH_GTKMM_3_0 + virtual void render_vfunc(const Cairo::RefPtr<Cairo::Context>& cr, + Gtk::Widget& widget, + const Gdk::Rectangle& background_area, + const Gdk::Rectangle& cell_area, + Gtk::CellRendererState flags); +#else + virtual void render_vfunc(const Glib::RefPtr<Gdk::Drawable>& window, + Gtk::Widget& widget, + const Gdk::Rectangle& background_area, + const Gdk::Rectangle& cell_area, + const Gdk::Rectangle& expose_area, + Gtk::CellRendererState flags); +#endif private: Glib::Property<Glib::RefPtr<Gdk::Pixbuf> > _property_icon; Glib::Property<unsigned int> _property_event_type; std::map<const unsigned int, Glib::RefPtr<Gdk::Pixbuf> > _icon_cache; + }; @@ -85,15 +94,21 @@ public: static const Filter& no_filter; - protected: - - virtual void - render_vfunc(const Glib::RefPtr<Gdk::Drawable>& window, - Gtk::Widget& widget, - const Gdk::Rectangle& background_area, - const Gdk::Rectangle& cell_area, - const Gdk::Rectangle& expose_area, - Gtk::CellRendererState flags); +protected: +#if WITH_GTKMM_3_0 + virtual void render_vfunc(const Cairo::RefPtr<Cairo::Context>& cr, + Gtk::Widget& widget, + const Gdk::Rectangle& background_area, + const Gdk::Rectangle& cell_area, + Gtk::CellRendererState flags); +#else + virtual void render_vfunc(const Glib::RefPtr<Gdk::Drawable>& window, + Gtk::Widget& widget, + const Gdk::Rectangle& background_area, + const Gdk::Rectangle& cell_area, + const Gdk::Rectangle& expose_area, + Gtk::CellRendererState flags); +#endif private: @@ -120,9 +135,11 @@ public: protected: + SPDesktop *_desktop; SPDocument *_document; EventLog *_event_log; + const EventLog::EventModelColumns *_columns; Gtk::ScrolledWindow _scrolled_window; @@ -131,8 +148,17 @@ protected: Gtk::TreeView _event_list_view; Glib::RefPtr<Gtk::TreeSelection> _event_list_selection; + DesktopTracker _deskTrack; + sigc::connection _desktopChangeConn; + EventLog::CallbackMap _callback_connections; + static void *_handleEventLogDestroyCB(void *data); + + void _connectDocument(SPDesktop* desktop, SPDocument *document); + void _connectEventLog(); + void _handleDocumentReplaced(SPDesktop* desktop, SPDocument *document); + void *_handleEventLogDestroy(); void _onListSelectionChange(); void _onExpandEvent(const Gtk::TreeModel::iterator &iter, const Gtk::TreeModel::Path &path); void _onCollapseEvent(const Gtk::TreeModel::iterator &iter, const Gtk::TreeModel::Path &path); diff --git a/src/ui/dialog/xml-tree.cpp b/src/ui/dialog/xml-tree.cpp index 03678d26d..55d0aff09 100644 --- a/src/ui/dialog/xml-tree.cpp +++ b/src/ui/dialog/xml-tree.cpp @@ -27,7 +27,7 @@ #include "dialogs/dialog-events.h" #include "document.h" #include "document-undo.h" -#include "event-context.h" +#include "ui/tools/tool-base.h" #include "helper/window.h" #include "inkscape.h" #include "interface.h" @@ -48,10 +48,6 @@ #include "widgets/sp-xmlview-content.h" #include "widgets/sp-xmlview-tree.h" -#if !GTK_CHECK_VERSION(2,22,0) -#include "compat-key-syms.h" -#endif - namespace Inkscape { namespace UI { namespace Dialog { @@ -83,7 +79,11 @@ XmlTree::XmlTree (void) : xml_attribute_delete_button (_("Delete attribute")), text_container (), attr_container (), - attr_subpaned_container (), +#if WITH_GTKMM_3_0 + attr_subpaned_container(Gtk::ORIENTATION_VERTICAL), +#else + attr_subpaned_container(), +#endif set_attr (_("Set")), new_window(NULL) { @@ -100,6 +100,9 @@ XmlTree::XmlTree (void) : status.set_alignment( 0.0, 0.5); status.set_size_request(1, -1); status.set_markup(""); +#if WITH_GTKMM_3_0 + status.set_line_wrap(true); +#endif status_box.pack_start( status, TRUE, TRUE, 0); contents->pack_end(status_box, false, false, 2); @@ -328,7 +331,7 @@ void XmlTree::attr_reset_context(gint attr) bool XmlTree::sp_xml_tree_key_press(GdkEventKey *event) { - unsigned int shortcut = get_group0_keyval (event) | + unsigned int shortcut = Inkscape::UI::Tools::get_group0_keyval (event) | ( event->state & GDK_SHIFT_MASK ? SP_SHORTCUT_SHIFT_MASK : 0 ) | ( event->state & GDK_CONTROL_MASK ? @@ -450,7 +453,7 @@ void XmlTree::set_tree_select(Inkscape::XML::Node *repr) void XmlTree::propagate_tree_select(Inkscape::XML::Node *repr) { - if (repr && repr->type() == Inkscape::XML::ELEMENT_NODE) { + if (repr && (repr->type() == Inkscape::XML::ELEMENT_NODE)) { sp_xmlview_attr_list_set_repr(attributes, repr); } else { sp_xmlview_attr_list_set_repr(attributes, NULL); @@ -536,7 +539,7 @@ void XmlTree::on_tree_select_row(GtkTreeSelection *selection, gpointer data) return; } - Inkscape::XML::Node *repr = sp_xmlview_tree_node_get_repr(GTK_TREE_VIEW(self->tree), &iter); + Inkscape::XML::Node *repr = sp_xmlview_tree_node_get_repr(model, &iter); g_assert(repr != NULL); @@ -586,7 +589,7 @@ void XmlTree::on_tree_select_row_enable(GtkTreeIter *node) return; } - Inkscape::XML::Node *repr = sp_xmlview_tree_node_get_repr(GTK_TREE_VIEW(tree), node); + Inkscape::XML::Node *repr = sp_xmlview_tree_node_get_repr(GTK_TREE_MODEL(tree->store), node); Inkscape::XML::Node *parent=repr->parent(); //on_tree_select_row_enable_if_mutable @@ -631,7 +634,7 @@ void XmlTree::on_tree_select_row_enable(GtkTreeIter *node) prev && prev->next() != repr ; prev = prev->next() ){}; - if (prev && prev->type() == Inkscape::XML::ELEMENT_NODE) { + if (prev && (prev->type() == Inkscape::XML::ELEMENT_NODE)) { indentable = TRUE; } } @@ -650,7 +653,7 @@ void XmlTree::on_tree_select_row_enable(GtkTreeIter *node) //on_tree_select_row_enable_if_not_last_child { - if ( parent && parent->parent() && repr->next() ) { + if ( parent && (parent->parent() && repr->next())) { lower_node_button.set_sensitive(true); } else { lower_node_button.set_sensitive(false); @@ -690,7 +693,7 @@ gboolean XmlTree::xml_tree_node_mutable(GtkTreeIter *node) } Inkscape::XML::Node *repr; - repr = sp_xmlview_tree_node_get_repr(GTK_TREE_VIEW(tree), node); + repr = sp_xmlview_tree_node_get_repr(GTK_TREE_MODEL(tree->store), node); g_assert(repr); // don't let "defs" or "namedview" disappear @@ -842,10 +845,14 @@ void XmlTree::on_document_uri_set(gchar const * /*uri*/, SPDocument * /*document gboolean XmlTree::quit_on_esc (GtkWidget *w, GdkEventKey *event, GObject */*tbl*/) { - switch (get_group0_keyval (event)) { + switch (Inkscape::UI::Tools::get_group0_keyval (event)) { case GDK_KEY_Escape: // defocus gtk_widget_destroy(w); return TRUE; + case GDK_KEY_Return: // create + case GDK_KEY_KP_Enter: + gtk_widget_destroy(w); + return TRUE; } return FALSE; } @@ -866,16 +873,32 @@ void XmlTree::cmd_new_element_node() g_signal_connect(G_OBJECT(new_window), "destroy", gtk_main_quit, NULL); g_signal_connect(G_OBJECT(new_window), "key-press-event", G_CALLBACK(quit_on_esc), new_window); +#if GTK_CHECK_VERSION(3,0,0) + vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 4); + gtk_box_set_homogeneous(GTK_BOX(vbox), FALSE); +#else vbox = gtk_vbox_new(FALSE, 4); +#endif + gtk_container_add(GTK_CONTAINER(new_window), vbox); name_entry = new Gtk::Entry(); gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(name_entry->gobj()), FALSE, TRUE, 0); +#if GTK_CHECK_VERSION(3,0,0) + sep = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL); +#else sep = gtk_hseparator_new(); +#endif + gtk_box_pack_start(GTK_BOX(vbox), sep, FALSE, TRUE, 0); +#if GTK_CHECK_VERSION(3,0,0) + bbox = gtk_button_box_new(GTK_ORIENTATION_HORIZONTAL); +#else bbox = gtk_hbutton_box_new(); +#endif + gtk_container_set_border_width(GTK_CONTAINER(bbox), 4); gtk_button_box_set_layout(GTK_BUTTON_BOX(bbox), GTK_BUTTONBOX_END); gtk_box_pack_start(GTK_BOX(vbox), bbox, FALSE, TRUE, 0); @@ -958,8 +981,6 @@ void XmlTree::cmd_duplicate_node() if (sp_xmlview_tree_get_repr_node(SP_XMLVIEW_TREE(tree), dup, &node)) { GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree)); gtk_tree_selection_select_iter(selection, &node); - } else { - } } @@ -968,6 +989,7 @@ void XmlTree::cmd_delete_node() g_assert(selected_repr != NULL); sp_repr_unparent(selected_repr); + reinterpret_cast<SPObject *>(current_desktop->currentLayer())->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); DocumentUndo::done(current_document, SP_VERB_DIALOG_XML_EDITOR, Q_("nodeAsInXMLinHistoryDialog|Delete node")); } @@ -1030,7 +1052,7 @@ void XmlTree::cmd_raise_node() Inkscape::XML::Node *ref = NULL; Inkscape::XML::Node *before = parent->firstChild(); - while (before && before->next() != selected_repr) { + while (before && (before->next() != selected_repr)) { ref = before; before = before->next(); } @@ -1072,7 +1094,7 @@ void XmlTree::cmd_indent_node() g_return_if_fail(parent->firstChild() != repr); Inkscape::XML::Node* prev = parent->firstChild(); - while (prev && prev->next() != repr) { + while (prev && (prev->next() != repr)) { prev = prev->next(); } g_return_if_fail(prev != NULL); diff --git a/src/ui/dialog/xml-tree.h b/src/ui/dialog/xml-tree.h index ee1dadc14..58ef3aef8 100644 --- a/src/ui/dialog/xml-tree.h +++ b/src/ui/dialog/xml-tree.h @@ -13,6 +13,10 @@ #ifndef SEEN_DIALOGS_XML_TREE_H #define SEEN_DIALOGS_XML_TREE_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + #include "ui/widget/panel.h" #include <gtkmm/entry.h> #include <gtkmm/textview.h> @@ -24,8 +28,8 @@ #include "ui/dialog/desktop-tracker.h" #include "message.h" -struct SPDesktop; -struct SPObject; +class SPDesktop; +class SPObject; struct SPXMLViewAttrList; struct SPXMLViewContent; struct SPXMLViewTree; @@ -215,7 +219,12 @@ private: Gtk::Button *create_button; Gtk::Entry *name_entry; +#if WITH_GTKMM_3_0 + Gtk::Paned paned; +#else Gtk::HPaned paned; +#endif + Gtk::VBox left_box; Gtk::VBox right_box; Gtk::HBox status_box; @@ -239,7 +248,13 @@ private: Gtk::ScrolledWindow text_container; Gtk::HBox attr_hbox; Gtk::VBox attr_container; + +#if WITH_GTKMM_3_0 + Gtk::Paned attr_subpaned_container; +#else Gtk::VPaned attr_subpaned_container; +#endif + Gtk::Button set_attr; GtkWidget *new_window; diff --git a/src/ui/previewable.h b/src/ui/previewable.h index 9a086a9a2..377e109fb 100644 --- a/src/ui/previewable.h +++ b/src/ui/previewable.h @@ -35,12 +35,13 @@ typedef enum { VIEW_TYPE_GRID } ViewType; + class Previewable { public: // TODO need to add some nice parameters virtual ~Previewable() {} - virtual Gtk::Widget* getPreview( PreviewStyle style, ViewType view, ::PreviewSize size, guint ratio ) = 0; + virtual Gtk::Widget* getPreview( PreviewStyle style, ViewType view, ::PreviewSize size, guint ratio, guint border) = 0; }; diff --git a/src/ui/previewfillable.h b/src/ui/previewfillable.h index d5f609a0b..044357503 100644 --- a/src/ui/previewfillable.h +++ b/src/ui/previewfillable.h @@ -28,11 +28,12 @@ public: virtual void addPreview( Previewable* preview ) = 0; virtual void freezeUpdates() = 0; virtual void thawUpdates() = 0; - virtual void setStyle( ::PreviewSize size, ViewType type, guint ratio) = 0; + virtual void setStyle( ::PreviewSize size, ViewType type, guint ratio, ::BorderStyle border ) = 0; virtual void setOrientation(SPAnchorType how) = 0; virtual ::PreviewSize getPreviewSize() const = 0; virtual ViewType getPreviewType() const = 0; virtual guint getPreviewRatio() const = 0; + virtual ::BorderStyle getPreviewBorder() const = 0; virtual void setWrap( bool b ) = 0; virtual bool getWrap() const = 0; }; diff --git a/src/ui/previewholder.cpp b/src/ui/previewholder.cpp index d89df1104..38f6f353f 100644 --- a/src/ui/previewholder.cpp +++ b/src/ui/previewholder.cpp @@ -12,10 +12,18 @@ #include "previewholder.h" +#include "preferences.h" #include <gtkmm/scrolledwindow.h> #include <gtkmm/sizegroup.h> #include <gtkmm/scrollbar.h> +#include <gtkmm/adjustment.h> + +#if WITH_GTKMM_3_0 +# include <gtkmm/grid.h> +#else +# include <gtkmm/table.h> +#endif #define COLUMNS_FOR_SMALL 16 #define COLUMNS_FOR_LARGE 8 @@ -38,25 +46,67 @@ PreviewHolder::PreviewHolder() : _baseSize(PREVIEW_SIZE_SMALL), _ratio(100), _view(VIEW_TYPE_LIST), - _wrap(false) + _wrap(false), + _border(BORDER_NONE) { _scroller = manage(new Gtk::ScrolledWindow()); + ((Gtk::ScrolledWindow *)_scroller)->set_policy(Gtk::POLICY_AUTOMATIC, + Gtk::POLICY_AUTOMATIC); + +#if WITH_GTKMM_3_0 + _insides = manage(new Gtk::Grid()); + _insides->set_column_spacing(8); + + // Add a container with the scroller and a spacer + Gtk::Grid* spaceHolder = manage(new Gtk::Grid()); + + _scroller->set_hexpand(); + _scroller->set_vexpand(); +#else _insides = manage(new Gtk::Table( 1, 2 )); _insides->set_col_spacings( 8 ); - + // Add a container with the scroller and a spacer Gtk::Table* spaceHolder = manage( new Gtk::Table(1, 2) ); +#endif + _scroller->add( *_insides ); + +#if WITH_GTKMM_3_0 + spaceHolder->attach( *_scroller, 0, 0, 1, 1); +#else spaceHolder->attach( *_scroller, 0, 1, 0, 1, Gtk::FILL|Gtk::EXPAND, Gtk::FILL|Gtk::EXPAND ); +#endif pack_start(*spaceHolder, Gtk::PACK_EXPAND_WIDGET); } PreviewHolder::~PreviewHolder() { + } +bool PreviewHolder::on_scroll_event(GdkEventScroll *event) +{ + // Scroll horizontally by page on mouse wheel +#if WITH_GTKMM_3_0 + Glib::RefPtr<Gtk::Adjustment> adj = dynamic_cast<Gtk::ScrolledWindow*>(_scroller)->get_hadjustment(); +#else + Gtk::Adjustment *adj = dynamic_cast<Gtk::ScrolledWindow*>(_scroller)->get_hadjustment(); +#endif + + if (!adj) { + return FALSE; + } + + int move = (event->direction == GDK_SCROLL_DOWN) ? adj->get_page_size() : -adj->get_page_size(); + + double value = std::min(adj->get_upper() - move, adj->get_value() + move ); + adj->set_value(value); + + return FALSE; +} void PreviewHolder::clear() { @@ -69,6 +119,11 @@ void PreviewHolder::clear() rebuildUI(); } +/** + * Add a Previewable item to the PreviewHolder + * + * \param[in] preview The Previewable item to add + */ void PreviewHolder::addPreview( Previewable* preview ) { items.push_back(preview); @@ -76,41 +131,78 @@ void PreviewHolder::addPreview( Previewable* preview ) { int i = items.size() - 1; - if ( _view == VIEW_TYPE_LIST ) { - Gtk::Widget* label = manage(preview->getPreview(PREVIEW_STYLE_BLURB, VIEW_TYPE_LIST, _baseSize, _ratio)); - Gtk::Widget* thing = manage(preview->getPreview(PREVIEW_STYLE_PREVIEW, VIEW_TYPE_LIST, _baseSize, _ratio)); + switch(_view) { + case VIEW_TYPE_LIST: + { + Gtk::Widget* label = manage(preview->getPreview(PREVIEW_STYLE_BLURB, VIEW_TYPE_LIST, _baseSize, _ratio, _border)); + Gtk::Widget* thing = manage(preview->getPreview(PREVIEW_STYLE_PREVIEW, VIEW_TYPE_LIST, _baseSize, _ratio, _border)); - _insides->attach( *thing, 0, 1, i, i+1, Gtk::FILL|Gtk::EXPAND, Gtk::FILL|Gtk::EXPAND ); - _insides->attach( *label, 1, 2, i, i+1, Gtk::FILL|Gtk::EXPAND, Gtk::SHRINK ); - } else { - Gtk::Widget* thing = manage(items[i]->getPreview(PREVIEW_STYLE_PREVIEW, VIEW_TYPE_GRID, _baseSize, _ratio)); - - int width = 1; - int height = 1; - calcGridSize( thing, items.size(), width, height ); - int col = i % width; - int row = i / width; - - if ( _insides && width > (int)_insides->property_n_columns() ) { - std::vector<Gtk::Widget*>kids = _insides->get_children(); - int oldWidth = (int)_insides->property_n_columns(); - int childCount = (int)kids.size(); -// g_message(" %3d resize from %d to %d (r:%d, c:%d) with %d children", i, oldWidth, width, row, col, childCount ); - _insides->resize( height, width ); - - for ( int j = oldWidth; j < childCount; j++ ) { - Gtk::Widget* target = kids[childCount - (j + 1)]; - int col2 = j % width; - int row2 = j / width; - Glib::RefPtr<Gtk::Widget> handle(target); - _insides->remove( *target ); - _insides->attach( *target, col2, col2+1, row2, row2+1, Gtk::FILL|Gtk::EXPAND, Gtk::FILL|Gtk::EXPAND ); +#if WITH_GTKMM_3_0 + thing->set_hexpand(); + thing->set_vexpand(); + _insides->attach(*thing, 0, i, 1, 1); + + label->set_hexpand(); + label->set_valign(Gtk::ALIGN_CENTER); + _insides->attach(*label, 1, i, 1, 1); +#else + _insides->attach( *thing, 0, 1, i, i+1, Gtk::FILL|Gtk::EXPAND, Gtk::FILL|Gtk::EXPAND ); + _insides->attach( *label, 1, 2, i, i+1, Gtk::FILL|Gtk::EXPAND, Gtk::SHRINK ); +#endif + } + + break; + case VIEW_TYPE_GRID: + { + Gtk::Widget* thing = manage(items[i]->getPreview(PREVIEW_STYLE_PREVIEW, VIEW_TYPE_GRID, _baseSize, _ratio, _border)); + + int width = 1; + int height = 1; + calcGridSize( thing, items.size(), width, height ); + + // Column and row for the new widget + int col = i % width; + int row = i / width; + +#if !WITH_GTKMM_3_0 + // If the existing grid isn't wide enough, we need to resize + // it and re-pack the existing widgets + if ( _insides && width > (int)_insides->property_n_columns() ) { + _insides->resize( height, width ); +#endif + std::vector<Gtk::Widget*>kids = _insides->get_children(); + int childCount = (int)kids.size(); + // g_message(" %3d resize from %d to %d (r:%d, c:%d) with %d children", i, oldWidth, width, row, col, childCount ); + + // Loop through the existing widgets and move them to new location + for ( int j = 1; j < childCount; j++ ) { + Gtk::Widget* target = kids[childCount - (j + 1)]; + int col2 = j % width; + int row2 = j / width; + Glib::RefPtr<Gtk::Widget> handle(target); + _insides->remove( *target ); + +#if WITH_GTKMM_3_0 + target->set_hexpand(); + target->set_vexpand(); + _insides->attach( *target, col2, row2, 1, 1); +#else + _insides->attach( *target, col2, col2+1, row2, row2+1, Gtk::FILL|Gtk::EXPAND, Gtk::FILL|Gtk::EXPAND ); +#endif + } +#if WITH_GTKMM_3_0 + thing->set_hexpand(); + thing->set_vexpand(); + _insides->attach(*thing, col, row, 1, 1); +#else + } else if ( col == 0 ) { + // we just started a new row + _insides->resize( row + 1, width ); + } + + _insides->attach( *thing, col, col+1, row, row+1, Gtk::FILL|Gtk::EXPAND, Gtk::FILL|Gtk::EXPAND ); +#endif } - } else if ( col == 0 ) { - // we just started a new row - _insides->resize( row + 1, width ); - } - _insides->attach( *thing, col, col+1, row, row+1, Gtk::FILL|Gtk::EXPAND, Gtk::FILL|Gtk::EXPAND ); } _scroller->show_all_children(); @@ -129,12 +221,13 @@ void PreviewHolder::thawUpdates() rebuildUI(); } -void PreviewHolder::setStyle( ::PreviewSize size, ViewType view, guint ratio ) +void PreviewHolder::setStyle( ::PreviewSize size, ViewType view, guint ratio, ::BorderStyle border ) { - if ( size != _baseSize || view != _view || ratio != _ratio ) { + if ( size != _baseSize || view != _view || ratio != _ratio || border != _border ) { _baseSize = size; _view = view; _ratio = ratio; + _border = border; // Kludge to restore scrollbars if ( !_wrap && (_view != VIEW_TYPE_LIST) && (_anchor == SP_ANCHOR_NORTH || _anchor == SP_ANCHOR_SOUTH) ) { dynamic_cast<Gtk::ScrolledWindow*>(_scroller)->set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_NEVER ); @@ -224,17 +317,26 @@ void PreviewHolder::on_size_allocate( Gtk::Allocation& allocation ) } } -void PreviewHolder::on_size_request( Gtk::Requisition* requisition ) -{ +//void PreviewHolder::on_size_request( Gtk::Requisition* requisition ) +//{ // g_message( "on_size_request(%d, %d)", requisition->width, requisition->height ); - Gtk::VBox::on_size_request( requisition ); +// Gtk::VBox::on_size_request( requisition ); // g_message( " super (%d, %d)", requisition->width, requisition->height ); // g_message(" anchor:%d", _anchor); // g_message(" items:%d", (int)items.size()); -} +//} +/** + * Calculate the grid side of a preview holder + * + * \param[in] thing + * \param[in] itemCount The number of items to pack into the grid + * \param[out] width The width of the grid + * \param[out] height The height of the grid + */ void PreviewHolder::calcGridSize( const Gtk::Widget* thing, int itemCount, int& width, int& height ) { + // Initially set all items in a horizontal row width = itemCount; height = 1; @@ -301,45 +403,104 @@ void PreviewHolder::rebuildUI() _scroller->remove(); _insides = 0; // remove() call should have deleted the Gtk::Table. - if ( _view == VIEW_TYPE_LIST ) { - _insides = manage(new Gtk::Table( 1, 2 )); - _insides->set_col_spacings( 8 ); + switch(_view) { + case VIEW_TYPE_LIST: + { + +#if WITH_GTKMM_3_0 + _insides = manage(new Gtk::Grid()); + _insides->set_column_spacing(8); +#else + _insides = manage(new Gtk::Table( 1, 2 )); + _insides->set_col_spacings( 8 ); +#endif - for ( unsigned int i = 0; i < items.size(); i++ ) { - Gtk::Widget* label = manage(items[i]->getPreview(PREVIEW_STYLE_BLURB, _view, _baseSize, _ratio)); - //label->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER); + if (_border == BORDER_WIDE) { +#if WITH_GTKMM_3_0 + _insides->set_row_spacing(1); +#else + _insides->set_row_spacings( 1 ); +#endif + } - Gtk::Widget* thing = manage(items[i]->getPreview(PREVIEW_STYLE_PREVIEW, _view, _baseSize, _ratio)); + for ( unsigned int i = 0; i < items.size(); i++ ) { + Gtk::Widget* label = manage(items[i]->getPreview(PREVIEW_STYLE_BLURB, _view, _baseSize, _ratio, _border)); + //label->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER); - _insides->attach( *thing, 0, 1, i, i+1, Gtk::FILL|Gtk::EXPAND, Gtk::FILL|Gtk::EXPAND ); - _insides->attach( *label, 1, 2, i, i+1, Gtk::FILL|Gtk::EXPAND, Gtk::SHRINK ); - } - _scroller->add( *_insides ); - } else { - int col = 0; - int row = 0; - int width = 2; - int height = 1; + Gtk::Widget* thing = manage(items[i]->getPreview(PREVIEW_STYLE_PREVIEW, _view, _baseSize, _ratio, _border)); - for ( unsigned int i = 0; i < items.size(); i++ ) { - Gtk::Widget* thing = manage(items[i]->getPreview(PREVIEW_STYLE_PREVIEW, _view, _baseSize, _ratio)); +#if WITH_GTKMM_3_0 + thing->set_hexpand(); + thing->set_vexpand(); + _insides->attach(*thing, 0, i, 1, 1); - if ( !_insides ) { - calcGridSize( thing, items.size(), width, height ); - _insides = manage(new Gtk::Table( height, width )); - } + label->set_hexpand(); + label->set_valign(Gtk::ALIGN_CENTER); + _insides->attach(*label, 1, i, 1, 1); +#else + _insides->attach( *thing, 0, 1, i, i+1, Gtk::FILL|Gtk::EXPAND, Gtk::FILL|Gtk::EXPAND ); + _insides->attach( *label, 1, 2, i, i+1, Gtk::FILL|Gtk::EXPAND, Gtk::SHRINK ); +#endif + } - _insides->attach( *thing, col, col+1, row, row+1, Gtk::FILL|Gtk::EXPAND, Gtk::FILL|Gtk::EXPAND ); - if ( ++col >= width ) { - col = 0; - row++; + _scroller->add( *_insides ); } - } - if ( !_insides ) { - _insides = manage(new Gtk::Table( 1, 2 )); - } + break; + + case VIEW_TYPE_GRID: + { + int col = 0; + int row = 0; + int width = 2; + int height = 1; + + for ( unsigned int i = 0; i < items.size(); i++ ) { + + // If this is the last row, flag so the previews can draw a bottom + ::BorderStyle border = ((row == height -1) && (_border == BORDER_SOLID)) ? BORDER_SOLID_LAST_ROW : _border; + Gtk::Widget* thing = manage(items[i]->getPreview(PREVIEW_STYLE_PREVIEW, _view, _baseSize, _ratio, border)); + + if ( !_insides ) { + calcGridSize( thing, items.size(), width, height ); + +#if WITH_GTKMM_3_0 + _insides = manage(new Gtk::Grid()); + if (_border == BORDER_WIDE) { + _insides->set_column_spacing(1); + _insides->set_row_spacing(1); + } +#else + _insides = manage(new Gtk::Table( height, width )); + if (_border == BORDER_WIDE) { + _insides->set_col_spacings( 1 ); + _insides->set_row_spacings( 1 ); + } +#endif + } - _scroller->add( *_insides ); +#if WITH_GTKMM_3_0 + thing->set_hexpand(); + thing->set_vexpand(); + _insides->attach( *thing, col, row, 1, 1); +#else + _insides->attach( *thing, col, col+1, row, row+1, Gtk::FILL|Gtk::EXPAND, Gtk::FILL|Gtk::EXPAND ); +#endif + + if ( ++col >= width ) { + col = 0; + row++; + } + } + if ( !_insides ) { +#if WITH_GTKMM_3_0 + _insides = manage(new Gtk::Grid()); +#else + _insides = manage(new Gtk::Table( 1, 2 )); +#endif + } + + _scroller->add( *_insides ); + } } _scroller->show_all_children(); diff --git a/src/ui/previewholder.h b/src/ui/previewholder.h index 5a0dfc267..f9f923be4 100644 --- a/src/ui/previewholder.h +++ b/src/ui/previewholder.h @@ -12,10 +12,25 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif #include <gtkmm/box.h> #include <gtkmm/bin.h> -#include <gtkmm/table.h> + +namespace Gtk { +#if WITH_GTKMM_3_0 +class Grid; +#else +class Table; +#endif +} + #include "previewfillable.h" #include "../widgets/eek-preview.h" #include "enums.h" @@ -33,19 +48,21 @@ public: virtual void addPreview( Previewable* preview ); virtual void freezeUpdates(); virtual void thawUpdates(); - virtual void setStyle( ::PreviewSize size, ViewType view, guint ratio ); + virtual void setStyle( ::PreviewSize size, ViewType view, guint ratio, ::BorderStyle border ); virtual void setOrientation(SPAnchorType how); virtual int getColumnPref() const { return _prefCols; } virtual void setColumnPref( int cols ); virtual ::PreviewSize getPreviewSize() const { return _baseSize; } virtual ViewType getPreviewType() const { return _view; } virtual guint getPreviewRatio() const { return _ratio; } + virtual ::BorderStyle getPreviewBorder() const { return _border; } virtual void setWrap( bool b ); virtual bool getWrap() const { return _wrap; } protected: virtual void on_size_allocate( Gtk::Allocation& allocation ); - virtual void on_size_request( Gtk::Requisition* requisition ); + virtual bool on_scroll_event(GdkEventScroll*); +// virtual void on_size_request( Gtk::Requisition* requisition ); private: @@ -54,7 +71,13 @@ private: std::vector<Previewable*> items; Gtk::Bin *_scroller; + +#if WITH_GTKMM_3_0 + Gtk::Grid *_insides; +#else Gtk::Table *_insides; +#endif + int _prefCols; bool _updatesFrozen; SPAnchorType _anchor; @@ -62,6 +85,7 @@ private: guint _ratio; ViewType _view; bool _wrap; + ::BorderStyle _border; }; } //namespace UI diff --git a/src/ui/tool/Makefile_insert b/src/ui/tool/Makefile_insert index 2a72dd645..f46f48b72 100644 --- a/src/ui/tool/Makefile_insert +++ b/src/ui/tool/Makefile_insert @@ -19,8 +19,6 @@ ink_common_sources += \ ui/tool/node.cpp \ ui/tool/node.h \ ui/tool/node-types.h \ - ui/tool/node-tool.cpp \ - ui/tool/node-tool.h \ ui/tool/path-manipulator.cpp \ ui/tool/path-manipulator.h \ ui/tool/selectable-control-point.cpp \ diff --git a/src/ui/tool/control-point-selection.cpp b/src/ui/tool/control-point-selection.cpp index 1c66b91b6..d10ed0f0d 100644 --- a/src/ui/tool/control-point-selection.cpp +++ b/src/ui/tool/control-point-selection.cpp @@ -21,10 +21,6 @@ #include <gdk/gdkkeysyms.h> -#if !GTK_CHECK_VERSION(2,22,0) -#include "compat-key-syms.h" -#endif - namespace Inkscape { namespace UI { @@ -198,6 +194,8 @@ void ControlPointSelection::align(Geom::Dim2 axis) bound.unionWith(Geom::OptInterval((*i)->position()[d])); } + if (!bound) { return; } + double new_coord = bound->middle(); for (iterator i = _points.begin(); i != _points.end(); ++i) { Geom::Point pos = (*i)->position(); @@ -224,6 +222,8 @@ void ControlPointSelection::distribute(Geom::Dim2 d) bound.unionWith(Geom::OptInterval(pos[d])); } + if (!bound) { return; } + // now we iterate over the multimap and set aligned positions. double step = size() == 1 ? 0 : bound->extent() / (size() - 1); double start = bound->min(); @@ -268,7 +268,9 @@ void ControlPointSelection::toggleTransformHandlesMode() { if (_handles->mode() == TransformHandleSet::MODE_SCALE) { _handles->setMode(TransformHandleSet::MODE_ROTATE_SKEW); - if (size() == 1) _handles->rotationCenter().setVisible(false); + if (size() == 1) { + _handles->rotationCenter().setVisible(false); + } } else { _handles->setMode(TransformHandleSet::MODE_SCALE); } @@ -383,8 +385,9 @@ void ControlPointSelection::_pointChanged(SelectableControlPoint *p, bool select { _updateBounds(); _updateTransformHandles(false); - if (_bounds) + if (_bounds) { _handles->rotationCenter().move(_bounds->midpoint()); + } signal_point_changed.emit(p, selected); } @@ -583,7 +586,7 @@ void ControlPointSelection::_commitHandlesTransform(CommitEvent ce) signal_commit.emit(ce); } -bool ControlPointSelection::event(SPEventContext * /*event_context*/, GdkEvent *event) +bool ControlPointSelection::event(Inkscape::UI::Tools::ToolBase * /*event_context*/, GdkEvent *event) { // implement generic event handling that should apply for all control point selections here; // for example, keyboard moves and transformations. This way this functionality doesn't need diff --git a/src/ui/tool/control-point-selection.h b/src/ui/tool/control-point-selection.h index f5eb47026..a087e0455 100644 --- a/src/ui/tool/control-point-selection.h +++ b/src/ui/tool/control-point-selection.h @@ -90,7 +90,7 @@ public: void invertSelection(); void spatialGrow(SelectableControlPoint *origin, int dir); - virtual bool event(SPEventContext *, GdkEvent *); + virtual bool event(Inkscape::UI::Tools::ToolBase *, GdkEvent *); void transform(Geom::Affine const &m); void align(Geom::Dim2 d); diff --git a/src/ui/tool/control-point.cpp b/src/ui/tool/control-point.cpp index 68749cdff..e98c7b2a2 100644 --- a/src/ui/tool/control-point.cpp +++ b/src/ui/tool/control-point.cpp @@ -1,7 +1,3 @@ -/** - * @file - * Desktop-bound visual control object - implementation. - */ /* Authors: * Krzysztof Kosiński <tweenk.pl@gmail.com> * Jon A. Cruz <jon@joncruz.org> @@ -11,103 +7,46 @@ */ #include <iostream> +#include <gdk/gdkkeysyms.h> #include <gdkmm.h> -#include <gtkmm.h> #include <2geom/point.h> #include "desktop.h" #include "desktop-handles.h" #include "display/sp-canvas.h" #include "display/snap-indicator.h" -#include "event-context.h" +#include "ui/tools/tool-base.h" #include "message-context.h" #include "preferences.h" #include "snap-preferences.h" #include "sp-namedview.h" +#include "ui/control-manager.h" #include "ui/tool/control-point.h" #include "ui/tool/event-utils.h" #include "ui/tool/transform-handle-set.h" -#if !GTK_CHECK_VERSION(2,22,0) -#include "compat-key-syms.h" -#endif - namespace Inkscape { namespace UI { -// class and member documentation goes here... - -/** - * @class ControlPoint - * Draggable point, the workhorse of on-canvas editing. - * - * Control points (formerly known as knots) are graphical representations of some significant - * point in the drawing. The drawing can be changed by dragging the point and the things that are - * attached to it with the mouse. Example things that could be edited with draggable points - * are gradient stops, the place where text is attached to a path, text kerns, nodes and handles - * in a path, and many more. - * - * @par Control point event handlers - * @par - * The control point has several virtual methods which allow you to react to things that - * happen to it. The most important ones are the grabbed, dragged, ungrabbed and moved functions. - * When a drag happens, the order of calls is as follows: - * - <tt>grabbed()</tt> - * - <tt>dragged()</tt> - * - <tt>dragged()</tt> - * - <tt>dragged()</tt> - * - ... - * - <tt>dragged()</tt> - * - <tt>ungrabbed()</tt> - * - * The control point can also respond to clicks and double clicks. On a double click, - * clicked() is called, followed by doubleclicked(). When deriving from SelectableControlPoint, - * you need to manually call the superclass version at the appropriate point in your handler. - * - * @par Which method to override? - * @par - * You might wonder which hook to use when you want to do things when the point is relocated. - * Here are some tips: - * - If the point is used to edit an object, override the move() method. - * - If the point can usually be dragged wherever you like but can optionally be constrained - * to axes or the like, add a handler for <tt>signal_dragged</tt> that modifies its new - * position argument. - * - If the point has additional canvas items tied to it (like handle lines), override - * the setPosition() method. - */ - -/** - * @enum ControlPoint::State - * Enumeration representing the possible states of the control point, used to determine - * its appearance. - * @var ControlPoint::STATE_NORMAL - * Normal state - * @var ControlPoint::STATE_MOUSEOVER - * Mouse is hovering over the control point - * @var ControlPoint::STATE_CLICKED - * First mouse button pressed over the control point - */ // Default colors for control points -static ControlPoint::ColorSet default_color_set = { +ControlPoint::ColorSet ControlPoint::_default_color_set = { {0xffffff00, 0x01000000}, // normal fill, stroke {0xff0000ff, 0x01000000}, // mouseover fill, stroke - {0x0000ffff, 0x01000000} // clicked fill, stroke + {0x0000ffff, 0x01000000}, // clicked fill, stroke + // + {0x0000ffff, 0x000000ff}, // normal fill, stroke when selected + {0xff000000, 0x000000ff}, // mouseover fill, stroke when selected + {0xff000000, 0x000000ff} // clicked fill, stroke when selected }; -/** Holds the currently mouseovered control point. */ ControlPoint *ControlPoint::mouseovered_point = 0; -/** Emitted when the mouseovered point changes. The parameter is the new mouseovered point. - * When a point ceases to be mouseovered, the parameter will be NULL. */ sigc::signal<void, ControlPoint*> ControlPoint::signal_mouseover_change; -/** Stores the window point over which the cursor was during the last mouse button press */ Geom::Point ControlPoint::_drag_event_origin(Geom::infinity(), Geom::infinity()); -/** Stores the desktop point from which the last drag was initiated */ Geom::Point ControlPoint::_drag_origin(Geom::infinity(), Geom::infinity()); -/** Events which should be captured when a handle is being dragged. */ int const ControlPoint::_grab_event_mask = (GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK); @@ -115,69 +54,51 @@ int const ControlPoint::_grab_event_mask = (GDK_BUTTON_PRESS_MASK | GDK_BUTTON_R bool ControlPoint::_drag_initiated = false; bool ControlPoint::_event_grab = false; -/** A color set which you can use to create an invisible control that can still receive events. - * @relates ControlPoint */ -ControlPoint::ColorSet invisible_cset = { +ControlPoint::ColorSet ControlPoint::invisible_cset = { + {0x00000000, 0x00000000}, + {0x00000000, 0x00000000}, + {0x00000000, 0x00000000}, {0x00000000, 0x00000000}, {0x00000000, 0x00000000}, {0x00000000, 0x00000000} }; -/** - * Create a regular control point. - * Derive to have constructors with a reasonable number of parameters. - * - * @param d Desktop for this control - * @param initial_pos Initial position of the control point in desktop coordinates - * @param anchor Where is the control point rendered relative to its desktop coordinates - * @param shape Shape of the control point: square, diamond, circle... - * @param size Pixel size of the visual representation - * @param cset Colors of the point - * @param group The canvas group the point's canvas item should be created in - */ -ControlPoint::ControlPoint(SPDesktop *d, Geom::Point const &initial_pos, - SPAnchorType anchor, SPCtrlShapeType shape, - unsigned int size, ColorSet *cset, SPCanvasGroup *group) - : _desktop (d) - , _canvas_item (NULL) - , _cset (cset ? cset : &default_color_set) - , _state (STATE_NORMAL) - , _position (initial_pos) +ControlPoint::ControlPoint(SPDesktop *d, Geom::Point const &initial_pos, SPAnchorType anchor, + Glib::RefPtr<Gdk::Pixbuf> pixbuf, + ColorSet const &cset, SPCanvasGroup *group) : + _desktop(d), + _canvas_item(NULL), + _cset(cset), + _state(STATE_NORMAL), + _position(initial_pos), + _lurking(false) { _canvas_item = sp_canvas_item_new( - group ? group : sp_desktop_controls (_desktop), SP_TYPE_CTRL, - "anchor", (SPAnchorType) anchor, "size", (gdouble) size, "shape", shape, - "filled", TRUE, "fill_color", _cset->normal.fill, - "stroked", TRUE, "stroke_color", _cset->normal.stroke, + group ? group : sp_desktop_controls(_desktop), SP_TYPE_CTRL, + "anchor", (SPAnchorType) anchor, "size", (gdouble) pixbuf->get_width(), + "shape", SP_CTRL_SHAPE_BITMAP, "pixbuf", pixbuf->gobj(), + "filled", TRUE, "fill_color", _cset.normal.fill, + "stroked", TRUE, "stroke_color", _cset.normal.stroke, "mode", SP_CTRL_MODE_XOR, NULL); _commonInit(); } -/** - * Create a control point with a pixbuf-based visual representation. - * - * @param d Desktop for this control - * @param initial_pos Initial position of the control point in desktop coordinates - * @param anchor Where is the control point rendered relative to its desktop coordinates - * @param pixbuf Pixbuf to be used as the visual representation - * @param cset Colors of the point - * @param group The canvas group the point's canvas item should be created in - */ -ControlPoint::ControlPoint(SPDesktop *d, Geom::Point const &initial_pos, - SPAnchorType anchor, Glib::RefPtr<Gdk::Pixbuf> pixbuf, - ColorSet *cset, SPCanvasGroup *group) - : _desktop (d) - , _canvas_item (NULL) - , _cset(cset ? cset : &default_color_set) - , _position (initial_pos) +ControlPoint::ControlPoint(SPDesktop *d, Geom::Point const &initial_pos, SPAnchorType anchor, + ControlType type, + ColorSet const &cset, SPCanvasGroup *group) : + _desktop(d), + _canvas_item(NULL), + _cset(cset), + _state(STATE_NORMAL), + _position(initial_pos), + _lurking(false) { - _canvas_item = sp_canvas_item_new( - group ? group : sp_desktop_controls(_desktop), SP_TYPE_CTRL, - "anchor", (SPAnchorType) anchor, "size", (gdouble) pixbuf->get_width(), - "shape", SP_CTRL_SHAPE_BITMAP, "pixbuf", pixbuf->gobj(), - "filled", TRUE, "fill_color", _cset->normal.fill, - "stroked", TRUE, "stroke_color", _cset->normal.stroke, - "mode", SP_CTRL_MODE_XOR, NULL); + _canvas_item = ControlManager::getManager().createControl(group ? group : sp_desktop_controls(_desktop), type); + g_object_set(_canvas_item, + "anchor", anchor, + "filled", TRUE, "fill_color", _cset.normal.fill, + "stroked", TRUE, "stroke_color", _cset.normal.stroke, + "mode", SP_CTRL_MODE_XOR, NULL); _commonInit(); } @@ -190,7 +111,7 @@ ControlPoint::~ControlPoint() g_signal_handler_disconnect(G_OBJECT(_canvas_item), _event_handler_connection); //sp_canvas_item_hide(_canvas_item); - gtk_object_destroy(_canvas_item); + sp_canvas_item_destroy(_canvas_item); } void ControlPoint::_commonInit() @@ -200,29 +121,17 @@ void ControlPoint::_commonInit() G_CALLBACK(_event_handler), this); } -/** Relocate the control point without side effects. - * Overload this method only if there is an additional graphical representation - * that must be updated (like the lines that connect handles to nodes). If you override it, - * you must also call the superclass implementation of the method. - * @todo Investigate whether this method should be protected */ void ControlPoint::setPosition(Geom::Point const &pos) { _position = pos; SP_CTRL(_canvas_item)->moveto(pos); } -/** Move the control point to new position with side effects. - * This is called after each drag. Override this method if only some positions make sense - * for a control point (like a point that must always be on a path and can't modify it), - * or when moving a control point changes the positions of other points. */ void ControlPoint::move(Geom::Point const &pos) { setPosition(pos); } -/** Apply an arbitrary affine transformation to a control point. This is used - * by ControlPointSelection, and is important for things like nodes with handles. - * The default implementation simply moves the point according to the transform. */ void ControlPoint::transform(Geom::Affine const &m) { move(position() * m); } @@ -232,9 +141,6 @@ bool ControlPoint::visible() const return sp_canvas_item_is_visible(_canvas_item); } -/** Set the visibility of the control point. An invisible point is not drawn on the canvas - * and cannot receive any events. If you want to have an invisible point that can respond - * to events, use <tt>invisible_cset</tt> as its color set. */ void ControlPoint::setVisible(bool v) { if (v) sp_canvas_item_show(_canvas_item); @@ -287,9 +193,9 @@ void ControlPoint::_setSize(unsigned int size) g_object_set(_canvas_item, "size", (gdouble) size, NULL); } -void ControlPoint::_setShape(SPCtrlShapeType shape) +bool ControlPoint::_setControlType(Inkscape::ControlType type) { - g_object_set(_canvas_item, "shape", shape, NULL); + return ControlManager::getManager().setControlType(_canvas_item, type); } void ControlPoint::_setAnchor(SPAnchorType anchor) @@ -305,15 +211,36 @@ void ControlPoint::_setPixbuf(Glib::RefPtr<Gdk::Pixbuf> p) // re-routes events into the virtual function int ControlPoint::_event_handler(SPCanvasItem */*item*/, GdkEvent *event, ControlPoint *point) { + if ((point == NULL) || (point->_desktop == NULL)) { + return FALSE; + } return point->_eventHandler(point->_desktop->event_context, event) ? TRUE : FALSE; } // main event callback, which emits all other callbacks. -bool ControlPoint::_eventHandler(SPEventContext *event_context, GdkEvent *event) +bool ControlPoint::_eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event) { // NOTE the static variables below are shared for all points! // TODO handle clicks and drags from other buttons too + if (event == NULL) + { + return false; + } + + if (event_context == NULL) + { + return false; + } + if (_desktop == NULL) + { + return false; + } + if(event_context->desktop !=_desktop) + { + g_warning ("ControlPoint: desktop pointers not equal!"); + //return false; + } // offset from the pointer hotspot to the center of the grabbed knot in desktop coords static Geom::Point pointer_offset; // number of last doubleclicked button @@ -321,7 +248,8 @@ bool ControlPoint::_eventHandler(SPEventContext *event_context, GdkEvent *event) Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int drag_tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); - + GdkEventMotion em; + SPCanvas* Ca; switch(event->type) { case GDK_BUTTON_PRESS: @@ -347,18 +275,22 @@ bool ControlPoint::_eventHandler(SPEventContext *event_context, GdkEvent *event) return true; case GDK_MOTION_NOTIFY: - combine_motion_events(_desktop->canvas, event->motion, 0); - if (_event_grab && !_desktop->event_context->space_panning) { + Ca = _desktop->canvas; + em = event->motion; + combine_motion_events(Ca, em, 0); + if (_event_grab && ! event_context->space_panning) { _desktop->snapindicator->remove_snaptarget(); bool transferred = false; if (!_drag_initiated) { - bool t = fabs(event->motion.x - _drag_event_origin[Geom::X]) <= drag_tolerance && - fabs(event->motion.y - _drag_event_origin[Geom::Y]) <= drag_tolerance; - if (t) return true; + bool t = fabs(em.x - _drag_event_origin[Geom::X]) <= drag_tolerance && + fabs(em.y - _drag_event_origin[Geom::Y]) <= drag_tolerance; + if (t){ + return true; + } // if we are here, it means the tolerance was just exceeded. _drag_origin = _position; - transferred = grabbed(&event->motion); + transferred = grabbed(&em); // _drag_initiated might change during the above virtual call if (!_drag_initiated) { // this guarantees smooth redraws while dragging @@ -369,17 +301,16 @@ bool ControlPoint::_eventHandler(SPEventContext *event_context, GdkEvent *event) if (!transferred) { // dragging in progress Geom::Point new_pos = _desktop->w2d(event_point(event->motion)) + pointer_offset; - // the new position is passed by reference and can be changed in the handlers. - dragged(new_pos, &event->motion); + dragged(new_pos, &em); move(new_pos); - _updateDragTip(&event->motion); // update dragging tip after moving to new position + _updateDragTip(&em); // update dragging tip after moving to new position _desktop->scroll_to_point(new_pos); _desktop->set_coordinate_status(_position); - sp_event_context_snap_delay_handler(_desktop->event_context, NULL, + sp_event_context_snap_delay_handler(event_context, NULL, (gpointer) this, &event->motion, - DelayedSnapEvent::CONTROL_POINT_HANDLER); + Inkscape::UI::Tools::DelayedSnapEvent::CONTROL_POINT_HANDLER); } return true; } @@ -393,8 +324,9 @@ bool ControlPoint::_eventHandler(SPEventContext *event_context, GdkEvent *event) // We must snap at some point in time though, and this is our last chance) // PS: For other contexts this is handled already in sp_event_context_item_handler or // sp_event_context_root_handler - if (_desktop->event_context->_delayed_snap_event) { - sp_event_context_snap_watchdog_callback(_desktop->event_context->_delayed_snap_event); + //if (_desktop && _desktop->event_context && _desktop->event_context->_delayed_snap_event) { + if (event_context->_delayed_snap_event) { + sp_event_context_snap_watchdog_callback(event_context->_delayed_snap_event); } sp_canvas_item_ungrab(_canvas_item, event->button.time); @@ -429,8 +361,9 @@ bool ControlPoint::_eventHandler(SPEventContext *event_context, GdkEvent *event) if (_event_grab && !event->grab_broken.keyboard) { { ungrabbed(NULL); - if (_drag_initiated) + if (_drag_initiated) { _desktop->canvas->endForcedFullRedraws(); + } } _setState(STATE_NORMAL); _event_grab = false; @@ -442,14 +375,14 @@ bool ControlPoint::_eventHandler(SPEventContext *event_context, GdkEvent *event) // update tips on modifier state change // TODO add ESC keybinding as drag cancel case GDK_KEY_PRESS: - switch (get_group0_keyval(&event->key)) + switch (Inkscape::UI::Tools::get_group0_keyval(&event->key)) { case GDK_KEY_Escape: { // ignore Escape if this is not a drag if (!_drag_initiated) break; // temporarily disable snapping - we might snap to a different place than we were initially - sp_event_context_discard_delayed_snap_event(_desktop->event_context); + sp_event_context_discard_delayed_snap_event(event_context); SnapPreferences &snapprefs = _desktop->namedview->snap_manager.snapprefs; bool snap_save = snapprefs.getSnapEnabledGlobally(); snapprefs.setSnapEnabledGlobally(false); @@ -483,7 +416,8 @@ bool ControlPoint::_eventHandler(SPEventContext *event_context, GdkEvent *event) ungrabbed(NULL); // ungrabbed handlers can handle a NULL event snapprefs.setSnapEnabledGlobally(snap_save); - } return true; + } + return true; case GDK_KEY_Tab: {// Downcast from ControlPoint to TransformHandle, if possible // This is an ugly hack; we should have the transform handle intercept the keystrokes itself @@ -509,7 +443,9 @@ bool ControlPoint::_eventHandler(SPEventContext *event_context, GdkEvent *event) } // Do not break here, to allow for updating tooltips and such case GDK_KEY_RELEASE: - if (mouseovered_point != this) return false; + if (mouseovered_point != this){ + return false; + } if (_drag_initiated) { return true; // this prevents the tool from overwriting the drag tip } else { @@ -559,7 +495,9 @@ bool ControlPoint::_updateTip(unsigned state) bool ControlPoint::_updateDragTip(GdkEventMotion *event) { - if (!_hasDragTips()) return false; + if (!_hasDragTips()) { + return false; + } Glib::ustring tip = _getDragTip(event); if (!tip.empty()) { _desktop->event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, @@ -581,16 +519,6 @@ void ControlPoint::_clearMouseover() } } -/** Transfer the grab to another point. This method allows one to create a draggable point - * that should be dragged instead of the one that received the grabbed signal. - * This is used to implement dragging out handles in the new node tool, for example. - * - * This method will NOT emit the ungrab signal of @c prev_point, because this would complicate - * using it with selectable control points. If you use this method while dragging, you must emit - * the ungrab signal yourself. - * - * Note that this will break horribly if you try to transfer grab between points in different - * desktops, which doesn't make much sense anyway. */ void ControlPoint::transferGrab(ControlPoint *prev_point, GdkEventMotion *event) { if (!_event_grab) return; @@ -608,42 +536,80 @@ void ControlPoint::transferGrab(ControlPoint *prev_point, GdkEventMotion *event) _setMouseover(this, event->state); } -/** - * Change the state of the knot. - * Alters the appearance of the knot to match one of the states: normal, mouseover - * or clicked. - */ void ControlPoint::_setState(State state) { ColorEntry current = {0, 0}; + ColorSet const &activeCset = (_isLurking()) ? invisible_cset : _cset; switch(state) { - case STATE_NORMAL: - current = _cset->normal; break; - case STATE_MOUSEOVER: - current = _cset->mouseover; break; - case STATE_CLICKED: - current = _cset->clicked; break; + case STATE_NORMAL: + current = activeCset.normal; + break; + case STATE_MOUSEOVER: + current = activeCset.mouseover; + break; + case STATE_CLICKED: + current = activeCset.clicked; + break; }; _setColors(current); _state = state; } + +void ControlPoint::_handleControlStyling() +{ + if (_canvas_item->ctrlType != CTRL_TYPE_UNKNOWN) { + ControlManager::getManager().updateItem(_canvas_item); + } +} + void ControlPoint::_setColors(ColorEntry colors) { g_object_set(_canvas_item, "fill_color", colors.fill, "stroke_color", colors.stroke, NULL); } +bool ControlPoint::_isLurking() +{ + return _lurking; +} + +void ControlPoint::_setLurking(bool lurking) +{ + if (lurking != _lurking) { + _lurking = lurking; + _setState(_state); // TODO refactor out common part + } +} + + bool ControlPoint::_is_drag_cancelled(GdkEventMotion *event) { return !event || event->x_root == -1; } // dummy implementations for handlers -// they are here to avoid unused param warnings -bool ControlPoint::grabbed(GdkEventMotion *) { return false; } -void ControlPoint::dragged(Geom::Point &, GdkEventMotion *) {} -void ControlPoint::ungrabbed(GdkEventButton *) {} -bool ControlPoint::clicked(GdkEventButton *) { return false; } -bool ControlPoint::doubleclicked(GdkEventButton *) { return false; } + +bool ControlPoint::grabbed(GdkEventMotion * /*event*/) +{ + return false; +} + +void ControlPoint::dragged(Geom::Point &/*new_pos*/, GdkEventMotion * /*event*/) +{ +} + +void ControlPoint::ungrabbed(GdkEventButton * /*event*/) +{ +} + +bool ControlPoint::clicked(GdkEventButton * /*event*/) +{ + return false; +} + +bool ControlPoint::doubleclicked(GdkEventButton * /*event*/) +{ + return false; +} } // namespace UI } // namespace Inkscape diff --git a/src/ui/tool/control-point.h b/src/ui/tool/control-point.h index 8d1b778a7..b3ed9545e 100644 --- a/src/ui/tool/control-point.h +++ b/src/ui/tool/control-point.h @@ -1,9 +1,8 @@ -/** @file - * Desktop-bound visual control object - */ /* Authors: * Krzysztof Kosiński <tweenk.pl@gmail.com> + * Jon A. Cruz <jon@joncruz.org> * + * Copyright (C) 2012 Authors * Copyright (C) 2009 Authors * Released under GNU GPL, read the file 'COPYING' for more information */ @@ -17,59 +16,149 @@ #include <sigc++/signal.h> #include <sigc++/trackable.h> #include <2geom/point.h> + +#include "ui/control-types.h" #include "util/accumulators.h" #include "display/sodipodi-ctrl.h" #include "enums.h" class SPDesktop; -class SPEventContext; namespace Inkscape { namespace UI { +namespace Tools { + +class ToolBase; + +} +} +} -// most of the documentation is in the .cpp file +namespace Inkscape { +namespace UI { +/** + * Draggable point, the workhorse of on-canvas editing. + * + * Control points (formerly known as knots) are graphical representations of some significant + * point in the drawing. The drawing can be changed by dragging the point and the things that are + * attached to it with the mouse. Example things that could be edited with draggable points + * are gradient stops, the place where text is attached to a path, text kerns, nodes and handles + * in a path, and many more. + * + * @par Control point event handlers + * @par + * The control point has several virtual methods which allow you to react to things that + * happen to it. The most important ones are the grabbed, dragged, ungrabbed and moved functions. + * When a drag happens, the order of calls is as follows: + * - <tt>grabbed()</tt> + * - <tt>dragged()</tt> + * - <tt>dragged()</tt> + * - <tt>dragged()</tt> + * - ... + * - <tt>dragged()</tt> + * - <tt>ungrabbed()</tt> + * + * The control point can also respond to clicks and double clicks. On a double click, + * clicked() is called, followed by doubleclicked(). When deriving from SelectableControlPoint, + * you need to manually call the superclass version at the appropriate point in your handler. + * + * @par Which method to override? + * @par + * You might wonder which hook to use when you want to do things when the point is relocated. + * Here are some tips: + * - If the point is used to edit an object, override the move() method. + * - If the point can usually be dragged wherever you like but can optionally be constrained + * to axes or the like, add a handler for <tt>signal_dragged</tt> that modifies its new + * position argument. + * - If the point has additional canvas items tied to it (like handle lines), override + * the setPosition() method. + */ class ControlPoint : boost::noncopyable, public sigc::trackable { public: typedef Inkscape::Util::ReverseInterruptible RInt; typedef Inkscape::Util::Interruptible Int; - // these have to be public, because GCC doesn't allow protected types in constructors, - // even if the constructors are protected themselves. - struct ColorEntry { - guint32 fill; - guint32 stroke; - }; - struct ColorSet { - ColorEntry normal; - ColorEntry mouseover; - ColorEntry clicked; - }; + + /** + * Enumeration representing the possible states of the control point, used to determine + * its appearance. + * + * @todo resolve this to be in sync with the five standard GTK states. + */ enum State { + /** Normal state. */ STATE_NORMAL, + + /** Mouse is hovering over the control point. */ STATE_MOUSEOVER, + + /** First mouse button pressed over the control point. */ STATE_CLICKED }; + /** + * Destructor + */ virtual ~ControlPoint(); /// @name Adjust the position of the control point /// @{ /** Current position of the control point. */ Geom::Point const &position() const { return _position; } + operator Geom::Point const &() { return _position; } + + /** + * Move the control point to new position with side effects. + * This is called after each drag. Override this method if only some positions make sense + * for a control point (like a point that must always be on a path and can't modify it), + * or when moving a control point changes the positions of other points. + */ virtual void move(Geom::Point const &pos); + + /** + * Relocate the control point without side effects. + * Overload this method only if there is an additional graphical representation + * that must be updated (like the lines that connect handles to nodes). If you override it, + * you must also call the superclass implementation of the method. + * @todo Investigate whether this method should be protected + */ virtual void setPosition(Geom::Point const &pos); + + /** + * Apply an arbitrary affine transformation to a control point. This is used + * by ControlPointSelection, and is important for things like nodes with handles. + * The default implementation simply moves the point according to the transform. + */ virtual void transform(Geom::Affine const &m); /// @} /// @name Toggle the point's visibility /// @{ bool visible() const; + + /** + * Set the visibility of the control point. An invisible point is not drawn on the canvas + * and cannot receive any events. If you want to have an invisible point that can respond + * to events, use <tt>invisible_cset</tt> as its color set. + */ virtual void setVisible(bool v); /// @} /// @name Transfer grab from another event handler /// @{ + /** + * Transfer the grab to another point. This method allows one to create a draggable point + * that should be dragged instead of the one that received the grabbed signal. + * This is used to implement dragging out handles in the new node tool, for example. + * + * This method will NOT emit the ungrab signal of @c prev_point, because this would complicate + * using it with selectable control points. If you use this method while dragging, you must emit + * the ungrab signal yourself. + * + * Note that this will break horribly if you try to transfer grab between points in different + * desktops, which doesn't make much sense anyway. + */ void transferGrab(ControlPoint *from, GdkEventMotion *event); /// @} @@ -84,109 +173,233 @@ public: /// @name Inspect the state of the control point /// @{ - State state() { return _state; } - bool mouseovered() { return this == mouseovered_point; } + State state() const { return _state; } + + bool mouseovered() const { return this == mouseovered_point; } /// @} + /** Holds the currently mouseovered control point. */ static ControlPoint *mouseovered_point; + + /** + * Emitted when the mouseovered point changes. The parameter is the new mouseovered point. + * When a point ceases to be mouseovered, the parameter will be NULL. + */ static sigc::signal<void, ControlPoint*> signal_mouseover_change; + static Glib::ustring format_tip(char const *format, ...) G_GNUC_PRINTF(1,2); // temporarily public, until snap delay is refactored a little - virtual bool _eventHandler(SPEventContext *event_context, GdkEvent *event); + virtual bool _eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event); + SPDesktop *const _desktop; ///< The desktop this control point resides on. protected: + + struct ColorEntry { + guint32 fill; + guint32 stroke; + }; + + /** + * Color entries for each possible state. + * @todo resolve this to be in sync with the five standard GTK states. + */ + struct ColorSet { + ColorEntry normal; + ColorEntry mouseover; + ColorEntry clicked; + ColorEntry selected_normal; + ColorEntry selected_mouseover; + ColorEntry selected_clicked; + }; + + /** + * A color set which you can use to create an invisible control that can still receive events. + */ + static ColorSet invisible_cset; + + /** + * Create a regular control point. + * Derive to have constructors with a reasonable number of parameters. + * + * @param d Desktop for this control + * @param initial_pos Initial position of the control point in desktop coordinates + * @param anchor Where is the control point rendered relative to its desktop coordinates + * @param type Logical type of the control point. + * @param cset Colors of the point + * @param group The canvas group the point's canvas item should be created in + */ ControlPoint(SPDesktop *d, Geom::Point const &initial_pos, SPAnchorType anchor, - SPCtrlShapeType shape, unsigned int size, ColorSet *cset = 0, SPCanvasGroup *group = 0); + ControlType type, + ColorSet const &cset = _default_color_set, SPCanvasGroup *group = 0); + + /** + * Create a control point with a pixbuf-based visual representation. + * + * @param d Desktop for this control + * @param initial_pos Initial position of the control point in desktop coordinates + * @param anchor Where is the control point rendered relative to its desktop coordinates + * @param pixbuf Pixbuf to be used as the visual representation + * @param cset Colors of the point + * @param group The canvas group the point's canvas item should be created in + */ ControlPoint(SPDesktop *d, Geom::Point const &initial_pos, SPAnchorType anchor, - Glib::RefPtr<Gdk::Pixbuf> pixbuf, ColorSet *cset = 0, SPCanvasGroup *group = 0); + Glib::RefPtr<Gdk::Pixbuf> pixbuf, + ColorSet const &cset = _default_color_set, SPCanvasGroup *group = 0); /// @name Handle control point events in subclasses /// @{ /** * Called when the user moves the point beyond the drag tolerance with the first button held - * down. Return true if you called transferGrab() during this method. - * @param event Motion event when drag tolerance was exceeded */ + * down. + * + * @param event Motion event when drag tolerance was exceeded. + * @return true if you called transferGrab() during this method. + */ virtual bool grabbed(GdkEventMotion *event); + /** * Called while dragging, but before moving the knot to new position. + * * @param pos Old position, always equal to position() * @param new_pos New position (after drag). This is passed as a non-const reference, * so you can change it from the handler - that's how constrained dragging is implemented. - * @param event Motion event */ + * @param event Motion event. + */ virtual void dragged(Geom::Point &new_pos, GdkEventMotion *event); + /** - * @var ControlPoint::signal_ungrabbed - * Emitted when the control point finishes a drag. + * Called when the control point finishes a drag. + * * @param event Button release event */ virtual void ungrabbed(GdkEventButton *event); + /** - * Called when the control point is clicked, at mouse button release. Your override should - * return true if the click had some effect. If it did nothing, return false. Improperly - * implementing this method can cause the default context menu not to appear when a control + * Called when the control point is clicked, at mouse button release. + * Improperly implementing this method can cause the default context menu not to appear when a control * point is right-clicked. - * @param event Button release event */ + * + * @param event Button release event + * @return true if the click had some effect, false if it did nothing. + */ virtual bool clicked(GdkEventButton *event); + /** * Called when the control point is doubleclicked, at mouse button release. - * @param event Button release event */ - virtual bool doubleclicked(GdkEventButton *); + * + * @param event Button release event + */ + virtual bool doubleclicked(GdkEventButton *event); /// @} /// @name Manipulate the control point's appearance in subclasses /// @{ + + /** + * Change the state of the knot. + * Alters the appearance of the knot to match one of the states: normal, mouseover + * or clicked. + */ virtual void _setState(State state); + + void _handleControlStyling(); + void _setColors(ColorEntry c); unsigned int _size() const; + SPCtrlShapeType _shape() const; + SPAnchorType _anchor() const; + Glib::RefPtr<Gdk::Pixbuf> _pixbuf(); void _setSize(unsigned int size); - void _setShape(SPCtrlShapeType shape); + + bool _setControlType(Inkscape::ControlType type); + void _setAnchor(SPAnchorType anchor); + void _setPixbuf(Glib::RefPtr<Gdk::Pixbuf>); + + /** + * Determins if the control point is not visible yet still reacting to events. + * + * @return true if non-visible, false otherwise. + */ + bool _isLurking(); + + /** + * Sets the control point to be non-visible yet still reacting to events. + * + * @param lurking true to make non-visible, false otherwise. + */ + void _setLurking(bool lurking); + /// @} - virtual Glib::ustring _getTip(unsigned /*state*/) { return ""; } - virtual Glib::ustring _getDragTip(GdkEventMotion */*event*/) { return ""; } - virtual bool _hasDragTips() { return false; } + virtual Glib::ustring _getTip(unsigned /*state*/) const { return ""; } + + virtual Glib::ustring _getDragTip(GdkEventMotion */*event*/) const { return ""; } + + virtual bool _hasDragTips() const { return false; } + - SPDesktop *const _desktop; ///< The desktop this control point resides on. SPCanvasItem * _canvas_item; ///< Visual representation of the control point. - ColorSet *_cset; ///< Colors used to represent the point + + ColorSet const &_cset; ///< Colors used to represent the point + State _state; static Geom::Point const &_last_click_event_point() { return _drag_event_origin; } + static Geom::Point const &_last_drag_origin() { return _drag_origin; } + static bool _is_drag_cancelled(GdkEventMotion *event); + + /** Events which should be captured when a handle is being dragged. */ static int const _grab_event_mask; private: + ControlPoint(ControlPoint const &other); + void operator=(ControlPoint const &other); static int _event_handler(SPCanvasItem *item, GdkEvent *event, ControlPoint *point); + static void _setMouseover(ControlPoint *, unsigned state); + static void _clearMouseover(); + bool _updateTip(unsigned state); + bool _updateDragTip(GdkEventMotion *event); + void _setDefaultColors(); + void _commonInit(); Geom::Point _position; ///< Current position in desktop coordinates + gulong _event_handler_connection; + bool _lurking; + + static ColorSet _default_color_set; + + /** Stores the window point over which the cursor was during the last mouse button press. */ static Geom::Point _drag_event_origin; + + /** Stores the desktop point from which the last drag was initiated. */ static Geom::Point _drag_origin; + static bool _event_grab; + static bool _drag_initiated; }; -extern ControlPoint::ColorSet invisible_cset; - } // namespace UI } // namespace Inkscape diff --git a/src/ui/tool/curve-drag-point.cpp b/src/ui/tool/curve-drag-point.cpp index 8754681df..4ca736f80 100644 --- a/src/ui/tool/curve-drag-point.cpp +++ b/src/ui/tool/curve-drag-point.cpp @@ -1,8 +1,6 @@ -/** @file - * Control point that is dragged during path drag - */ /* Authors: * Krzysztof Kosiński <tweenk.pl@gmail.com> + * Jon A. Cruz <jon@joncruz.org> * * Copyright (C) 2009 Authors * Released under GNU GPL, read the file 'COPYING' for more information @@ -21,31 +19,20 @@ namespace Inkscape { namespace UI { -/** - * @class CurveDragPoint - * An invisible point used to drag curves. This point is used by PathManipulator to allow editing - * of path segments by dragging them. It is defined in a separate file so that the node tool - * can check if the mouseovered control point is a curve drag point and update the cursor - * accordingly, without the need to drag in the full PathManipulator header. - */ - -// This point should be invisible to the user - use the invisible_cset from control-point.h -// TODO make some methods from path-manipulator.cpp public so that this point doesn't have -// to be declared as a friend bool CurveDragPoint::_drags_stroke = false; bool CurveDragPoint::_segment_was_degenerate = false; -CurveDragPoint::CurveDragPoint(PathManipulator &pm) - : ControlPoint(pm._multi_path_manipulator._path_data.node_data.desktop, Geom::Point(), - SP_ANCHOR_CENTER, SP_CTRL_SHAPE_CIRCLE, 1.0, &invisible_cset, - pm._multi_path_manipulator._path_data.dragpoint_group) - , _pm(pm) +CurveDragPoint::CurveDragPoint(PathManipulator &pm) : + ControlPoint(pm._multi_path_manipulator._path_data.node_data.desktop, Geom::Point(), SP_ANCHOR_CENTER, + CTRL_TYPE_INVISIPOINT, + invisible_cset, pm._multi_path_manipulator._path_data.dragpoint_group), + _pm(pm) { setVisible(false); } -bool CurveDragPoint::_eventHandler(SPEventContext *event_context, GdkEvent *event) +bool CurveDragPoint::_eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event) { // do not process any events when the manipulator is empty if (_pm.empty()) { @@ -170,7 +157,7 @@ void CurveDragPoint::_insertNode(bool take_selection) _pm._commit(_("Add node")); } -Glib::ustring CurveDragPoint::_getTip(unsigned state) +Glib::ustring CurveDragPoint::_getTip(unsigned state) const { if (_pm.empty()) return ""; if (!first || !first.next()) return ""; diff --git a/src/ui/tool/curve-drag-point.h b/src/ui/tool/curve-drag-point.h index 939047634..ea83978e0 100644 --- a/src/ui/tool/curve-drag-point.h +++ b/src/ui/tool/curve-drag-point.h @@ -1,8 +1,6 @@ -/** @file - * Control point that is dragged during path drag - */ /* Authors: * Krzysztof Kosiński <tweenk.pl@gmail.com> + * Jon A. Cruz <jon@joncruz.org> * * Copyright (C) 2009 Authors * Released under GNU GPL, read the file 'COPYING' for more information @@ -21,15 +19,27 @@ namespace UI { class PathManipulator; struct PathSharedData; +// This point should be invisible to the user - use the invisible_cset from control-point.h +// TODO make some methods from path-manipulator.cpp public so that this point doesn't have +// to be declared as a friend +/** + * An invisible point used to drag curves. This point is used by PathManipulator to allow editing + * of path segments by dragging them. It is defined in a separate file so that the node tool + * can check if the mouseovered control point is a curve drag point and update the cursor + * accordingly, without the need to drag in the full PathManipulator header. + */ class CurveDragPoint : public ControlPoint { public: + CurveDragPoint(PathManipulator &pm); void setSize(double sz) { _setSize(sz); } void setTimeValue(double t) { _t = t; } void setIterator(NodeList::iterator i) { first = i; } - virtual bool _eventHandler(SPEventContext *event_context, GdkEvent *event); + virtual bool _eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event); + protected: - virtual Glib::ustring _getTip(unsigned state); + + virtual Glib::ustring _getTip(unsigned state) const; virtual void dragged(Geom::Point &, GdkEventMotion *); virtual bool grabbed(GdkEventMotion *); virtual void ungrabbed(GdkEventButton *); @@ -37,10 +47,13 @@ protected: virtual bool doubleclicked(GdkEventButton *); private: + void _insertNode(bool take_selection); + double _t; PathManipulator &_pm; NodeList::iterator first; + static bool _drags_stroke; static bool _segment_was_degenerate; static Geom::Point _stroke_drag_origin; diff --git a/src/ui/tool/event-utils.cpp b/src/ui/tool/event-utils.cpp index 6b067a3ce..079275d63 100644 --- a/src/ui/tool/event-utils.cpp +++ b/src/ui/tool/event-utils.cpp @@ -14,10 +14,6 @@ #include "display/sp-canvas.h" #include "ui/tool/event-utils.h" -#if !GTK_CHECK_VERSION(2,22,0) -#include "compat-key-syms.h" -#endif - namespace Inkscape { namespace UI { @@ -59,6 +55,9 @@ unsigned combine_key_events(guint keyval, gint mask) unsigned combine_motion_events(SPCanvas *canvas, GdkEventMotion &event, gint mask) { + if (canvas == NULL) { + return false; + } GdkEvent *event_next; gint i = 0; event.x -= canvas->x0; @@ -66,7 +65,7 @@ unsigned combine_motion_events(SPCanvas *canvas, GdkEventMotion &event, gint mas event_next = gdk_event_get(); // while the next event is also a motion notify - while (event_next && event_next->type == GDK_MOTION_NOTIFY + while (event_next && (event_next->type == GDK_MOTION_NOTIFY) && (!mask || event_next->motion.state & mask)) { if (event_next->motion.device == event.device) { @@ -80,11 +79,7 @@ unsigned combine_motion_events(SPCanvas *canvas, GdkEventMotion &event, gint mas event.x_root = next.x_root; event.y_root = next.y_root; if (event.axes && next.axes) { -#if GTK_CHECK_VERSION(2,22,0) memcpy(event.axes, next.axes, gdk_device_get_n_axes(event.device)); -#else - memcpy(event.axes, next.axes, event.device->num_axes); -#endif } } @@ -94,8 +89,9 @@ unsigned combine_motion_events(SPCanvas *canvas, GdkEventMotion &event, gint mas i++; } // otherwise, put it back onto the queue - if (event_next) + if (event_next) { gdk_event_put(event_next); + } event.x += canvas->x0; event.y += canvas->y0; diff --git a/src/ui/tool/manipulator.h b/src/ui/tool/manipulator.h index ffed370d3..07e01a656 100644 --- a/src/ui/tool/manipulator.h +++ b/src/ui/tool/manipulator.h @@ -18,7 +18,7 @@ #include <glib.h> #include <gdk/gdk.h> #include <boost/shared_ptr.hpp> -#include "event-context.h" +#include "ui/tools/tool-base.h" class SPDesktop; namespace Inkscape { @@ -40,7 +40,7 @@ public: virtual ~Manipulator() {} /// Handle input event. Returns true if handled. - virtual bool event(SPEventContext *, GdkEvent *)=0; + virtual bool event(Inkscape::UI::Tools::ToolBase *, GdkEvent *)=0; SPDesktop *const _desktop; }; @@ -145,7 +145,7 @@ public: } } - virtual bool event(SPEventContext *event_context, GdkEvent *event) { + virtual bool event(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event) { for (typename MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) { if ((*i).second->event(event_context, event)) return true; } diff --git a/src/ui/tool/modifier-tracker.cpp b/src/ui/tool/modifier-tracker.cpp index 601c8334f..cc4e4d0b2 100644 --- a/src/ui/tool/modifier-tracker.cpp +++ b/src/ui/tool/modifier-tracker.cpp @@ -14,10 +14,6 @@ #include "ui/tool/modifier-tracker.h" #include <gtk/gtk.h> -#if !GTK_CHECK_VERSION(2,22,0) -#include "compat-key-syms.h" -#endif - namespace Inkscape { namespace UI { diff --git a/src/ui/tool/multi-path-manipulator.cpp b/src/ui/tool/multi-path-manipulator.cpp index 3fc202b69..65987ad52 100644 --- a/src/ui/tool/multi-path-manipulator.cpp +++ b/src/ui/tool/multi-path-manipulator.cpp @@ -11,9 +11,8 @@ */ #include <boost/shared_ptr.hpp> -#include <glib.h> -#include <glibmm/i18n.h> #include "node.h" +#include <glibmm/i18n.h> #include "desktop.h" #include "desktop-handles.h" #include "document.h" @@ -31,21 +30,6 @@ #include <gdk/gdkkeysyms.h> -#if !GTK_CHECK_VERSION(2,22,0) -#include "compat-key-syms.h" -#endif - -#ifdef USE_GNU_HASHES -namespace __gnu_cxx { -template<> -struct hash<Inkscape::UI::NodeList::iterator> { - size_t operator()(Inkscape::UI::NodeList::iterator const &n) const { - return reinterpret_cast<size_t>(n.ptr()); - } -}; -} // namespace __gnu_cxx -#endif // USE_GNU_HASHES - namespace Inkscape { namespace UI { @@ -69,7 +53,6 @@ typedef std::pair<double, IterPair> DistanceMapItem; void find_join_iterators(ControlPointSelection &sel, IterPairList &pairs) { IterSet join_iters; - DistanceMap dists; // find all endnodes in selection for (ControlPointSelection::iterator i = sel.begin(); i != sel.end(); ++i) { @@ -230,10 +213,12 @@ void MultiPathManipulator::shiftSelection(int dir) SubpathList::iterator last_j; NodeList::iterator last_k; bool anything_found = false; + bool anynode_found = false; for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) { SubpathList &sp = i->second->subpathList(); for (SubpathList::iterator j = sp.begin(); j != sp.end(); ++j) { + anynode_found = true; for (NodeList::iterator k = (*j)->begin(); k != (*j)->end(); ++k) { if (k->selected()) { last_i = i; @@ -255,10 +240,12 @@ void MultiPathManipulator::shiftSelection(int dir) if (!anything_found) { // select first / last node // this should never fail because there must be at least 1 non-empty manipulator - if (dir == 1) { + if (anynode_found) { + if (dir == 1) { _selection.insert((*_mmap.begin()->second->subpathList().begin())->begin().ptr()); - } else { + } else { _selection.insert((--(*--(--_mmap.end())->second->subpathList().end())->end()).ptr()); + } } return; } @@ -341,23 +328,27 @@ void MultiPathManipulator::setSegmentType(SegmentType type) void MultiPathManipulator::insertNodes() { + if (_selection.empty()) return; invokeForAll(&PathManipulator::insertNodes); _done(_("Add nodes")); } void MultiPathManipulator::insertNodesAtExtrema(ExtremumType extremum) { + if (_selection.empty()) return; invokeForAll(&PathManipulator::insertNodeAtExtremum, extremum); _done(_("Add extremum nodes")); } void MultiPathManipulator::duplicateNodes() { + if (_selection.empty()) return; invokeForAll(&PathManipulator::duplicateNodes); _done(_("Duplicate nodes")); } void MultiPathManipulator::joinNodes() { + if (_selection.empty()) return; invokeForAll(&PathManipulator::hideDragPoint); // Node join has two parts. In the first one we join two subpaths by fusing endpoints // into one. In the second we fuse nodes in each subpath. @@ -435,6 +426,7 @@ void MultiPathManipulator::deleteNodes(bool keep_shape) /** Join selected endpoints to create segments. */ void MultiPathManipulator::joinSegments() { + if (_selection.empty()) return; IterPairList joins; find_join_iterators(_selection, joins); @@ -467,6 +459,7 @@ void MultiPathManipulator::deleteSegments() void MultiPathManipulator::alignNodes(Geom::Dim2 d) { + if (_selection.empty()) return; _selection.align(d); if (d == Geom::X) { _done("Align nodes to a horizontal line"); @@ -477,6 +470,7 @@ void MultiPathManipulator::alignNodes(Geom::Dim2 d) void MultiPathManipulator::distributeNodes(Geom::Dim2 d) { + if (_selection.empty()) return; _selection.distribute(d); if (d == Geom::X) { _done("Distrubute nodes horizontally"); @@ -498,6 +492,7 @@ void MultiPathManipulator::reverseSubpaths() void MultiPathManipulator::move(Geom::Point const &delta) { + if (_selection.empty()) return; _selection.transform(Geom::Translate(delta)); _done("Move nodes"); } @@ -554,7 +549,12 @@ void MultiPathManipulator::updateOutlineColors() //} } -bool MultiPathManipulator::event(SPEventContext *event_context, GdkEvent *event) +void MultiPathManipulator::updateHandles() +{ + invokeForAll(&PathManipulator::updateHandles); +} + +bool MultiPathManipulator::event(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event) { _tracker.event(event); guint key = 0; @@ -671,6 +671,9 @@ bool MultiPathManipulator::event(SPEventContext *event_context, GdkEvent *event) // b) ctrl+del preserves shape (del_preserves_shape is false), and control is pressed // Hence xor deleteNodes(del_preserves_shape ^ held_control(event->key)); + + // Delete any selected gradient nodes as well + event_context->deleteSelectedDrag(held_control(event->key)); } return true; case GDK_KEY_c: @@ -723,7 +726,7 @@ bool MultiPathManipulator::event(SPEventContext *event_context, GdkEvent *event) case GDK_KEY_u: case GDK_KEY_U: if (held_only_shift(event->key)) { - // Shift+L - make segments curves + // Shift+U - make segments curves setSegmentType(SEGMENT_CUBIC_BEZIER); return true; } diff --git a/src/ui/tool/multi-path-manipulator.h b/src/ui/tool/multi-path-manipulator.h index 2c05a1252..1328372c6 100644 --- a/src/ui/tool/multi-path-manipulator.h +++ b/src/ui/tool/multi-path-manipulator.h @@ -36,7 +36,7 @@ class MultiPathManipulator : public PointManipulator { public: MultiPathManipulator(PathSharedData &data, sigc::connection &chg); virtual ~MultiPathManipulator(); - virtual bool event(SPEventContext *, GdkEvent *event); + virtual bool event(Inkscape::UI::Tools::ToolBase *, GdkEvent *event); bool empty() { return _mmap.empty(); } unsigned size() { return _mmap.empty(); } @@ -70,6 +70,7 @@ public: void setLiveOutline(bool set); void setLiveObjects(bool set); void updateOutlineColors(); + void updateHandles(); sigc::signal<void> signal_coords_changed; /// Emitted whenever the coordinates /// shown in the status bar need updating diff --git a/src/ui/tool/node-tool.cpp b/src/ui/tool/node-tool.cpp deleted file mode 100644 index 7127ae968..000000000 --- a/src/ui/tool/node-tool.cpp +++ /dev/null @@ -1,695 +0,0 @@ -/** - * @file - * New node tool - implementation. - */ -/* Authors: - * Krzysztof Kosiński <tweenk@gmail.com> - * Abhishek Sharma - * - * Copyright (C) 2009 Authors - * Released under GNU GPL, read the file 'COPYING' for more information - */ - -#include "curve-drag-point.h" -#include <glib/gi18n.h> -#include "desktop.h" -#include "desktop-handles.h" -#include "display/sp-canvas-group.h" -#include "display/canvas-bpath.h" -#include "display/curve.h" -#include "display/sp-canvas.h" -#include "document.h" -#include "live_effects/lpeobject.h" -#include "message-context.h" -#include "selection.h" -#include "shape-editor.h" // temporary! -#include "sp-clippath.h" -#include "sp-item-group.h" -#include "sp-mask.h" -#include "sp-object-group.h" -#include "sp-path.h" -#include "sp-text.h" -#include "ui/tool/node-tool.h" -#include "ui/tool/control-point-selection.h" -#include "ui/tool/event-utils.h" -#include "ui/tool/manipulator.h" -#include "ui/tool/multi-path-manipulator.h" -#include "ui/tool/path-manipulator.h" -#include "ui/tool/selector.h" -#include "ui/tool/shape-record.h" - -#include "pixmaps/cursor-node.xpm" -#include "pixmaps/cursor-node-d.xpm" - -#include <gdk/gdkkeysyms.h> - -#if !GTK_CHECK_VERSION(2,22,0) -#include "compat-key-syms.h" -#endif - -/** @struct InkNodeTool - * - * Node tool event context. - * - * @par Architectural overview of the tool - * @par - * Here's a breakdown of what each object does. - * - Handle: shows a handle and keeps the node type constraint (smooth / symmetric) by updating - * the other handle's position when dragged. Its move() method cannot violate the constraints. - * - Node: keeps node type constraints for auto nodes and smooth nodes at ends of linear segments. - * Its move() method cannot violate constraints. Handles linear grow and dispatches spatial grow - * to MultiPathManipulator. Keeps a reference to its NodeList. - * - NodeList: exposes an iterator-based interface to nodes. It is possible to obtain an iterator - * to a node from the node. Keeps a reference to its SubpathList. - * - SubpathList: list of NodeLists that represents an editable pathvector. Keeps a reference - * to its PathManipulator. - * - PathManipulator: performs most of the single-path actions like reverse subpaths, - * delete segment, shift selection, etc. Keeps a reference to MultiPathManipulator. - * - MultiPathManipulator: performs additional operations for actions that are not per-path, - * for example node joins and segment joins. Tracks the control transforms for PMs that edit - * clipping paths and masks. It is more or less equivalent to ShapeEditor and in the future - * it might handle all shapes. Handles XML commit of actions that affect all paths or - * the node selection and removes PathManipulators that have no nodes left after e.g. node - * deletes. - * - ControlPointSelection: keeps track of node selection and a set of nodes that can potentially - * be selected. There can be more than one selection. Performs actions that require no - * knowledge about the path, only about the nodes, like dragging and transforms. It is not - * specific to nodes and can accomodate any control point derived from SelectableControlPoint. - * Transforms nodes in response to transform handle events. - * - TransformHandleSet: displays nodeset transform handles and emits transform events. The aim - * is to eventually use a common class for object and control point transforms. - * - SelectableControlPoint: base for any type of selectable point. It can belong to only one - * selection. - * - * @par Functionality that resides in weird places - * @par - * - * This list is probably incomplete. - * - Curve dragging: CurveDragPoint, controlled by PathManipulator - * - Single handle shortcuts: MultiPathManipulator::event(), ModifierTracker - * - Linear and spatial grow: Node, spatial grow routed to ControlPointSelection - * - Committing handle actions performed with the mouse: PathManipulator - * - Sculpting: ControlPointSelection - * - * @par Plans for the future - * @par - * - MultiPathManipulator should become a generic shape editor that manages all active manipulator, - * more or less like the old ShapeEditor. - * - Knotholder should be rewritten into one manipulator class per shape, using the control point - * classes. Interesting features like dragging rectangle sides could be added along the way. - * - Better handling of clip and mask editing, particularly in response to undo. - * - High level refactoring of the event context hierarchy. All aspects of tools, like toolbox - * controls, icons, event handling should be collected in one class, though each aspect - * of a tool might be in an separate class for better modularity. The long term goal is to allow - * tools to be defined in extensions or shared library plugins. - */ - -namespace { -SPCanvasGroup *create_control_group(SPDesktop *d); -void ink_node_tool_class_init(InkNodeToolClass *klass); -void ink_node_tool_init(InkNodeTool *node_context); -void ink_node_tool_dispose(GObject *object); - -void ink_node_tool_setup(SPEventContext *ec); -gint ink_node_tool_root_handler(SPEventContext *event_context, GdkEvent *event); -gint ink_node_tool_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event); -void ink_node_tool_set(SPEventContext *ec, Inkscape::Preferences::Entry *value); - -void ink_node_tool_update_tip(InkNodeTool *nt, GdkEvent *event); -void ink_node_tool_selection_changed(InkNodeTool *nt, Inkscape::Selection *sel); -void ink_node_tool_select_area(InkNodeTool *nt, Geom::Rect const &, GdkEventButton *); -void ink_node_tool_select_point(InkNodeTool *nt, Geom::Point const &, GdkEventButton *); -void ink_node_tool_mouseover_changed(InkNodeTool *nt, Inkscape::UI::ControlPoint *p); -} // anonymous namespace - -GType ink_node_tool_get_type() -{ - static GType type = 0; - if (!type) { - GTypeInfo info = { - sizeof(InkNodeToolClass), - NULL, NULL, - (GClassInitFunc) ink_node_tool_class_init, - NULL, NULL, - sizeof(InkNodeTool), - 4, - (GInstanceInitFunc) ink_node_tool_init, - NULL, /* value_table */ - }; - type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "InkNodeTool", &info, (GTypeFlags)0); - } - return type; -} - -namespace { - -SPCanvasGroup *create_control_group(SPDesktop *d) -{ - return reinterpret_cast<SPCanvasGroup*>(sp_canvas_item_new( - sp_desktop_controls(d), SP_TYPE_CANVAS_GROUP, NULL)); -} - -void destroy_group(SPCanvasGroup *g) -{ - gtk_object_destroy(GTK_OBJECT(g)); -} - -void ink_node_tool_class_init(InkNodeToolClass *klass) -{ - GObjectClass *object_class = (GObjectClass *) klass; - SPEventContextClass *event_context_class = (SPEventContextClass *) klass; - - object_class->dispose = ink_node_tool_dispose; - - event_context_class->setup = ink_node_tool_setup; - event_context_class->set = ink_node_tool_set; - event_context_class->root_handler = ink_node_tool_root_handler; - event_context_class->item_handler = ink_node_tool_item_handler; -} - -void ink_node_tool_init(InkNodeTool *nt) -{ - SPEventContext *event_context = SP_EVENT_CONTEXT(nt); - - event_context->cursor_shape = cursor_node_xpm; - event_context->hot_x = 1; - event_context->hot_y = 1; - - new (&nt->_selection_changed_connection) sigc::connection(); - new (&nt->_selection_modified_connection) sigc::connection(); - new (&nt->_mouseover_changed_connection) sigc::connection(); - //new (&nt->_mgroup) Inkscape::UI::ManipulatorGroup(nt->desktop); - new (&nt->_selected_nodes) CSelPtr(); - new (&nt->_multipath) MultiPathPtr(); - new (&nt->_selector) SelectorPtr(); - new (&nt->_path_data) PathSharedDataPtr(); - new (&nt->_shape_editors) ShapeEditors(); -} - -void ink_node_tool_dispose(GObject *object) -{ - InkNodeTool *nt = INK_NODE_TOOL(object); - - nt->enableGrDrag(false); - - nt->_selection_changed_connection.disconnect(); - nt->_selection_modified_connection.disconnect(); - nt->_mouseover_changed_connection.disconnect(); - nt->_multipath.~MultiPathPtr(); - nt->_selected_nodes.~CSelPtr(); - nt->_selector.~SelectorPtr(); - nt->_shape_editors.~ShapeEditors(); - - Inkscape::UI::PathSharedData &data = *nt->_path_data; - destroy_group(data.node_data.node_group); - destroy_group(data.node_data.handle_group); - destroy_group(data.node_data.handle_line_group); - destroy_group(data.outline_group); - destroy_group(data.dragpoint_group); - destroy_group(nt->_transform_handle_group); - - nt->_path_data.~PathSharedDataPtr(); - nt->_selection_changed_connection.~connection(); - nt->_selection_modified_connection.~connection(); - nt->_mouseover_changed_connection.~connection(); - - if (nt->_node_message_context) { - delete nt->_node_message_context; - } - - G_OBJECT_CLASS(g_type_class_peek(g_type_parent(INK_TYPE_NODE_TOOL)))->dispose(object); -} - -void ink_node_tool_setup(SPEventContext *ec) -{ - InkNodeTool *nt = INK_NODE_TOOL(ec); - - SPEventContextClass *parent = (SPEventContextClass *) g_type_class_peek(g_type_parent(INK_TYPE_NODE_TOOL)); - if (parent->setup) parent->setup(ec); - - nt->_node_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack()); - - nt->_path_data.reset(new Inkscape::UI::PathSharedData()); - Inkscape::UI::PathSharedData &data = *nt->_path_data; - data.node_data.desktop = nt->desktop; - - // selector has to be created here, so that its hidden control point is on the bottom - nt->_selector.reset(new Inkscape::UI::Selector(nt->desktop)); - - // Prepare canvas groups for controls. This guarantees correct z-order, so that - // for example a dragpoint won't obscure a node - data.outline_group = create_control_group(nt->desktop); - data.node_data.handle_line_group = create_control_group(nt->desktop); - data.dragpoint_group = create_control_group(nt->desktop); - nt->_transform_handle_group = create_control_group(nt->desktop); - data.node_data.node_group = create_control_group(nt->desktop); - data.node_data.handle_group = create_control_group(nt->desktop); - - Inkscape::Selection *selection = sp_desktop_selection (ec->desktop); - nt->_selection_changed_connection.disconnect(); - nt->_selection_changed_connection = - selection->connectChanged( - sigc::bind<0>( - sigc::ptr_fun(&ink_node_tool_selection_changed), - nt)); - /*nt->_selection_modified_connection.disconnect(); - nt->_selection_modified_connection = - selection->connectModified( - sigc::hide(sigc::bind<0>( - sigc::ptr_fun(&ink_node_tool_selection_modified), - nt)));*/ - nt->_mouseover_changed_connection.disconnect(); - nt->_mouseover_changed_connection = - Inkscape::UI::ControlPoint::signal_mouseover_change.connect( - sigc::bind<0>( - sigc::ptr_fun(&ink_node_tool_mouseover_changed), - nt)); - - nt->_selected_nodes.reset( - new Inkscape::UI::ControlPointSelection(nt->desktop, nt->_transform_handle_group)); - data.node_data.selection = nt->_selected_nodes.get(); - nt->_multipath.reset(new Inkscape::UI::MultiPathManipulator(data, - nt->_selection_changed_connection)); - - nt->_selector->signal_point.connect( - sigc::bind<0>( - sigc::ptr_fun(&ink_node_tool_select_point), - nt)); - nt->_selector->signal_area.connect( - sigc::bind<0>( - sigc::ptr_fun(&ink_node_tool_select_area), - nt)); - - nt->_multipath->signal_coords_changed.connect( - sigc::bind( - sigc::mem_fun(*nt->desktop, &SPDesktop::emitToolSubselectionChanged), - (void*) 0)); - nt->_selected_nodes->signal_point_changed.connect( - sigc::hide( sigc::hide( - sigc::bind( - sigc::bind( - sigc::ptr_fun(ink_node_tool_update_tip), - (GdkEvent*)0), - nt)))); - - nt->cursor_drag = false; - nt->show_transform_handles = true; - nt->single_node_transform_handles = false; - nt->flash_tempitem = NULL; - nt->flashed_item = NULL; - nt->_last_over = NULL; - - // read prefs before adding items to selection to prevent momentarily showing the outline - sp_event_context_read(nt, "show_handles"); - sp_event_context_read(nt, "show_outline"); - sp_event_context_read(nt, "live_outline"); - sp_event_context_read(nt, "live_objects"); - sp_event_context_read(nt, "show_path_direction"); - sp_event_context_read(nt, "show_transform_handles"); - sp_event_context_read(nt, "single_node_transform_handles"); - sp_event_context_read(nt, "edit_clipping_paths"); - sp_event_context_read(nt, "edit_masks"); - - ink_node_tool_selection_changed(nt, selection); - ink_node_tool_update_tip(nt, NULL); - - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if (prefs->getBool("/tools/nodes/selcue")) { - ec->enableSelectionCue(); - } - if (prefs->getBool("/tools/nodes/gradientdrag")) { - ec->enableGrDrag(); - } - - nt->desktop->emitToolSubselectionChanged(NULL); // sets the coord entry fields to inactive -} - -void ink_node_tool_set(SPEventContext *ec, Inkscape::Preferences::Entry *value) -{ - InkNodeTool *nt = INK_NODE_TOOL(ec); - Glib::ustring entry_name = value->getEntryName(); - - if (entry_name == "show_handles") { - nt->show_handles = value->getBool(true); - nt->_multipath->showHandles(nt->show_handles); - } else if (entry_name == "show_outline") { - nt->show_outline = value->getBool(); - nt->_multipath->showOutline(nt->show_outline); - } else if (entry_name == "live_outline") { - nt->live_outline = value->getBool(); - nt->_multipath->setLiveOutline(nt->live_outline); - } else if (entry_name == "live_objects") { - nt->live_objects = value->getBool(); - nt->_multipath->setLiveObjects(nt->live_objects); - } else if (entry_name == "show_path_direction") { - nt->show_path_direction = value->getBool(); - nt->_multipath->showPathDirection(nt->show_path_direction); - } else if (entry_name == "show_transform_handles") { - nt->show_transform_handles = value->getBool(true); - nt->_selected_nodes->showTransformHandles( - nt->show_transform_handles, nt->single_node_transform_handles); - } else if (entry_name == "single_node_transform_handles") { - nt->single_node_transform_handles = value->getBool(); - nt->_selected_nodes->showTransformHandles( - nt->show_transform_handles, nt->single_node_transform_handles); - } else if (entry_name == "edit_clipping_paths") { - nt->edit_clipping_paths = value->getBool(); - ink_node_tool_selection_changed(nt, nt->desktop->selection); - } else if (entry_name == "edit_masks") { - nt->edit_masks = value->getBool(); - ink_node_tool_selection_changed(nt, nt->desktop->selection); - } else { - SPEventContextClass *parent_class = - (SPEventContextClass *) g_type_class_peek(g_type_parent(INK_TYPE_NODE_TOOL)); - if (parent_class->set) - parent_class->set(ec, value); - } -} - -/** Recursively collect ShapeRecords */ -void gather_items(InkNodeTool *nt, SPItem *base, SPObject *obj, Inkscape::UI::ShapeRole role, - std::set<Inkscape::UI::ShapeRecord> &s) -{ - using namespace Inkscape::UI; - if (!obj) return; - - //XML Tree being used directly here while it shouldn't be. - if (SP_IS_PATH(obj) && obj->getRepr()->attribute("inkscape:original-d") != NULL) { - ShapeRecord r; - r.item = static_cast<SPItem*>(obj); - r.edit_transform = Geom::identity(); // TODO wrong? - r.role = role; - s.insert(r); - } else if (role != SHAPE_ROLE_NORMAL && (SP_IS_GROUP(obj) || SP_IS_OBJECTGROUP(obj))) { - for (SPObject *c = obj->children; c; c = c->next) { - gather_items(nt, base, c, role, s); - } - } else if (SP_IS_ITEM(obj)) { - SPItem *item = static_cast<SPItem*>(obj); - ShapeRecord r; - r.item = item; - // TODO add support for objectBoundingBox - r.edit_transform = base ? base->i2doc_affine() : Geom::identity(); - r.role = role; - if (s.insert(r).second) { - // this item was encountered the first time - if (nt->edit_clipping_paths && item->clip_ref) { - gather_items(nt, item, item->clip_ref->getObject(), SHAPE_ROLE_CLIPPING_PATH, s); - } - if (nt->edit_masks && item->mask_ref) { - gather_items(nt, item, item->mask_ref->getObject(), SHAPE_ROLE_MASK, s); - } - } - } -} - -void ink_node_tool_selection_changed(InkNodeTool *nt, Inkscape::Selection *sel) -{ - using namespace Inkscape::UI; - - std::set<ShapeRecord> shapes; - - GSList const *ilist = sel->itemList(); - - for (GSList *i = const_cast<GSList*>(ilist); i; i = i->next) { - SPObject *obj = static_cast<SPObject*>(i->data); - if (SP_IS_ITEM(obj)) { - gather_items(nt, NULL, static_cast<SPItem*>(obj), SHAPE_ROLE_NORMAL, shapes); - } - } - - // use multiple ShapeEditors for now, to allow editing many shapes at once - // needs to be rethought - for (ShapeEditors::iterator i = nt->_shape_editors.begin(); - i != nt->_shape_editors.end(); ) - { - ShapeRecord s; - s.item = i->first; - if (shapes.find(s) == shapes.end()) { - nt->_shape_editors.erase(i++); - } else { - ++i; - } - } - - for (std::set<ShapeRecord>::iterator i = shapes.begin(); i != shapes.end(); ++i) { - ShapeRecord const &r = *i; - if ((SP_IS_SHAPE(r.item) || SP_IS_TEXT(r.item)) && - nt->_shape_editors.find(r.item) == nt->_shape_editors.end()) - { - ShapeEditor *si = new ShapeEditor(nt->desktop); - si->set_item(r.item, SH_KNOTHOLDER); - nt->_shape_editors.insert(const_cast<SPItem*&>(r.item), si); - } - } - - nt->_multipath->setItems(shapes); - ink_node_tool_update_tip(nt, NULL); - nt->desktop->updateNow(); -} - -gint ink_node_tool_root_handler(SPEventContext *event_context, GdkEvent *event) -{ - /* things to handle here: - * 1. selection of items - * 2. passing events to manipulators - * 3. some keybindings - */ - using namespace Inkscape::UI; // pull in event helpers - - SPDesktop *desktop = event_context->desktop; - Inkscape::Selection *selection = desktop->selection; - InkNodeTool *nt = static_cast<InkNodeTool*>(event_context); - static Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - - if (nt->_multipath->event(event_context, event)) return true; - if (nt->_selector->event(event_context, event)) return true; - if (nt->_selected_nodes->event(event_context, event)) return true; - - switch (event->type) - { - case GDK_MOTION_NOTIFY: { - combine_motion_events(desktop->canvas, event->motion, 0); - SPItem *over_item = sp_event_context_find_item (desktop, event_point(event->button), - FALSE, TRUE); - if (over_item != nt->_last_over) { - nt->_last_over = over_item; - ink_node_tool_update_tip(nt, event); - } - - // create pathflash outline - if (prefs->getBool("/tools/nodes/pathflash_enabled")) { - if (over_item == nt->flashed_item) break; - if (!prefs->getBool("/tools/nodes/pathflash_selected") && selection->includes(over_item)) break; - if (nt->flash_tempitem) { - desktop->remove_temporary_canvasitem(nt->flash_tempitem); - nt->flash_tempitem = NULL; - nt->flashed_item = NULL; - } - if (!SP_IS_SHAPE(over_item)) break; // for now, handle only shapes - - nt->flashed_item = over_item; - SPCurve *c = SP_SHAPE(over_item)->getCurveBeforeLPE(); - if (!c) break; // break out when curve doesn't exist - c->transform(over_item->i2dt_affine()); - SPCanvasItem *flash = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), c); - sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(flash), - prefs->getInt("/tools/nodes/highlight_color", 0xff0000ff), 1.0, - SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); - sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(flash), 0, SP_WIND_RULE_NONZERO); - nt->flash_tempitem = desktop->add_temporary_canvasitem(flash, - prefs->getInt("/tools/nodes/pathflash_timeout", 500)); - c->unref(); - } - } break; // do not return true, because we need to pass this event to the parent context - // otherwise some features cease to work - - case GDK_KEY_PRESS: - switch (get_group0_keyval(&event->key)) - { - case GDK_KEY_Escape: // deselect everything - if (nt->_selected_nodes->empty()) { - selection->clear(); - } else { - nt->_selected_nodes->clear(); - } - ink_node_tool_update_tip(nt, event); - return TRUE; - case GDK_KEY_a: - case GDK_KEY_A: - if (held_control(event->key) && held_alt(event->key)) { - nt->_selected_nodes->selectAll(); - // Ctrl+A is handled in selection-chemistry.cpp via verb - ink_node_tool_update_tip(nt, event); - return TRUE; - } - break; - case GDK_KEY_h: - case GDK_KEY_H: - if (held_only_control(event->key)) { - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setBool("/tools/nodes/show_handles", !nt->show_handles); - return TRUE; - } - break; - default: - break; - } - ink_node_tool_update_tip(nt, event); - break; - case GDK_KEY_RELEASE: - ink_node_tool_update_tip(nt, event); - break; - default: break; - } - - SPEventContextClass *parent_class = (SPEventContextClass *) g_type_class_peek(g_type_parent(INK_TYPE_NODE_TOOL)); - if (parent_class->root_handler) - return parent_class->root_handler(event_context, event); - return FALSE; -} - -void ink_node_tool_update_tip(InkNodeTool *nt, GdkEvent *event) -{ - using namespace Inkscape::UI; - if (event && (event->type == GDK_KEY_PRESS || event->type == GDK_KEY_RELEASE)) { - unsigned new_state = state_after_event(event); - if (new_state == event->key.state) return; - if (state_held_shift(new_state)) { - if (nt->_last_over) { - nt->_node_message_context->set(Inkscape::NORMAL_MESSAGE, - C_("Node tool tip", "<b>Shift</b>: drag to add nodes to the selection, " - "click to toggle object selection")); - } else { - nt->_node_message_context->set(Inkscape::NORMAL_MESSAGE, - C_("Node tool tip", "<b>Shift</b>: drag to add nodes to the selection")); - } - return; - } - } - unsigned sz = nt->_selected_nodes->size(); - unsigned total = nt->_selected_nodes->allPoints().size(); - if (sz != 0) { - char *nodestring = g_strdup_printf( - ngettext("<b>%u of %u</b> node selected.", "<b>%u of %u</b> nodes selected.", total), - sz, total); - if (nt->_last_over) { - // TRANSLATORS: The %s below is where the "%u of %u nodes selected" sentence gets put - char *dyntip = g_strdup_printf(C_("Node tool tip", - "%s Drag to select nodes, click to edit only this object (more: Shift)"), - nodestring); - nt->_node_message_context->set(Inkscape::NORMAL_MESSAGE, dyntip); - g_free(dyntip); - } else { - char *dyntip = g_strdup_printf(C_("Node tool tip", - "%s Drag to select nodes, click clear the selection"), - nodestring); - nt->_node_message_context->set(Inkscape::NORMAL_MESSAGE, dyntip); - g_free(dyntip); - } - g_free(nodestring); - } else if (!nt->_multipath->empty()) { - if (nt->_last_over) { - nt->_node_message_context->set(Inkscape::NORMAL_MESSAGE, C_("Node tool tip", - "Drag to select nodes, click to edit only this object")); - } else { - nt->_node_message_context->set(Inkscape::NORMAL_MESSAGE, C_("Node tool tip", - "Drag to select nodes, click to clear the selection")); - } - } else { - if (nt->_last_over) { - nt->_node_message_context->set(Inkscape::NORMAL_MESSAGE, C_("Node tool tip", - "Drag to select objects to edit, click to edit this object (more: Shift)")); - } else { - nt->_node_message_context->set(Inkscape::NORMAL_MESSAGE, C_("Node tool tip", - "Drag to select objects to edit")); - } - } -} - -gint ink_node_tool_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event) -{ - SPEventContextClass *parent_class = - (SPEventContextClass *) g_type_class_peek(g_type_parent(INK_TYPE_NODE_TOOL)); - if (parent_class->item_handler) - return parent_class->item_handler(event_context, item, event); - return FALSE; -} - -void ink_node_tool_select_area(InkNodeTool *nt, Geom::Rect const &sel, GdkEventButton *event) -{ - using namespace Inkscape::UI; - if (nt->_multipath->empty()) { - // if multipath is empty, select rubberbanded items rather than nodes - Inkscape::Selection *selection = nt->desktop->selection; - GSList *items = sp_desktop_document(nt->desktop)->getItemsInBox(nt->desktop->dkey, sel); - selection->setList(items); - g_slist_free(items); - } else { - if (!held_shift(*event)) nt->_selected_nodes->clear(); - nt->_selected_nodes->selectArea(sel); - } -} -void ink_node_tool_select_point(InkNodeTool *nt, Geom::Point const &/*sel*/, GdkEventButton *event) -{ - using namespace Inkscape::UI; // pull in event helpers - if (!event) return; - if (event->button != 1) return; - - Inkscape::Selection *selection = nt->desktop->selection; - - SPItem *item_clicked = sp_event_context_find_item (nt->desktop, event_point(*event), - (event->state & GDK_MOD1_MASK) && !(event->state & GDK_CONTROL_MASK), TRUE); - - if (item_clicked == NULL) { // nothing under cursor - // if no Shift, deselect - // if there are nodes selected, the first click should deselect the nodes - // and the second should deselect the items - if (!state_held_shift(event->state)) { - if (nt->_selected_nodes->empty()) { - selection->clear(); - } else { - nt->_selected_nodes->clear(); - } - } - } else { - if (held_shift(*event)) { - selection->toggle(item_clicked); - } else { - selection->set(item_clicked); - } - nt->desktop->updateNow(); - } -} - -void ink_node_tool_mouseover_changed(InkNodeTool *nt, Inkscape::UI::ControlPoint *p) -{ - using Inkscape::UI::CurveDragPoint; - CurveDragPoint *cdp = dynamic_cast<CurveDragPoint*>(p); - if (cdp && !nt->cursor_drag) { - nt->cursor_shape = cursor_node_d_xpm; - nt->hot_x = 1; - nt->hot_y = 1; - sp_event_context_update_cursor(nt); - nt->cursor_drag = true; - } else if (!cdp && nt->cursor_drag) { - nt->cursor_shape = cursor_node_xpm; - nt->hot_x = 1; - nt->hot_y = 1; - sp_event_context_update_cursor(nt); - nt->cursor_drag = false; - } -} - -} // anonymous namespace - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tool/node-tool.h b/src/ui/tool/node-tool.h deleted file mode 100644 index 6f7ab01d4..000000000 --- a/src/ui/tool/node-tool.h +++ /dev/null @@ -1,95 +0,0 @@ -/** @file - * @brief New node tool with support for multiple path editing - */ -/* Authors: - * Krzysztof Kosiński <tweenk@gmail.com> - * - * Copyright (C) 2009 Authors - * Released under GNU GPL, read the file 'COPYING' for more information - */ - -#ifndef SEEN_UI_TOOL_NODE_TOOL_H -#define SEEN_UI_TOOL_NODE_TOOL_H - -#include <memory> -#include <boost/ptr_container/ptr_map.hpp> -#include <glib.h> -#include <stddef.h> -#include <sigc++/sigc++.h> -#include "event-context.h" -#include "ui/tool/node-types.h" - -#define INK_TYPE_NODE_TOOL (ink_node_tool_get_type ()) -#define INK_NODE_TOOL(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), INK_TYPE_NODE_TOOL, InkNodeTool)) -#define INK_NODE_TOOL_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), INK_TYPE_NODE_TOOL, InkNodeToolClass)) -#define INK_IS_NODE_TOOL(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), INK_TYPE_NODE_TOOL)) -#define INK_IS_NODE_TOOL_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), INK_TYPE_NODE_TOOL)) - -class InkNodeTool; -class InkNodeToolClass; - -namespace Inkscape { - -namespace Display { -class TemporaryItem; -} // namespace Display -namespace UI { -class MultiPathManipulator; -class ControlPointSelection; -class Selector; -struct PathSharedData; -} // namespace UI -} // namespace Inkscape - -typedef std::auto_ptr<Inkscape::UI::MultiPathManipulator> MultiPathPtr; -typedef std::auto_ptr<Inkscape::UI::ControlPointSelection> CSelPtr; -typedef std::auto_ptr<Inkscape::UI::Selector> SelectorPtr; -typedef std::auto_ptr<Inkscape::UI::PathSharedData> PathSharedDataPtr; -typedef boost::ptr_map<SPItem*, ShapeEditor> ShapeEditors; - -struct InkNodeTool : public SPEventContext -{ - sigc::connection _selection_changed_connection; - sigc::connection _mouseover_changed_connection; - sigc::connection _selection_modified_connection; - Inkscape::MessageContext *_node_message_context; - SPItem *flashed_item; - Inkscape::Display::TemporaryItem *flash_tempitem; - CSelPtr _selected_nodes; - MultiPathPtr _multipath; - SelectorPtr _selector; - PathSharedDataPtr _path_data; - SPCanvasGroup *_transform_handle_group; - SPItem *_last_over; - ShapeEditors _shape_editors; - - unsigned cursor_drag : 1; - unsigned show_handles : 1; - unsigned show_outline : 1; - unsigned live_outline : 1; - unsigned live_objects : 1; - unsigned show_path_direction : 1; - unsigned show_transform_handles : 1; - unsigned single_node_transform_handles : 1; - unsigned edit_clipping_paths : 1; - unsigned edit_masks : 1; -}; - -struct InkNodeToolClass { - SPEventContextClass parent_class; -}; - -GType ink_node_tool_get_type (void); - -#endif - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tool/node.cpp b/src/ui/tool/node.cpp index ad48b523b..fbbc4be64 100644 --- a/src/ui/tool/node.cpp +++ b/src/ui/tool/node.cpp @@ -1,7 +1,3 @@ -/** - * @file - * Editable node - implementation. - */ /* Authors: * Krzysztof Kosiński <tweenk.pl@gmail.com> * Jon A. Cruz <jon@joncruz.org> @@ -26,33 +22,57 @@ #include "preferences.h" #include "snap.h" #include "snap-preferences.h" -#include "sp-metrics.h" #include "sp-namedview.h" +#include "ui/control-manager.h" #include "ui/tool/control-point-selection.h" #include "ui/tool/event-utils.h" #include "ui/tool/node.h" #include "ui/tool/path-manipulator.h" #include <gdk/gdkkeysyms.h> -#if !GTK_CHECK_VERSION(2,22,0) -#include "compat-key-syms.h" -#endif +namespace { + +Inkscape::ControlType nodeTypeToCtrlType(Inkscape::UI::NodeType type) +{ + Inkscape::ControlType result = Inkscape::CTRL_TYPE_NODE_CUSP; + switch(type) { + case Inkscape::UI::NODE_SMOOTH: + result = Inkscape::CTRL_TYPE_NODE_SMOOTH; + break; + case Inkscape::UI::NODE_AUTO: + result = Inkscape::CTRL_TYPE_NODE_AUTO; + break; + case Inkscape::UI::NODE_SYMMETRIC: + result = Inkscape::CTRL_TYPE_NODE_SYMETRICAL; + break; + case Inkscape::UI::NODE_CUSP: + default: + result = Inkscape::CTRL_TYPE_NODE_CUSP; + break; + } + return result; +} + +} // namespace namespace Inkscape { namespace UI { -static SelectableControlPoint::ColorSet node_colors = { - { - {0xbfbfbf00, 0x000000ff}, // normal fill, stroke - {0xff000000, 0x000000ff}, // mouseover fill, stroke - {0xff000000, 0x000000ff} // clicked fill, stroke - }, +ControlPoint::ColorSet Node::node_colors = { + {0xbfbfbf00, 0x000000ff}, // normal fill, stroke + {0xff000000, 0x000000ff}, // mouseover fill, stroke + {0xff000000, 0x000000ff}, // clicked fill, stroke + // {0x0000ffff, 0x000000ff}, // normal fill, stroke when selected {0xff000000, 0x000000ff}, // mouseover fill, stroke when selected {0xff000000, 0x000000ff} // clicked fill, stroke when selected }; -static ControlPoint::ColorSet handle_colors = { +ControlPoint::ColorSet Handle::_handle_colors = { + {0xffffffff, 0x000000ff}, // normal fill, stroke + {0xff000000, 0x000000ff}, // mouseover fill, stroke + {0xff000000, 0x000000ff}, // clicked fill, stroke + // {0xffffffff, 0x000000ff}, // normal fill, stroke {0xff000000, 0x000000ff}, // mouseover fill, stroke {0xff000000, 0x000000ff} // clicked fill, stroke @@ -75,30 +95,27 @@ static Geom::Point direction(Geom::Point const &first, Geom::Point const &second return Geom::unit_vector(second - first); } -/** - * Control point of a cubic Bezier curve in a path. - * - * Handle keeps the node type invariant only for the opposite handle of the same node. - * Keeping the invariant on node moves is left to the %Node class. - */ Geom::Point Handle::_saved_other_pos(0, 0); + double Handle::_saved_length = 0.0; + bool Handle::_drag_out = false; -Handle::Handle(NodeSharedData const &data, Geom::Point const &initial_pos, Node *parent) - : ControlPoint(data.desktop, initial_pos, SP_ANCHOR_CENTER, SP_CTRL_SHAPE_CIRCLE, 7.0, - &handle_colors, data.handle_group) - , _parent(parent) - , _degenerate(true) +Handle::Handle(NodeSharedData const &data, Geom::Point const &initial_pos, Node *parent) : + ControlPoint(data.desktop, initial_pos, SP_ANCHOR_CENTER, + CTRL_TYPE_ADJ_HANDLE, + _handle_colors, data.handle_group), + _parent(parent), + _handle_line(ControlManager::getManager().createControlLine(data.handle_line_group)), + _degenerate(true) { - _cset = &handle_colors; - _handle_line = SP_CTRLLINE(sp_canvas_item_new(data.handle_line_group, SP_TYPE_CTRLLINE, NULL)); setVisible(false); } + Handle::~Handle() { //sp_canvas_item_hide(_handle_line); - gtk_object_destroy(_handle_line); + sp_canvas_item_destroy(_handle_line); } void Handle::setVisible(bool v) @@ -233,7 +250,7 @@ char const *Handle::handle_type_to_localized_string(NodeType type) } } -bool Handle::_eventHandler(SPEventContext *event_context, GdkEvent *event) +bool Handle::_eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event) { switch (event->type) { @@ -275,7 +292,7 @@ void Handle::dragged(Geom::Point &new_pos, GdkEventMotion *event) Geom::Point parent_pos = _parent->position(); Geom::Point origin = _last_drag_origin(); SnapManager &sm = _desktop->namedview->snap_manager; - bool snap = sm.someSnapperMightSnap(); + bool snap = held_shift(*event) ? false : sm.someSnapperMightSnap(); boost::optional<Inkscape::Snapper::SnapConstraint> ctrl_constraint; // with Alt, preserve length @@ -387,10 +404,18 @@ bool Handle::clicked(GdkEventButton *event) return true; } +Handle const *Handle::other() const +{ + return const_cast<Handle *>(this)->other(); +} + Handle *Handle::other() { - if (this == &_parent->_front) return &_parent->_back; - return &_parent->_front; + if (this == &_parent->_front) { + return &_parent->_back; + } else { + return &_parent->_front; + } } static double snap_increment_degrees() { @@ -399,7 +424,7 @@ static double snap_increment_degrees() { return 180.0 / snaps; } -Glib::ustring Handle::_getTip(unsigned state) +Glib::ustring Handle::_getTip(unsigned state) const { char const *more; bool can_shift_rotate = _parent->type() == NODE_CUSP && !other()->isDegenerate(); @@ -457,16 +482,20 @@ Glib::ustring Handle::_getTip(unsigned state) } } -Glib::ustring Handle::_getDragTip(GdkEventMotion */*event*/) +Glib::ustring Handle::_getDragTip(GdkEventMotion */*event*/) const { Geom::Point dist = position() - _last_drag_origin(); // report angle in mathematical convention double angle = Geom::angle_between(Geom::Point(-1,0), position() - _parent->position()); angle += M_PI; // angle is (-M_PI...M_PI] - offset by +pi and scale to 0...360 angle *= 360.0 / (2 * M_PI); - GString *x = SP_PX_TO_METRIC_STRING(dist[Geom::X], _desktop->namedview->getDefaultMetric()); - GString *y = SP_PX_TO_METRIC_STRING(dist[Geom::Y], _desktop->namedview->getDefaultMetric()); - GString *len = SP_PX_TO_METRIC_STRING(length(), _desktop->namedview->getDefaultMetric()); + + Inkscape::Util::Quantity x_q = Inkscape::Util::Quantity(dist[Geom::X], "px"); + Inkscape::Util::Quantity y_q = Inkscape::Util::Quantity(dist[Geom::Y], "px"); + Inkscape::Util::Quantity len_q = Inkscape::Util::Quantity(length(), "px"); + GString *x = g_string_new(x_q.string(_desktop->namedview->doc_units).c_str()); + GString *y = g_string_new(y_q.string(_desktop->namedview->doc_units).c_str()); + GString *len = g_string_new(len_q.string(_desktop->namedview->doc_units).c_str()); Glib::ustring ret = format_tip(C_("Path handle tip", "Move handle by %s, %s; angle %.2f°, length %s"), x->str, y->str, angle, len->str); g_string_free(x, TRUE); @@ -475,34 +504,48 @@ Glib::ustring Handle::_getDragTip(GdkEventMotion */*event*/) return ret; } -/** - * Curve endpoint in an editable path. - * - * The method move() keeps node type invariants during translations. - */ -Node::Node(NodeSharedData const &data, Geom::Point const &initial_pos) - : SelectableControlPoint(data.desktop, initial_pos, SP_ANCHOR_CENTER, - SP_CTRL_SHAPE_DIAMOND, 9.0, *data.selection, &node_colors, data.node_group) - , _front(data, initial_pos, this) - , _back(data, initial_pos, this) - , _type(NODE_CUSP) - , _handles_shown(false) +Node::Node(NodeSharedData const &data, Geom::Point const &initial_pos) : + SelectableControlPoint(data.desktop, initial_pos, SP_ANCHOR_CENTER, + CTRL_TYPE_NODE_CUSP, + *data.selection, + node_colors, data.node_group), + _front(data, initial_pos, this), + _back(data, initial_pos, this), + _type(NODE_CUSP), + _handles_shown(false) { // NOTE we do not set type here, because the handles are still degenerate } +Node const *Node::_next() const +{ + return const_cast<Node*>(this)->_next(); +} + // NOTE: not using iterators won't make this much quicker because iterators can be 100% inlined. Node *Node::_next() { NodeList::iterator n = NodeList::get_iterator(this).next(); - if (n) return n.ptr(); - return NULL; + if (n) { + return n.ptr(); + } else { + return NULL; + } +} + +Node const *Node::_prev() const +{ + return const_cast<Node *>(this)->_prev(); } + Node *Node::_prev() { NodeList::iterator p = NodeList::get_iterator(this).prev(); - if (p) return p.ptr(); - return NULL; + if (p) { + return p.ptr(); + } else { + return NULL; + } } void Node::move(Geom::Point const &new_pos) @@ -531,7 +574,7 @@ void Node::transform(Geom::Affine const &m) _fixNeighbors(old_pos, position()); } -Geom::Rect Node::bounds() +Geom::Rect Node::bounds() const { Geom::Rect b(position(), position()); b.expandTo(_front.position()); @@ -608,17 +651,23 @@ void Node::_updateAutoHandles() void Node::showHandles(bool v) { _handles_shown = v; - if (!_front.isDegenerate()) _front.setVisible(v); - if (!_back.isDegenerate()) _back.setVisible(v); + if (!_front.isDegenerate()) { + _front.setVisible(v); + } + if (!_back.isDegenerate()) { + _back.setVisible(v); + } } -/** Sets the node type and optionally restores the invariants associated with the given type. - * @param type The type to set - * @param update_handles Whether to restore invariants associated with the given type. - * Passing false is useful e.g. wen initially creating the path, - * and when making cusp nodes during some node algorithms. - * Pass true when used in response to an UI node type button. - */ +void Node::updateHandles() +{ + _handleControlStyling(); + + _front._handleControlStyling(); + _back._handleControlStyling(); +} + + void Node::setType(NodeType type, bool update_handles) { if (type == NODE_PICK_BEST) { @@ -711,12 +760,10 @@ void Node::setType(NodeType type, bool update_handles) } } _type = type; - _setShape(_node_type_to_shape(type)); + _setControlType(nodeTypeToCtrlType(_type)); updateState(); } -/** Pick the best type for this node, based on the position of its handles. - * This is what assigns types to nodes created using the pen tool. */ void Node::pickBestType() { _type = NODE_CUSP; @@ -762,17 +809,15 @@ void Node::pickBestType() } } } while (false); - _setShape(_node_type_to_shape(_type)); + _setControlType(nodeTypeToCtrlType(_type)); updateState(); } -bool Node::isEndNode() +bool Node::isEndNode() const { return !_prev() || !_next(); } -/** Move the node to the bottom of its canvas group. Useful for node break, to ensure that - * the selected nodes are above the unselected ones. */ void Node::sink() { sp_canvas_item_move_to_z(_canvas_item, 0); @@ -789,8 +834,7 @@ NodeType Node::parse_nodetype(char x) } } -/** Customized event handler to catch scroll events needed for selection grow/shrink. */ -bool Node::_eventHandler(SPEventContext *event_context, GdkEvent *event) +bool Node::_eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event) { int dir = 0; @@ -834,8 +878,6 @@ bool Node::_eventHandler(SPEventContext *event_context, GdkEvent *event) return ControlPoint::_eventHandler(event_context, event); } -/** Select or deselect a node in this node's subpath based on its path distance from this node. - * @param dir If negative, shrink selection by one node; if positive, grow by one node */ void Node::_linearGrow(int dir) { // Interestingly, we do not need any help from PathManipulator when doing linear grow. @@ -948,29 +990,36 @@ void Node::_linearGrow(int dir) void Node::_setState(State state) { // change node size to match type and selection state - switch (_type) { - case NODE_AUTO: - case NODE_CUSP: - if (selected()) _setSize(11); - else _setSize(9); - break; - default: - if(selected()) _setSize(9); - else _setSize(7); - break; + ControlManager &mgr = ControlManager::getManager(); + mgr.setSelected(_canvas_item, selected()); + switch (state) { + case STATE_NORMAL: + mgr.setActive(_canvas_item, false); + mgr.setPrelight(_canvas_item, false); + break; + case STATE_MOUSEOVER: + mgr.setActive(_canvas_item, false); + mgr.setPrelight(_canvas_item, true); + break; + case STATE_CLICKED: + mgr.setActive(_canvas_item, true); + mgr.setPrelight(_canvas_item, false); + break; } SelectableControlPoint::_setState(state); } bool Node::grabbed(GdkEventMotion *event) { - if (SelectableControlPoint::grabbed(event)) + if (SelectableControlPoint::grabbed(event)) { return true; + } // Dragging out handles with Shift + drag on a node. - if (!held_shift(*event)) return false; + if (!held_shift(*event)) { + return false; + } - Handle *h; Geom::Point evp = event_point(*event); Geom::Point rel_evp = evp - _last_click_event_point(); @@ -991,8 +1040,11 @@ bool Node::grabbed(GdkEventMotion *event) angle_prev = fabs(Geom::angle_between(rel_evp, prev_relpos)); has_degenerate = true; } - if (!has_degenerate) return false; - h = angle_next < angle_prev ? &_front : &_back; + if (!has_degenerate) { + return false; + } + + Handle *h = angle_next < angle_prev ? &_front : &_back; h->setPosition(_desktop->w2d(evp)); h->setVisible(true); @@ -1138,13 +1190,13 @@ bool Node::clicked(GdkEventButton *event) return SelectableControlPoint::clicked(event); } -Inkscape::SnapSourceType Node::_snapSourceType() +Inkscape::SnapSourceType Node::_snapSourceType() const { if (_type == NODE_SMOOTH || _type == NODE_AUTO) return SNAPSOURCE_NODE_SMOOTH; return SNAPSOURCE_NODE_CUSP; } -Inkscape::SnapTargetType Node::_snapTargetType() +Inkscape::SnapTargetType Node::_snapTargetType() const { if (_type == NODE_SMOOTH || _type == NODE_AUTO) return SNAPTARGET_NODE_SMOOTH; @@ -1156,10 +1208,6 @@ Inkscape::SnapCandidatePoint Node::snapCandidatePoint() return SnapCandidatePoint(position(), _snapSourceType(), _snapTargetType()); } -/** - * Gets the handle that faces the given adjacent node. - * Will abort with error if the given node is not adjacent. - */ Handle *Node::handleToward(Node *to) { if (_next() == to) { @@ -1169,12 +1217,9 @@ Handle *Node::handleToward(Node *to) return back(); } g_error("Node::handleToward(): second node is not adjacent!"); + return NULL; } -/** - * Gets the node in the direction of the given handle. - * Will abort with error if the handle doesn't belong to this node. - */ Node *Node::nodeToward(Handle *dir) { if (front() == dir) { @@ -1184,12 +1229,9 @@ Node *Node::nodeToward(Handle *dir) return _prev(); } g_error("Node::nodeToward(): handle is not a child of this node!"); + return NULL; } -/** - * Gets the handle that goes in the direction opposite to the given adjacent node. - * Will abort with error if the given node is not adjacent. - */ Handle *Node::handleAwayFrom(Node *to) { if (_next() == to) { @@ -1199,12 +1241,9 @@ Handle *Node::handleAwayFrom(Node *to) return front(); } g_error("Node::handleAwayFrom(): second node is not adjacent!"); + return NULL; } -/** - * Gets the node in the direction opposite to the given handle. - * Will abort with error if the handle doesn't belong to this node. - */ Node *Node::nodeAwayFrom(Handle *h) { if (front() == h) { @@ -1214,9 +1253,10 @@ Node *Node::nodeAwayFrom(Handle *h) return _next(); } g_error("Node::nodeAwayFrom(): handle is not a child of this node!"); + return NULL; } -Glib::ustring Node::_getTip(unsigned state) +Glib::ustring Node::_getTip(unsigned state) const { if (state_held_shift(state)) { bool can_drag_out = (_next() && _front.isDegenerate()) || (_prev() && _back.isDegenerate()); @@ -1258,13 +1298,15 @@ Glib::ustring Node::_getTip(unsigned state) "<b>%s</b>: drag to shape the path, click to select only this node (more: Shift, Ctrl, Alt)"), nodetype); } -Glib::ustring Node::_getDragTip(GdkEventMotion */*event*/) +Glib::ustring Node::_getDragTip(GdkEventMotion */*event*/) const { Geom::Point dist = position() - _last_drag_origin(); - GString *x = SP_PX_TO_METRIC_STRING(dist[Geom::X], _desktop->namedview->getDefaultMetric()); - GString *y = SP_PX_TO_METRIC_STRING(dist[Geom::Y], _desktop->namedview->getDefaultMetric()); - Glib::ustring ret = format_tip(C_("Path node tip", "Move node by %s, %s"), - x->str, y->str); + + Inkscape::Util::Quantity x_q = Inkscape::Util::Quantity(dist[Geom::X], "px"); + Inkscape::Util::Quantity y_q = Inkscape::Util::Quantity(dist[Geom::Y], "px"); + GString *x = g_string_new(x_q.string(_desktop->namedview->doc_units).c_str()); + GString *y = g_string_new(y_q.string(_desktop->namedview->doc_units).c_str()); + Glib::ustring ret = format_tip(C_("Path node tip", "Move node by %s, %s"), x->str, y->str); g_string_free(x, TRUE); g_string_free(y, TRUE); return ret; @@ -1281,7 +1323,6 @@ char const *Node::node_type_to_localized_string(NodeType type) } } -/** Determine whether two nodes are joined by a linear segment. */ bool Node::_is_line_segment(Node *first, Node *second) { if (!first || !second) return false; @@ -1292,25 +1333,6 @@ bool Node::_is_line_segment(Node *first, Node *second) return false; } -SPCtrlShapeType Node::_node_type_to_shape(NodeType type) -{ - switch(type) { - case NODE_CUSP: return SP_CTRL_SHAPE_DIAMOND; - case NODE_SMOOTH: return SP_CTRL_SHAPE_SQUARE; - case NODE_AUTO: return SP_CTRL_SHAPE_CIRCLE; - case NODE_SYMMETRIC: return SP_CTRL_SHAPE_SQUARE; - default: return SP_CTRL_SHAPE_DIAMOND; - } -} - - -/** - * An editable list of nodes representing a subpath. - * - * It can optionally be cyclic to represent a closed path. - * The list has iterators that act like plain node iterators, but can also be used - * to obtain shared pointers to nodes. - */ NodeList::NodeList(SubpathList &splist) : _list(splist) , _closed(false) @@ -1342,8 +1364,6 @@ bool NodeList::closed() return _closed; } -/** A subpath is degenerate if it has no segments - either one node in an open path - * or no nodes in a closed path */ bool NodeList::degenerate() { return closed() ? empty() : ++begin() == end(); @@ -1360,10 +1380,9 @@ NodeList::iterator NodeList::before(double t, double *fracpart) return ret; } -// insert a node before i -NodeList::iterator NodeList::insert(iterator i, Node *x) +NodeList::iterator NodeList::insert(iterator pos, Node *x) { - ListNode *ins = i._node; + ListNode *ins = pos._node; x->ln_next = ins; x->ln_prev = ins->ln_prev; ins->ln_prev->ln_next = x; @@ -1469,11 +1488,6 @@ NodeList &NodeList::get(iterator const &i) { } -/** - * @class SubpathList - * Editable path composed of one or more subpaths. - */ - } // namespace UI } // namespace Inkscape diff --git a/src/ui/tool/node.h b/src/ui/tool/node.h index f2e31e018..b874949f5 100644 --- a/src/ui/tool/node.h +++ b/src/ui/tool/node.h @@ -3,6 +3,7 @@ */ /* Authors: * Krzysztof Kosiński <tweenk.pl@gmail.com> + * Jon A. Cruz <jon@joncruz.org> * * Copyright (C) 2009 Authors * Released under GNU GPL, read the file 'COPYING' for more information @@ -15,7 +16,13 @@ #include <iosfwd> #include <stdexcept> #include <cstddef> + +#if __cplusplus >= 201103L +#include <functional> +#else #include <tr1/functional> +#endif + #include <boost/enable_shared_from_this.hpp> #include <boost/shared_ptr.hpp> #include "ui/tool/selectable-control-point.h" @@ -30,11 +37,13 @@ template <typename> class NodeIterator; } } +#if __cplusplus < 201103L namespace std { namespace tr1 { template <typename N> struct hash< Inkscape::UI::NodeIterator<N> >; } } +#endif namespace Inkscape { namespace UI { @@ -80,10 +89,11 @@ struct NodeSharedData { class Handle : public ControlPoint { public: + virtual ~Handle(); - inline Geom::Point relativePos(); - inline double length(); - bool isDegenerate() { return _degenerate; } // True if the handle is retracted, i.e. has zero length. + inline Geom::Point relativePos() const; + inline double length() const; + bool isDegenerate() const { return _degenerate; } // True if the handle is retracted, i.e. has zero length. virtual void setVisible(bool); virtual void move(Geom::Point const &p); @@ -96,80 +106,161 @@ public: void setDirection(Geom::Point const &dir); Node *parent() { return _parent; } Handle *other(); + Handle const *other() const; static char const *handle_type_to_localized_string(NodeType type); + protected: + Handle(NodeSharedData const &data, Geom::Point const &initial_pos, Node *parent); - virtual bool _eventHandler(SPEventContext *event_context, GdkEvent *event); - virtual void dragged(Geom::Point &, GdkEventMotion *); - virtual bool grabbed(GdkEventMotion *); - virtual void ungrabbed(GdkEventButton *); - virtual bool clicked(GdkEventButton *); + virtual bool _eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event); + virtual void dragged(Geom::Point &new_pos, GdkEventMotion *event); + virtual bool grabbed(GdkEventMotion *event); + virtual void ungrabbed(GdkEventButton *event); + virtual bool clicked(GdkEventButton *event); + + virtual Glib::ustring _getTip(unsigned state) const; + virtual Glib::ustring _getDragTip(GdkEventMotion *event) const; + virtual bool _hasDragTips() const { return true; } - virtual Glib::ustring _getTip(unsigned state); - virtual Glib::ustring _getDragTip(GdkEventMotion *event); - virtual bool _hasDragTips() { return true; } private: + inline PathManipulator &_pm(); Node *_parent; // the handle's lifetime does not extend beyond that of the parent node, // so a naked pointer is OK and allows setting it during Node's construction SPCtrlLine *_handle_line; bool _degenerate; // True if the handle is retracted, i.e. has zero length. This is used often internally so it makes sense to cache this + /** + * Control point of a cubic Bezier curve in a path. + * + * Handle keeps the node type invariant only for the opposite handle of the same node. + * Keeping the invariant on node moves is left to the %Node class. + */ static Geom::Point _saved_other_pos; + static double _saved_length; static bool _drag_out; + static ColorSet _handle_colors; friend class Node; }; class Node : ListNode, public SelectableControlPoint { public: + + /** + * Curve endpoint in an editable path. + * + * The method move() keeps node type invariants during translations. + */ Node(NodeSharedData const &data, Geom::Point const &pos); + virtual void move(Geom::Point const &p); virtual void transform(Geom::Affine const &m); - virtual Geom::Rect bounds(); - - NodeType type() { return _type; } + virtual Geom::Rect bounds() const; + + NodeType type() const { return _type; } + + /** + * Sets the node type and optionally restores the invariants associated with the given type. + * @param type The type to set. + * @param update_handles Whether to restore invariants associated with the given type. + * Passing false is useful e.g. wen initially creating the path, + * and when making cusp nodes during some node algorithms. + * Pass true when used in response to an UI node type button. + */ void setType(NodeType type, bool update_handles = true); + void showHandles(bool v); + + void updateHandles(); + + + /** + * Pick the best type for this node, based on the position of its handles. + * This is what assigns types to nodes created using the pen tool. + */ void pickBestType(); // automatically determine the type from handle positions - bool isDegenerate() { return _front.isDegenerate() && _back.isDegenerate(); } - bool isEndNode(); + + bool isDegenerate() const { return _front.isDegenerate() && _back.isDegenerate(); } + bool isEndNode() const; Handle *front() { return &_front; } Handle *back() { return &_back; } + + /** + * Gets the handle that faces the given adjacent node. + * Will abort with error if the given node is not adjacent. + */ Handle *handleToward(Node *to); + + /** + * Gets the node in the direction of the given handle. + * Will abort with error if the handle doesn't belong to this node. + */ Node *nodeToward(Handle *h); + + /** + * Gets the handle that goes in the direction opposite to the given adjacent node. + * Will abort with error if the given node is not adjacent. + */ Handle *handleAwayFrom(Node *to); + + /** + * Gets the node in the direction opposite to the given handle. + * Will abort with error if the handle doesn't belong to this node. + */ Node *nodeAwayFrom(Handle *h); + NodeList &nodeList() { return *(static_cast<ListNode*>(this)->ln_list); } + + /** + * Move the node to the bottom of its canvas group. + * Useful for node break, to ensure that the selected nodes are above the unselected ones. + */ void sink(); static NodeType parse_nodetype(char x); static char const *node_type_to_localized_string(NodeType type); + // temporarily public - virtual bool _eventHandler(SPEventContext *event_context, GdkEvent *event); + /** Customized event handler to catch scroll events needed for selection grow/shrink. */ + virtual bool _eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event); + Inkscape::SnapCandidatePoint snapCandidatePoint(); + protected: - virtual void dragged(Geom::Point &, GdkEventMotion *); - virtual bool grabbed(GdkEventMotion *); - virtual bool clicked(GdkEventButton *); + + virtual void dragged(Geom::Point &new_pos, GdkEventMotion *event); + virtual bool grabbed(GdkEventMotion *event); + virtual bool clicked(GdkEventButton *event); virtual void _setState(State state); - virtual Glib::ustring _getTip(unsigned state); - virtual Glib::ustring _getDragTip(GdkEventMotion *event); - virtual bool _hasDragTips() { return true; } + virtual Glib::ustring _getTip(unsigned state) const; + virtual Glib::ustring _getDragTip(GdkEventMotion *event) const; + virtual bool _hasDragTips() const { return true; } + private: + Node(Node const &); void _fixNeighbors(Geom::Point const &old_pos, Geom::Point const &new_pos); void _updateAutoHandles(); + + /** + * Select or deselect a node in this node's subpath based on its path distance from this node. + * @param dir If negative, shrink selection by one node; if positive, grow by one node. + */ void _linearGrow(int dir); + Node *_next(); + Node const *_next() const; Node *_prev(); - Inkscape::SnapSourceType _snapSourceType(); - Inkscape::SnapTargetType _snapTargetType(); + Node const *_prev() const; + Inkscape::SnapSourceType _snapSourceType() const; + Inkscape::SnapTargetType _snapTargetType() const; inline PathManipulator &_pm(); - static SPCtrlShapeType _node_type_to_shape(NodeType type); + + /** Determine whether two nodes are joined by a linear segment. */ static bool _is_line_segment(Node *first, Node *second); // Handles are always present, but are not visible if they coincide with the node @@ -179,6 +270,8 @@ private: Handle _back; ///< Node handle in the forward direction of the path NodeType _type; ///< Type of node - cusp, smooth... bool _handles_shown; + static ColorSet node_colors; + friend class Handle; friend class NodeList; friend class NodeIterator<Node>; @@ -224,14 +317,14 @@ public: // default copy, default assign self &operator++() { - _node = _node->ln_next; + _node = (_node?_node->ln_next:NULL); return *this; } self &operator--() { - _node = _node->ln_prev; + _node = (_node?_node->ln_prev:NULL); return *this; } - bool operator==(self const &other) const { return _node == other._node; } + bool operator==(self const &other) const { if(&other){return _node == other._node;} else{return false;} } N &operator*() const { return *static_cast<N*>(_node); } inline operator bool() const; // define after NodeList /// Get a pointer to the underlying node. Equivalent to <code>&*i</code>. @@ -271,7 +364,15 @@ public: typedef NodeIterator<value_type const> const_iterator; // TODO Lame. Make this private and make SubpathList a factory + /** + * An editable list of nodes representing a subpath. + * + * It can optionally be cyclic to represent a closed path. + * The list has iterators that act like plain node iterators, but can also be used + * to obtain shared pointers to nodes. + */ NodeList(SubpathList &_list); + ~NodeList(); // iterators @@ -286,7 +387,13 @@ public: // extra node-specific methods bool closed(); + + /** + * A subpath is degenerate if it has no segments - either one node in an open path + * or no nodes in a closed path. + */ bool degenerate(); + void setClosed(bool c) { _closed = c; } iterator before(double t, double *fracpart = NULL); const_iterator before(double t, double *fracpart = NULL) const { @@ -294,7 +401,10 @@ public: } // list operations + + /** insert a node before pos. */ iterator insert(iterator pos, Node *x); + template <class InputIterator> void insert(iterator pos, InputIterator first, InputIterator last) { for (; first != last; ++first) insert(pos, *first); @@ -342,7 +452,10 @@ private: friend class NodeIterator<Node const>; }; -/** List of node lists. Represents an editable path. */ +/** + * List of node lists. Represents an editable path. + * Editable path composed of one or more subpaths. + */ class SubpathList : public std::list< boost::shared_ptr<NodeList> > { public: typedef std::list< boost::shared_ptr<NodeList> > list_type; @@ -361,13 +474,13 @@ private: // define inline Handle funcs after definition of Node -inline Geom::Point Handle::relativePos() { +inline Geom::Point Handle::relativePos() const { return position() - _parent->position(); } inline void Handle::setRelativePos(Geom::Point const &p) { setPosition(_parent->position() + p); } -inline double Handle::length() { +inline double Handle::length() const { return relativePos().length(); } inline PathManipulator &Handle::_pm() { diff --git a/src/ui/tool/path-manipulator.cpp b/src/ui/tool/path-manipulator.cpp index 97e25069f..338499672 100644 --- a/src/ui/tool/path-manipulator.cpp +++ b/src/ui/tool/path-manipulator.cpp @@ -18,8 +18,7 @@ #include <boost/shared_ptr.hpp> #include <2geom/bezier-curve.h> #include <2geom/bezier-utils.h> -#include <2geom/svg-path.h> -#include <glibmm.h> +#include <2geom/path-sink.h> #include <glibmm/i18n.h> #include "ui/tool/path-manipulator.h" #include "desktop.h" @@ -152,13 +151,13 @@ PathManipulator::~PathManipulator() { delete _dragpoint; delete _observer; - gtk_object_destroy(_outline); + sp_canvas_item_destroy(_outline); _spcurve->unref(); clear(); } /** Handle motion events to update the position of the curve drag point. */ -bool PathManipulator::event(SPEventContext * /*event_context*/, GdkEvent *event) +bool PathManipulator::event(Inkscape::UI::Tools::ToolBase * /*event_context*/, GdkEvent *event) { if (empty()) return false; @@ -204,7 +203,7 @@ void PathManipulator::writeXML() sp_object_ref(_path); _path->deleteObject(true, true); sp_object_unref(_path); - _path = 0; + _path = NULL; } _observer->unblock(); } @@ -460,7 +459,10 @@ void PathManipulator::weldSegments() if (j->selected()) ++num_selected; else ++num_unselected; } - if (num_selected < 3) continue; + + // if 2 or fewer nodes are selected, there can't be any middle points to remove. + if (num_selected <= 2) continue; + if (num_unselected == 0 && sp->closed()) { // if all nodes in a closed subpath are selected, the operation doesn't make much sense continue; @@ -490,14 +492,16 @@ void PathManipulator::weldSegments() } if (num_points > 2) { // remove nodes in the middle + // TODO: fit bezier to the former shape sel_beg = sel_beg.next(); while (sel_beg != sel_end.prev()) { NodeList::iterator next = sel_beg.next(); sp->erase(sel_beg); sel_beg = next; } - sel_beg = sel_end; } + sel_beg = sel_end; + // decrease num_selected by the number of points processed num_selected -= num_points; } } @@ -915,6 +919,15 @@ void PathManipulator::setLiveObjects(bool set) _live_objects = set; } +void PathManipulator::updateHandles() +{ + for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) { + for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) { + j->updateHandles(); + } + } +} + void PathManipulator::setControlsTransform(Geom::Affine const &tnew) { Geom::Affine delta = _i2d_transform.inverse() * _edit_transform.inverse() * tnew * _i2d_transform; @@ -1189,12 +1202,13 @@ void PathManipulator::_createGeometryFromControlPoints(bool alert_LPE) } ++spi; } - builder.finish(); + builder.flush(); Geom::PathVector pathv = builder.peek() * (_edit_transform * _i2d_transform).inverse(); _spcurve->set_pathvector(pathv); if (alert_LPE) { - if (SP_IS_LPE_ITEM(_path) && sp_lpe_item_has_path_effect(SP_LPE_ITEM(_path))) { - PathEffectList effect_list = sp_lpe_item_get_effect_list(SP_LPE_ITEM(_path)); + /// \todo note that _path can be an Inkscape::LivePathEffect::Effect* too, kind of confusing, rework member naming? + if (SP_IS_LPE_ITEM(_path) && _path->hasPathEffect()) { + PathEffectList effect_list = _path->getEffectList(); LivePathEffect::LPEPowerStroke *lpe_pwr = dynamic_cast<LivePathEffect::LPEPowerStroke*>( effect_list.front()->lpeobject->get_lpe() ); if (lpe_pwr) { lpe_pwr->adjustForNewPath(pathv); @@ -1296,6 +1310,10 @@ void PathManipulator::_getGeometry() } else { _spcurve->unref(); _spcurve = _path->get_curve_for_edit(); + // never allow NULL to sneak in here! + if (_spcurve == NULL) { + _spcurve = new SPCurve(); + } } } @@ -1320,7 +1338,7 @@ void PathManipulator::_setGeometry() if (_path->getRepr()->attribute("inkscape:original-d")) _path->set_original_curve(_spcurve, false, false); else - SP_SHAPE(_path)->setCurve(_spcurve, false); + _path->setCurve(_spcurve, false); } } diff --git a/src/ui/tool/path-manipulator.h b/src/ui/tool/path-manipulator.h index fe73555c8..7a13ce723 100644 --- a/src/ui/tool/path-manipulator.h +++ b/src/ui/tool/path-manipulator.h @@ -21,8 +21,8 @@ #include "ui/tool/manipulator.h" struct SPCanvasItem; -struct SPCurve; -struct SPPath; +class SPCurve; +class SPPath; namespace Inkscape { namespace XML { class Node; } @@ -56,7 +56,7 @@ public: PathManipulator(MultiPathManipulator &mpm, SPPath *path, Geom::Affine const &edit_trans, guint32 outline_color, Glib::ustring lpe_key); ~PathManipulator(); - virtual bool event(SPEventContext *, GdkEvent *); + virtual bool event(Inkscape::UI::Tools::ToolBase *, GdkEvent *); bool empty(); void writeXML(); @@ -86,6 +86,7 @@ public: void showPathDirection(bool show); void setLiveOutline(bool set); void setLiveObjects(bool set); + void updateHandles(); void setControlsTransform(Geom::Affine const &); void hideDragPoint(); MultiPathManipulator &mpm() { return _multi_path_manipulator; } @@ -130,7 +131,7 @@ private: SubpathList _subpaths; MultiPathManipulator &_multi_path_manipulator; - SPPath *_path; + SPPath *_path; ///< can be an SPPath or an Inkscape::LivePathEffect::Effect !!! SPCurve *_spcurve; // in item coordinates SPCanvasItem *_outline; CurveDragPoint *_dragpoint; // an invisible control point hoverng over curve diff --git a/src/ui/tool/selectable-control-point.cpp b/src/ui/tool/selectable-control-point.cpp index cec2e7b07..f3f9c0e1e 100644 --- a/src/ui/tool/selectable-control-point.cpp +++ b/src/ui/tool/selectable-control-point.cpp @@ -1,8 +1,6 @@ -/** @file - * Desktop-bound selectable control object - implementation - */ /* Authors: * Krzysztof Kosiński <tweenk.pl@gmail.com> + * Jon A. Cruz <jon@joncruz.org> * * Copyright (C) 2009 Authors * Released under GNU GPL, read the file 'COPYING' for more information @@ -15,34 +13,32 @@ namespace Inkscape { namespace UI { -static SelectableControlPoint::ColorSet default_scp_color_set = { - { - {0xffffff00, 0x01000000}, // normal fill, stroke - {0xff0000ff, 0x01000000}, // mouseover fill, stroke - {0x0000ffff, 0x01000000} // clicked fill, stroke - }, +ControlPoint::ColorSet SelectableControlPoint::_default_scp_color_set = { + {0xffffff00, 0x01000000}, // normal fill, stroke + {0xff0000ff, 0x01000000}, // mouseover fill, stroke + {0x0000ffff, 0x01000000}, // clicked fill, stroke + // {0x0000ffff, 0x000000ff}, // normal fill, stroke when selected {0xff000000, 0x000000ff}, // mouseover fill, stroke when selected {0xff000000, 0x000000ff} // clicked fill, stroke when selected }; -SelectableControlPoint::SelectableControlPoint(SPDesktop *d, Geom::Point const &initial_pos, - SPAnchorType anchor, SPCtrlShapeType shape, unsigned int size, - ControlPointSelection &sel, ColorSet *cset, SPCanvasGroup *group) - : ControlPoint (d, initial_pos, anchor, shape, size, - cset ? reinterpret_cast<ControlPoint::ColorSet*>(cset) - : reinterpret_cast<ControlPoint::ColorSet*>(&default_scp_color_set), group) - , _selection (sel) +SelectableControlPoint::SelectableControlPoint(SPDesktop *d, Geom::Point const &initial_pos, SPAnchorType anchor, + Inkscape::ControlType type, + ControlPointSelection &sel, + ColorSet const &cset, SPCanvasGroup *group) : + ControlPoint(d, initial_pos, anchor, type, cset, group), + _selection(sel) { _selection.allPoints().insert(this); } -SelectableControlPoint::SelectableControlPoint(SPDesktop *d, Geom::Point const &initial_pos, - SPAnchorType anchor, Glib::RefPtr<Gdk::Pixbuf> pixbuf, - ControlPointSelection &sel, ColorSet *cset, SPCanvasGroup *group) - : ControlPoint (d, initial_pos, anchor, pixbuf, - cset ? reinterpret_cast<ControlPoint::ColorSet*>(cset) - : reinterpret_cast<ControlPoint::ColorSet*>(&default_scp_color_set), group) - , _selection (sel) + +SelectableControlPoint::SelectableControlPoint(SPDesktop *d, Geom::Point const &initial_pos, SPAnchorType anchor, + Glib::RefPtr<Gdk::Pixbuf> pixbuf, + ControlPointSelection &sel, + ColorSet const &cset, SPCanvasGroup *group) : + ControlPoint(d, initial_pos, anchor, pixbuf, cset, group), + _selection (sel) { _selection.allPoints().insert(this); } @@ -107,21 +103,23 @@ void SelectableControlPoint::_setState(State state) { if (!selected()) { ControlPoint::_setState(state); - return; - } - - ColorSet *cset = reinterpret_cast<ColorSet*>(_cset); - ColorEntry current = {0, 0}; - switch (state) { - case STATE_NORMAL: - current = cset->selected_normal; break; - case STATE_MOUSEOVER: - current = cset->selected_mouseover; break; - case STATE_CLICKED: - current = cset->selected_clicked; break; + } else { + ColorEntry current = {0, 0}; + ColorSet const &activeCset = (_isLurking()) ? invisible_cset : _cset; + switch (state) { + case STATE_NORMAL: + current = activeCset.selected_normal; + break; + case STATE_MOUSEOVER: + current = activeCset.selected_mouseover; + break; + case STATE_CLICKED: + current = activeCset.selected_clicked; + break; + } + _setColors(current); + _state = state; } - _setColors(current); - _state = state; } } // namespace UI diff --git a/src/ui/tool/selectable-control-point.h b/src/ui/tool/selectable-control-point.h index 8ecb39a79..8acfc1168 100644 --- a/src/ui/tool/selectable-control-point.h +++ b/src/ui/tool/selectable-control-point.h @@ -1,8 +1,6 @@ -/** @file - * Desktop-bound selectable control object - */ /* Authors: * Krzysztof Kosiński <tweenk.pl@gmail.com> + * Jon A. Cruz <jon@joncruz.org> * * Copyright (C) 2009 Authors * Released under GNU GPL, read the file 'COPYING' for more information @@ -18,40 +16,45 @@ namespace UI { class ControlPointSelection; +/** + * Desktop-bound selectable control object. + */ class SelectableControlPoint : public ControlPoint { public: - struct ColorSet { - ControlPoint::ColorSet cpset; - ColorEntry selected_normal; - ColorEntry selected_mouseover; - ColorEntry selected_clicked; - }; ~SelectableControlPoint(); bool selected() const; - void updateState() const { const_cast<SelectableControlPoint*>(this)->_setState(_state); } - virtual Geom::Rect bounds() { + void updateState() { _setState(_state); } + virtual Geom::Rect bounds() const { return Geom::Rect(position(), position()); } + protected: - SelectableControlPoint(SPDesktop *d, Geom::Point const &initial_pos, - SPAnchorType anchor, SPCtrlShapeType shape, - unsigned int size, ControlPointSelection &sel, ColorSet *cset = 0, - SPCanvasGroup *group = 0); - SelectableControlPoint(SPDesktop *d, Geom::Point const &initial_pos, - SPAnchorType anchor, Glib::RefPtr<Gdk::Pixbuf> pixbuf, - ControlPointSelection &sel, ColorSet *cset = 0, SPCanvasGroup *group = 0); + + SelectableControlPoint(SPDesktop *d, Geom::Point const &initial_pos, SPAnchorType anchor, + Inkscape::ControlType type, + ControlPointSelection &sel, + ColorSet const &cset = _default_scp_color_set, SPCanvasGroup *group = 0); + + SelectableControlPoint(SPDesktop *d, Geom::Point const &initial_pos, SPAnchorType anchor, + Glib::RefPtr<Gdk::Pixbuf> pixbuf, + ControlPointSelection &sel, + ColorSet const &cset = _default_scp_color_set, SPCanvasGroup *group = 0); virtual void _setState(State state); - virtual void dragged(Geom::Point &, GdkEventMotion *); - virtual bool grabbed(GdkEventMotion *); - virtual void ungrabbed(GdkEventButton *); - virtual bool clicked(GdkEventButton *); + virtual void dragged(Geom::Point &new_pos, GdkEventMotion *event); + virtual bool grabbed(GdkEventMotion *event); + virtual void ungrabbed(GdkEventButton *event); + virtual bool clicked(GdkEventButton *event); ControlPointSelection &_selection; + private: + void _takeSelection(); + + static ColorSet _default_scp_color_set; }; } // namespace UI diff --git a/src/ui/tool/selector.cpp b/src/ui/tool/selector.cpp index 364776ce4..bdeacadc9 100644 --- a/src/ui/tool/selector.cpp +++ b/src/ui/tool/selector.cpp @@ -3,6 +3,7 @@ */ /* Authors: * Krzysztof Kosiński <tweenk.pl@gmail.com> + * Jon A. Cruz <jon@joncruz.org> * * Copyright (C) 2009 Authors * Released under GNU GPL, read the file 'COPYING' for more information @@ -12,17 +13,13 @@ #include "desktop.h" #include "desktop-handles.h" #include "display/sodipodi-ctrlrect.h" -#include "event-context.h" +#include "ui/tools/tool-base.h" #include "preferences.h" #include "ui/tool/event-utils.h" #include "ui/tool/selector.h" #include <gdk/gdkkeysyms.h> -#if !GTK_CHECK_VERSION(2,22,0) -#include "compat-key-syms.h" -#endif - namespace Inkscape { namespace UI { @@ -32,27 +29,31 @@ namespace UI { * is pressed, it grabs events and handles drags and clicks in the usual way. */ class SelectorPoint : public ControlPoint { public: - SelectorPoint(SPDesktop *d, SPCanvasGroup *group, Selector *s) - : ControlPoint(d, Geom::Point(0,0), SP_ANCHOR_CENTER, SP_CTRL_SHAPE_SQUARE, - 1, &invisible_cset, group) - , _selector(s) - , _cancel(false) + SelectorPoint(SPDesktop *d, SPCanvasGroup *group, Selector *s) : + ControlPoint(d, Geom::Point(0,0), SP_ANCHOR_CENTER, + CTRL_TYPE_INVISIPOINT, + invisible_cset, group), + _selector(s), + _cancel(false) { setVisible(false); _rubber = static_cast<CtrlRect*>(sp_canvas_item_new(sp_desktop_controls(_desktop), SP_TYPE_CTRLRECT, NULL)); sp_canvas_item_hide(_rubber); } + ~SelectorPoint() { - gtk_object_destroy(_rubber); + sp_canvas_item_destroy(_rubber); } + SPDesktop *desktop() { return _desktop; } - bool event(SPEventContext *ec, GdkEvent *e) { + + bool event(Inkscape::UI::Tools::ToolBase *ec, GdkEvent *e) { return _eventHandler(ec, e); } protected: - virtual bool _eventHandler(SPEventContext *event_context, GdkEvent *event) { + virtual bool _eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event) { if (event->type == GDK_KEY_PRESS && shortcut_key(event->key) == GDK_KEY_Escape && sp_canvas_item_is_visible(_rubber)) { @@ -70,22 +71,26 @@ private: sp_canvas_item_show(_rubber); return false; } + virtual void dragged(Geom::Point &new_pos, GdkEventMotion *) { if (_cancel) return; Geom::Rect sel(_start, new_pos); _rubber->setRectangle(sel); } + virtual void ungrabbed(GdkEventButton *event) { if (_cancel) return; sp_canvas_item_hide(_rubber); Geom::Rect sel(_start, position()); _selector->signal_area.emit(sel, event); } + virtual bool clicked(GdkEventButton *event) { if (event->button != 1) return false; _selector->signal_point.emit(position(), event); return true; } + CtrlRect *_rubber; Selector *_selector; Geom::Point _start; @@ -105,7 +110,7 @@ Selector::~Selector() delete _dragger; } -bool Selector::event(SPEventContext *event_context, GdkEvent *event) +bool Selector::event(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event) { // The hidden control point will capture all events after it obtains the grab, // but it relies on this function to initiate it. If we pass only first button @@ -113,7 +118,7 @@ bool Selector::event(SPEventContext *event_context, GdkEvent *event) switch (event->type) { case GDK_BUTTON_PRESS: // Do not pass button presses other than left button to the control point. - // This way middle click and right click can be handled in SPEventContext. + // This way middle click and right click can be handled in ToolBase. if (event->button.button == 1 && !event_context->space_panning) { _dragger->setPosition(_desktop->w2d(event_point(event->motion))); return _dragger->event(event_context, event); diff --git a/src/ui/tool/selector.h b/src/ui/tool/selector.h index 7e2759b69..dbe751ede 100644 --- a/src/ui/tool/selector.h +++ b/src/ui/tool/selector.h @@ -28,7 +28,7 @@ class Selector : public Manipulator { public: Selector(SPDesktop *d); virtual ~Selector(); - virtual bool event(SPEventContext *, GdkEvent *); + virtual bool event(Inkscape::UI::Tools::ToolBase *, GdkEvent *); sigc::signal<void, Geom::Rect const &, GdkEventButton*> signal_area; sigc::signal<void, Geom::Point const &, GdkEventButton*> signal_point; diff --git a/src/ui/tool/transform-handle-set.cpp b/src/ui/tool/transform-handle-set.cpp index b4a27170a..7d5c9bf0c 100644 --- a/src/ui/tool/transform-handle-set.cpp +++ b/src/ui/tool/transform-handle-set.cpp @@ -3,6 +3,7 @@ */ /* Authors: * Krzysztof Kosiński <tweenk.pl@gmail.com> + * Jon A. Cruz <jon@joncruz.org> * * Copyright (C) 2009 Authors * Released under GNU GPL, read the file 'COPYING' for more information @@ -25,7 +26,7 @@ #include "ui/tool/selectable-control-point.h" #include "ui/tool/event-utils.h" #include "ui/tool/transform-handle-set.h" -#include "ui/tool/node-tool.h" +#include "ui/tools/node-tool.h" #include "ui/tool/node.h" #include "seltrans.h" @@ -38,6 +39,7 @@ namespace Inkscape { namespace UI { namespace { + SPAnchorType corner_to_anchor(unsigned c) { switch (c % 4) { case 0: return SP_ANCHOR_NE; @@ -46,6 +48,7 @@ SPAnchorType corner_to_anchor(unsigned c) { default: return SP_ANCHOR_SE; } } + SPAnchorType side_to_anchor(unsigned s) { switch (s % 4) { case 0: return SP_ANCHOR_N; @@ -62,30 +65,30 @@ double snap_angle(double a) { double unit_angle = M_PI / snaps; return CLAMP(unit_angle * round(a / unit_angle), -M_PI, M_PI); } + double snap_increment_degrees() { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000); return 180.0 / snaps; } -ControlPoint::ColorSet thandle_cset = { +} // anonymous namespace + +ControlPoint::ColorSet TransformHandle::thandle_cset = { + {0x000000ff, 0x000000ff}, + {0x00ff6600, 0x000000ff}, + {0x00ff6600, 0x000000ff}, + // {0x000000ff, 0x000000ff}, {0x00ff6600, 0x000000ff}, {0x00ff6600, 0x000000ff} }; -ControlPoint::ColorSet center_cset = { - {0x00000000, 0x000000ff}, - {0x00000000, 0xff0000b0}, - {0x00000000, 0xff0000b0} -}; -} // anonymous namespace - -/** Base class for node transform handles to simplify implementation */ -TransformHandle::TransformHandle(TransformHandleSet &th, SPAnchorType anchor, Glib::RefPtr<Gdk::Pixbuf> pb) - : ControlPoint(th._desktop, Geom::Point(), anchor, pb, &thandle_cset, - th._transform_handle_group) - , _th(th) +TransformHandle::TransformHandle(TransformHandleSet &th, SPAnchorType anchor, Glib::RefPtr<Gdk::Pixbuf> pb) : + ControlPoint(th._desktop, Geom::Point(), anchor, + pb, + thandle_cset, th._transform_handle_group), + _th(th) { setVisible(false); } @@ -121,12 +124,13 @@ bool TransformHandle::grabbed(GdkEventMotion *) startTransform(); _th._setActiveHandle(this); - _cset = &invisible_cset; + _setLurking(true); _setState(_state); // Collect the snap-candidates, one for each selected node. These will be stored in the _snap_points vector. - InkNodeTool *nt = INK_NODE_TOOL(_th._desktop->event_context); - ControlPointSelection *selection = nt->_selected_nodes.get(); + Inkscape::UI::Tools::NodeTool *nt = INK_NODE_TOOL(_th._desktop->event_context); + //ControlPointSelection *selection = nt->_selected_nodes.get(); + ControlPointSelection* selection = nt->_selected_nodes; selection->setOriginalPoints(); selection->getOriginalPoints(_snap_points); @@ -171,7 +175,7 @@ void TransformHandle::ungrabbed(GdkEventButton *) { _snap_points.clear(); _th._clearActiveHandle(); - _cset = &thandle_cset; + _setLurking(false); _setState(_state); endTransform(); _th.signal_commit.emit(getCommitEvent()); @@ -184,7 +188,7 @@ public: : TransformHandle(th, anchor, pb) {} protected: - virtual Glib::ustring _getTip(unsigned state) { + virtual Glib::ustring _getTip(unsigned state) const { if (state_held_control(state)) { if (state_held_shift(state)) { return C_("Transform handle tip", @@ -205,31 +209,36 @@ protected: return C_("Transform handle tip", "<b>Scale handle</b>: drag to scale the selection"); } - virtual Glib::ustring _getDragTip(GdkEventMotion */*event*/) { + virtual Glib::ustring _getDragTip(GdkEventMotion */*event*/) const { return format_tip(C_("Transform handle tip", "Scale by %.2f%% x %.2f%%"), _last_scale_x * 100, _last_scale_y * 100); } - virtual bool _hasDragTips() { return true; } + virtual bool _hasDragTips() const { return true; } static double _last_scale_x, _last_scale_y; }; double ScaleHandle::_last_scale_x = 1.0; double ScaleHandle::_last_scale_y = 1.0; -/// Corner scaling handle for node transforms +/** + * Corner scaling handle for node transforms. + */ class ScaleCornerHandle : public ScaleHandle { public: - ScaleCornerHandle(TransformHandleSet &th, unsigned corner) - : ScaleHandle(th, corner_to_anchor(corner), _corner_to_pixbuf(corner)) - , _corner(corner) + + ScaleCornerHandle(TransformHandleSet &th, unsigned corner) : + ScaleHandle(th, corner_to_anchor(corner), _corner_to_pixbuf(corner)), + _corner(corner) {} + protected: virtual void startTransform() { _sc_center = _th.rotationCenter(); _sc_opposite = _th.bounds().corner(_corner + 2); _last_scale_x = _last_scale_y = 1.0; } + virtual Geom::Affine computeTransform(Geom::Point const &new_pos, GdkEventMotion *event) { Geom::Point scc = held_shift(*event) ? _sc_center : _sc_opposite; Geom::Point vold = _origin - scc, vnew = new_pos - scc; @@ -275,25 +284,35 @@ protected: * Geom::Translate(scc); return t; } + virtual CommitEvent getCommitEvent() { return _last_transform.isUniformScale() ? COMMIT_MOUSE_SCALE_UNIFORM : COMMIT_MOUSE_SCALE; } + private: + static Glib::RefPtr<Gdk::Pixbuf> _corner_to_pixbuf(unsigned c) { - sp_select_context_get_type(); + //sp_select_context_get_type(); switch (c % 2) { - case 0: return Glib::wrap(handles[1], true); - default: return Glib::wrap(handles[0], true); + case 0: + return Glib::wrap(handles[1], true); + break; + default: + return Glib::wrap(handles[0], true); + break; } } + Geom::Point _sc_center; Geom::Point _sc_opposite; unsigned _corner; }; -/// Side scaling handle for node transforms +/** + * Side scaling handle for node transforms. + */ class ScaleSideHandle : public ScaleHandle { public: ScaleSideHandle(TransformHandleSet &th, unsigned side) @@ -358,7 +377,7 @@ protected: } private: static Glib::RefPtr<Gdk::Pixbuf> _side_to_pixbuf(unsigned c) { - sp_select_context_get_type(); + //sp_select_context_get_type(); switch (c % 2) { case 0: return Glib::wrap(handles[3], true); default: return Glib::wrap(handles[2], true); @@ -369,7 +388,9 @@ private: unsigned _side; }; -/// Rotation handle for node transforms +/** + * Rotation handle for node transforms. + */ class RotateHandle : public TransformHandle { public: RotateHandle(TransformHandleSet &th, unsigned corner) @@ -410,7 +431,7 @@ protected: virtual CommitEvent getCommitEvent() { return COMMIT_MOUSE_ROTATE; } - virtual Glib::ustring _getTip(unsigned state) { + virtual Glib::ustring _getTip(unsigned state) const { if (state_held_shift(state)) { if (state_held_control(state)) { return format_tip(C_("Transform handle tip", @@ -427,20 +448,20 @@ protected: "the selection around the rotation center"); } - virtual Glib::ustring _getDragTip(GdkEventMotion */*event*/) { + virtual Glib::ustring _getDragTip(GdkEventMotion */*event*/) const { return format_tip(C_("Transform handle tip", "Rotate by %.2f°"), - _last_angle * 360.0); + _last_angle * 180.0 / M_PI); } - virtual bool _hasDragTips() { return true; } + virtual bool _hasDragTips() const { return true; } private: static Glib::RefPtr<Gdk::Pixbuf> _corner_to_pixbuf(unsigned c) { - sp_select_context_get_type(); + //sp_select_context_get_type(); switch (c % 4) { - case 0: return Glib::wrap(handles[10], true); - case 1: return Glib::wrap(handles[8], true); - case 2: return Glib::wrap(handles[6], true); + case 0: return Glib::wrap(handles[7], true); + case 1: return Glib::wrap(handles[6], true); + case 2: return Glib::wrap(handles[5], true); default: return Glib::wrap(handles[4], true); } } @@ -550,7 +571,7 @@ protected: : COMMIT_MOUSE_SKEW_X; } - virtual Glib::ustring _getTip(unsigned state) { + virtual Glib::ustring _getTip(unsigned state) const { if (state_held_shift(state)) { if (state_held_control(state)) { return format_tip(C_("Transform handle tip", @@ -568,7 +589,7 @@ protected: "the opposite handle"); } - virtual Glib::ustring _getDragTip(GdkEventMotion */*event*/) { + virtual Glib::ustring _getDragTip(GdkEventMotion */*event*/) const { if (_last_horizontal) { return format_tip(C_("Transform handle tip", "Skew horizontally by %.2f°"), _last_angle * 360.0); @@ -578,16 +599,16 @@ protected: } } - virtual bool _hasDragTips() { return true; } + virtual bool _hasDragTips() const { return true; } private: static Glib::RefPtr<Gdk::Pixbuf> _side_to_pixbuf(unsigned s) { - sp_select_context_get_type(); + //sp_select_context_get_type(); switch (s % 4) { - case 0: return Glib::wrap(handles[9], true); - case 1: return Glib::wrap(handles[7], true); - case 2: return Glib::wrap(handles[5], true); + case 0: return Glib::wrap(handles[10], true); + case 1: return Glib::wrap(handles[9], true); + case 2: return Glib::wrap(handles[8], true); default: return Glib::wrap(handles[11], true); } } @@ -601,11 +622,13 @@ bool SkewHandle::_last_horizontal = false; double SkewHandle::_last_angle = 0; class RotationCenter : public ControlPoint { + public: - RotationCenter(TransformHandleSet &th) - : ControlPoint(th._desktop, Geom::Point(), SP_ANCHOR_CENTER, _get_pixbuf(), - ¢er_cset, th._transform_handle_group) - , _th(th) + RotationCenter(TransformHandleSet &th) : + ControlPoint(th._desktop, Geom::Point(), SP_ANCHOR_CENTER, + _get_pixbuf(), + _center_cset, th._transform_handle_group), + _th(th) { setVisible(false); } @@ -628,7 +651,7 @@ protected: } sm.unSetup(); } - virtual Glib::ustring _getTip(unsigned /*state*/) { + virtual Glib::ustring _getTip(unsigned /*state*/) const { return C_("Transform handle tip", "<b>Rotation center</b>: drag to change the origin of transforms"); } @@ -636,13 +659,25 @@ protected: private: static Glib::RefPtr<Gdk::Pixbuf> _get_pixbuf() { - sp_select_context_get_type(); + //sp_select_context_get_type(); return Glib::wrap(handles[12], true); } + static ColorSet _center_cset; TransformHandleSet &_th; }; +ControlPoint::ColorSet RotationCenter::_center_cset = { + {0x00000000, 0x000000ff}, + {0x00000000, 0xff0000b0}, + {0x00000000, 0xff0000b0}, + // + {0x00000000, 0x000000ff}, + {0x00000000, 0xff0000b0}, + {0x00000000, 0xff0000b0} +}; + + TransformHandleSet::TransformHandleSet(SPDesktop *d, SPCanvasGroup *th_group) : Manipulator(d) , _active(0) @@ -674,18 +709,22 @@ TransformHandleSet::~TransformHandleSet() } } -/** Sets the mode of transform handles (scale or rotate). */ void TransformHandleSet::setMode(Mode m) { _mode = m; _updateVisibility(_visible); } -Geom::Rect TransformHandleSet::bounds() +Geom::Rect TransformHandleSet::bounds() const { return Geom::Rect(*_scale_corners[0], *_scale_corners[2]); } +ControlPoint const &TransformHandleSet::rotationCenter() const +{ + return *_center; +} + ControlPoint &TransformHandleSet::rotationCenter() { return *_center; @@ -715,7 +754,7 @@ void TransformHandleSet::setBounds(Geom::Rect const &r, bool preserve_center) } } -bool TransformHandleSet::event(SPEventContext *, GdkEvent*) +bool TransformHandleSet::event(Inkscape::UI::Tools::ToolBase *, GdkEvent*) { return false; } @@ -746,9 +785,6 @@ void TransformHandleSet::_clearActiveHandle() _updateVisibility(_visible); } -/** Update the visibility of transformation handles according to settings and the dimensions - * of the bounding box. It hides the handles that would have no effect or lead to - * discontinuities. Additionally, side handles for which there is no space are not shown. */ void TransformHandleSet::_updateVisibility(bool v) { if (v) { diff --git a/src/ui/tool/transform-handle-set.h b/src/ui/tool/transform-handle-set.h index cd1a61da2..54f81adf5 100644 --- a/src/ui/tool/transform-handle-set.h +++ b/src/ui/tool/transform-handle-set.h @@ -3,6 +3,7 @@ */ /* Authors: * Krzysztof Kosiński <tweenk.pl@gmail.com> + * Jon A. Cruz <jon@joncruz.org> * * Copyright (C) 2009 Authors * Released under GNU GPL, read the file 'COPYING' for more information @@ -23,7 +24,6 @@ class CtrlRect; namespace Inkscape { namespace UI { -//class TransformHandle; class RotateHandle; class SkewHandle; class ScaleCornerHandle; @@ -32,6 +32,7 @@ class RotationCenter; class TransformHandleSet : public Manipulator { public: + enum Mode { MODE_SCALE, MODE_ROTATE_SKEW @@ -39,25 +40,39 @@ public: TransformHandleSet(SPDesktop *d, SPCanvasGroup *th_group); virtual ~TransformHandleSet(); - virtual bool event(SPEventContext *, GdkEvent *); + virtual bool event(Inkscape::UI::Tools::ToolBase *, GdkEvent *); - bool visible() { return _visible; } - Mode mode() { return _mode; } - Geom::Rect bounds(); + bool visible() const { return _visible; } + Mode mode() const { return _mode; } + Geom::Rect bounds() const; void setVisible(bool v); - void setMode(Mode); + + /** Sets the mode of transform handles (scale or rotate). */ + void setMode(Mode m); + void setBounds(Geom::Rect const &, bool preserve_center = false); bool transforming() { return _in_transform; } + + ControlPoint const &rotationCenter() const; ControlPoint &rotationCenter(); sigc::signal<void, Geom::Affine const &> signal_transform; sigc::signal<void, CommitEvent> signal_commit; + private: + void _emitTransform(Geom::Affine const &); void _setActiveHandle(ControlPoint *h); void _clearActiveHandle(); + + /** Update the visibility of transformation handles according to settings and the dimensions + * of the bounding box. It hides the handles that would have no effect or lead to + * discontinuities. Additionally, side handles for which there is no space are not shown. + */ void _updateVisibility(bool v); + + // TODO unions must GO AWAY: union { ControlPoint *_handles[17]; struct { @@ -68,6 +83,7 @@ private: RotationCenter *_center; }; }; + ControlPoint *_active; SPCanvasGroup *_transform_handle_group; CtrlRect *_trans_outline; @@ -79,8 +95,9 @@ private: friend class RotationCenter; }; -/** Base class for node transform handles to simplify implementation */ -class TransformHandle : public ControlPoint { +/** Base class for node transform handles to simplify implementation. */ +class TransformHandle : public ControlPoint +{ public: TransformHandle(TransformHandleSet &th, SPAnchorType anchor, Glib::RefPtr<Gdk::Pixbuf> pb); void getNextClosestPoint(bool reverse); @@ -103,6 +120,8 @@ private: virtual bool grabbed(GdkEventMotion *); virtual void dragged(Geom::Point &new_pos, GdkEventMotion *event); virtual void ungrabbed(GdkEventButton *); + + static ColorSet thandle_cset; }; } // namespace UI diff --git a/src/ui/tools/Makefile_insert b/src/ui/tools/Makefile_insert new file mode 100644 index 000000000..cd09a3230 --- /dev/null +++ b/src/ui/tools/Makefile_insert @@ -0,0 +1,28 @@ +## Makefile.am fragment sourced by src/Makefile.am. + +ink_common_sources += \ + ui/tools/arc-tool.cpp ui/tools/arc-tool.h \ + ui/tools/box3d-tool.cpp ui/tools/box3d-tool.h \ + ui/tools/calligraphic-tool.cpp ui/tools/calligraphic-tool.h \ + ui/tools/connector-tool.cpp ui/tools/connector-tool.h \ + ui/tools/dropper-tool.cpp ui/tools/dropper-tool.h \ + ui/tools/dynamic-base.cpp ui/tools/dynamic-base.h \ + ui/tools/eraser-tool.cpp ui/tools/eraser-tool.h \ + ui/tools/flood-tool.cpp ui/tools/flood-tool.h \ + ui/tools/freehand-base.cpp ui/tools/freehand-base.h \ + ui/tools/gradient-tool.cpp ui/tools/gradient-tool.h \ + ui/tools/lpe-tool.cpp ui/tools/lpe-tool.h \ + ui/tools/measure-tool.cpp ui/tools/measure-tool.h \ + ui/tools/mesh-tool.cpp ui/tools/mesh-tool.h \ + ui/tools/node-tool.cpp ui/tools/node-tool.h \ + ui/tools/pen-tool.cpp ui/tools/pen-tool.h \ + ui/tools/pencil-tool.cpp ui/tools/pencil-tool.h \ + ui/tools/rect-tool.cpp ui/tools/rect-tool.h \ + ui/tools/select-tool.cpp ui/tools/select-tool.h \ + ui/tools/spiral-tool.cpp ui/tools/spiral-tool.h \ + ui/tools/spray-tool.cpp ui/tools/spray-tool.h \ + ui/tools/star-tool.cpp ui/tools/star-tool.h \ + ui/tools/text-tool.cpp ui/tools/text-tool.h \ + ui/tools/tool-base.cpp ui/tools/tool-base.h \ + ui/tools/tweak-tool.cpp ui/tools/tweak-tool.h \ + ui/tools/zoom-tool.cpp ui/tools/zoom-tool.h
\ No newline at end of file diff --git a/src/ui/tools/arc-tool.cpp b/src/ui/tools/arc-tool.cpp new file mode 100644 index 000000000..43f8eb9e1 --- /dev/null +++ b/src/ui/tools/arc-tool.cpp @@ -0,0 +1,486 @@ +/** + * @file + * Ellipse drawing context. + */ +/* Authors: + * Mitsuru Oka + * Lauris Kaplinski <lauris@kaplinski.com> + * bulia byak <buliabyak@users.sf.net> + * Johan Engelen <johan@shouraizou.nl> + * Abhishek Sharma + * Jon A. Cruz <jon@joncruz.org> + * + * Copyright (C) 2000-2006 Authors + * Copyright (C) 2000-2001 Ximian, Inc. + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif +#include <gdk/gdkkeysyms.h> + +#include "macros.h" +#include <glibmm/i18n.h> +#include "display/sp-canvas.h" +#include "sp-ellipse.h" +#include "document.h" +#include "document-undo.h" +#include "sp-namedview.h" +#include "selection.h" +#include "desktop-handles.h" +#include "snap.h" +#include "pixmaps/cursor-ellipse.xpm" +#include "xml/repr.h" +#include "xml/node-event-vector.h" +#include "preferences.h" +#include "message-context.h" +#include "desktop.h" +#include "desktop-style.h" +#include "context-fns.h" +#include "verbs.h" +#include "shape-editor.h" +#include "ui/tools/tool-base.h" + +#include "ui/tools/arc-tool.h" +#include "display/sp-canvas-item.h" + +using Inkscape::DocumentUndo; + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +namespace { + ToolBase* createArcContext() { + return new ArcTool(); + } + + bool arcContextRegistered = ToolFactory::instance().registerObject("/tools/shapes/arc", createArcContext); +} + +const std::string& ArcTool::getPrefsPath() { + return ArcTool::prefsPath; +} + +const std::string ArcTool::prefsPath = "/tools/shapes/arc"; + + +ArcTool::ArcTool() + : ToolBase(cursor_ellipse_xpm, 4, 4) + , arc(NULL) +{ +} + +void ArcTool::finish() { + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), GDK_CURRENT_TIME); + this->finishItem(); + this->sel_changed_connection.disconnect(); + + ToolBase::finish(); +} + +ArcTool::~ArcTool() { + this->enableGrDrag(false); + + this->sel_changed_connection.disconnect(); + + delete this->shape_editor; + this->shape_editor = NULL; + + /* fixme: This is necessary because we do not grab */ + if (this->arc) { + this->finishItem(); + } +} + +/** + * Callback that processes the "changed" signal on the selection; + * destroys old and creates new knotholder. + */ +void ArcTool::selection_changed(Inkscape::Selection* selection) { + this->shape_editor->unset_item(SH_KNOTHOLDER); + this->shape_editor->set_item(selection->singleItem(), SH_KNOTHOLDER); +} + +void ArcTool::setup() { + ToolBase::setup(); + + Inkscape::Selection *selection = sp_desktop_selection(this->desktop); + + this->shape_editor = new ShapeEditor(this->desktop); + + SPItem *item = sp_desktop_selection(this->desktop)->singleItem(); + if (item) { + this->shape_editor->set_item(item, SH_KNOTHOLDER); + } + + this->sel_changed_connection.disconnect(); + this->sel_changed_connection = selection->connectChanged( + sigc::mem_fun(this, &ArcTool::selection_changed) + ); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/tools/shapes/selcue")) { + this->enableSelectionCue(); + } + + if (prefs->getBool("/tools/shapes/gradientdrag")) { + this->enableGrDrag(); + } +} + +bool ArcTool::item_handler(SPItem* item, GdkEvent* event) { + switch (event->type) { + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + Inkscape::setup_for_drag_start(desktop, this, event); + } + break; + // motion and release are always on root (why?) + default: + break; + } + + return ToolBase::item_handler(item, event); +} + +bool ArcTool::root_handler(GdkEvent* event) { + static bool dragging; + + Inkscape::Selection *selection = sp_desktop_selection(desktop); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + this->tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + + bool handled = false; + + switch (event->type) { + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + dragging = true; + + this->center = Inkscape::setup_for_drag_start(desktop, this, event); + + /* Snap center */ + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + m.freeSnapReturnByRef(this->center, Inkscape::SNAPSOURCE_NODE_HANDLE); + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + GDK_KEY_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | + GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK, + NULL, event->button.time); + handled = true; + m.unSetup(); + } + break; + case GDK_MOTION_NOTIFY: + if (dragging && (event->motion.state & GDK_BUTTON1_MASK) && !this->space_panning) { + if ( this->within_tolerance + && ( abs( (gint) event->motion.x - this->xp ) < this->tolerance ) + && ( abs( (gint) event->motion.y - this->yp ) < this->tolerance ) ) { + break; // do not drag if we're within tolerance from origin + } + // Once the user has moved farther than tolerance from the original location + // (indicating they intend to draw, not click), then always process the + // motion notify coordinates as given (no snapping back to origin) + this->within_tolerance = false; + + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); + + this->drag(motion_dt, event->motion.state); + + gobble_motion_events(GDK_BUTTON1_MASK); + + handled = true; + } else if (!this->sp_event_context_knot_mouseover()){ + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); + m.preSnap(Inkscape::SnapCandidatePoint(motion_dt, Inkscape::SNAPSOURCE_NODE_HANDLE)); + m.unSetup(); + } + break; + case GDK_BUTTON_RELEASE: + this->xp = this->yp = 0; + if (event->button.button == 1 && !this->space_panning) { + dragging = false; + sp_event_context_discard_delayed_snap_event(this); + + if (!this->within_tolerance) { + // we've been dragging, finish the arc + this->finishItem(); + } else if (this->item_to_select) { + // no dragging, select clicked item if any + if (event->button.state & GDK_SHIFT_MASK) { + selection->toggle(this->item_to_select); + } else { + selection->set(this->item_to_select); + } + } else { + // click in an empty space + selection->clear(); + } + + this->xp = 0; + this->yp = 0; + this->item_to_select = NULL; + handled = true; + } + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time); + break; + + case GDK_KEY_PRESS: + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + case GDK_KEY_Meta_L: // Meta is when you press Shift+Alt (at least on my machine) + case GDK_KEY_Meta_R: + if (!dragging) { + sp_event_show_modifier_tip(this->defaultMessageContext(), event, + _("<b>Ctrl</b>: make circle or integer-ratio ellipse, snap arc/segment angle"), + _("<b>Shift</b>: draw around the starting point"), + NULL); + } + break; + + case GDK_KEY_Up: + case GDK_KEY_Down: + case GDK_KEY_KP_Up: + case GDK_KEY_KP_Down: + // prevent the zoom field from activation + if (!MOD__CTRL_ONLY(event)) + handled = true; + break; + + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo ("altx-arc"); + handled = true; + } + break; + + case GDK_KEY_Escape: + if (dragging) { + dragging = false; + sp_event_context_discard_delayed_snap_event(this); + // if drawing, cancel, otherwise pass it up for deselecting + this->cancel(); + handled = true; + } + break; + + case GDK_KEY_space: + if (dragging) { + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time); + dragging = false; + sp_event_context_discard_delayed_snap_event(this); + + if (!this->within_tolerance) { + // we've been dragging, finish the arc + this->finishItem(); + } + // do not return true, so that space would work switching to selector + } + break; + + case GDK_KEY_Delete: + case GDK_KEY_KP_Delete: + case GDK_KEY_BackSpace: + handled = this->deleteSelectedDrag(MOD__CTRL_ONLY(event)); + break; + + default: + break; + } + break; + + case GDK_KEY_RELEASE: + switch (event->key.keyval) { + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + case GDK_KEY_Meta_L: // Meta is when you press Shift+Alt + case GDK_KEY_Meta_R: + this->defaultMessageContext()->clear(); + break; + + default: + break; + } + break; + + default: + break; + } + + if (!handled) { + handled = ToolBase::root_handler(event); + } + + return handled; +} + +void ArcTool::drag(Geom::Point pt, guint state) { + if (!this->arc) { + if (Inkscape::have_viable_layer(desktop, this->message_context) == false) { + return; + } + + // Create object + Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); + Inkscape::XML::Node *repr = xml_doc->createElement("svg:path"); + repr->setAttribute("sodipodi:type", "arc"); + + // Set style + sp_desktop_apply_style_tool(desktop, repr, "/tools/shapes/arc", false); + + this->arc = SP_GENERICELLIPSE(desktop->currentLayer()->appendChildRepr(repr)); + Inkscape::GC::release(repr); + this->arc->transform = SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); + this->arc->updateRepr(); + + desktop->canvas->forceFullRedrawAfterInterruptions(5); + } + + bool ctrl_save = false; + + if ((state & GDK_MOD1_MASK) && (state & GDK_CONTROL_MASK) && !(state & GDK_SHIFT_MASK)) { + // if Alt is pressed without Shift in addition to Control, temporarily drop the CONTROL mask + // so that the ellipse is not constrained to integer ratios + ctrl_save = true; + state = state ^ GDK_CONTROL_MASK; + } + + Geom::Rect r = Inkscape::snap_rectangular_box(desktop, this->arc, pt, this->center, state); + + if (ctrl_save) { + state = state ^ GDK_CONTROL_MASK; + } + + Geom::Point dir = r.dimensions() / 2; + + if (state & GDK_MOD1_MASK) { + /* With Alt let the ellipse pass through the mouse pointer */ + Geom::Point c = r.midpoint(); + + if (!ctrl_save) { + if (fabs(dir[Geom::X]) > 1E-6 && fabs(dir[Geom::Y]) > 1E-6) { + Geom::Affine const i2d ( (this->arc)->i2dt_affine() ); + Geom::Point new_dir = pt * i2d - c; + new_dir[Geom::X] *= dir[Geom::Y] / dir[Geom::X]; + double lambda = new_dir.length() / dir[Geom::Y]; + r = Geom::Rect (c - lambda*dir, c + lambda*dir); + } + } else { + /* with Alt+Ctrl (without Shift) we generate a perfect circle + with diameter click point <--> mouse pointer */ + double l = dir.length(); + Geom::Point d (l, l); + r = Geom::Rect (c - d, c + d); + } + } + + this->arc->position_set( + r.midpoint()[Geom::X], r.midpoint()[Geom::Y], + r.dimensions()[Geom::X] / 2, r.dimensions()[Geom::Y] / 2); + + double rdimx = r.dimensions()[Geom::X]; + double rdimy = r.dimensions()[Geom::Y]; + + Inkscape::Util::Quantity rdimx_q = Inkscape::Util::Quantity(rdimx, "px"); + Inkscape::Util::Quantity rdimy_q = Inkscape::Util::Quantity(rdimy, "px"); + GString *xs = g_string_new(rdimx_q.string(desktop->namedview->doc_units).c_str()); + GString *ys = g_string_new(rdimy_q.string(desktop->namedview->doc_units).c_str()); + + if (state & GDK_CONTROL_MASK) { + int ratio_x, ratio_y; + + if (fabs (rdimx) > fabs (rdimy)) { + ratio_x = (int) rint (rdimx / rdimy); + ratio_y = 1; + } else { + ratio_x = 1; + ratio_y = (int) rint (rdimy / rdimx); + } + + this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Ellipse</b>: %s × %s (constrained to ratio %d:%d); with <b>Shift</b> to draw around the starting point"), xs->str, ys->str, ratio_x, ratio_y); + } else { + this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Ellipse</b>: %s × %s; with <b>Ctrl</b> to make square or integer-ratio ellipse; with <b>Shift</b> to draw around the starting point"), xs->str, ys->str); + } + + g_string_free(xs, FALSE); + g_string_free(ys, FALSE); +} + +void ArcTool::finishItem() { + this->message_context->clear(); + + if (this->arc != NULL) { + if (this->arc->rx.computed == 0 || this->arc->ry.computed == 0) { + this->cancel(); // Don't allow the creating of zero sized arc, for example when the start and and point snap to the snap grid point + return; + } + + this->arc->updateRepr(); + this->arc->doWriteTransform(this->arc->getRepr(), this->arc->transform, NULL, true); + + desktop->canvas->endForcedFullRedraws(); + + sp_desktop_selection(desktop)->set(this->arc); + + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_ARC, _("Create ellipse")); + + this->arc = NULL; + } +} + +void ArcTool::cancel() { + sp_desktop_selection(desktop)->clear(); + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0); + + if (this->arc != NULL) { + this->arc->deleteObject(); + this->arc = NULL; + } + + this->within_tolerance = false; + this->xp = 0; + this->yp = 0; + this->item_to_select = NULL; + + desktop->canvas->endForcedFullRedraws(); + + DocumentUndo::cancel(sp_desktop_document(desktop)); +} + +} +} +} + + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/arc-tool.h b/src/ui/tools/arc-tool.h new file mode 100644 index 000000000..eaa50f2b9 --- /dev/null +++ b/src/ui/tools/arc-tool.h @@ -0,0 +1,76 @@ +#ifndef SEEN_ARC_CONTEXT_H +#define SEEN_ARC_CONTEXT_H + +/* + * Ellipse drawing context + * + * Authors: + * Mitsuru Oka + * Lauris Kaplinski <lauris@kaplinski.com> + * + * Copyright (C) 2000-2002 Lauris Kaplinski + * Copyright (C) 2000-2001 Ximian, Inc. + * Copyright (C) 2002 Mitsuru Oka + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include <stddef.h> +#include <sigc++/connection.h> + +#include <2geom/point.h> +#include "ui/tools/tool-base.h" + +#include "sp-ellipse.h" + +#define SP_ARC_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::ArcTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_ARC_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::ArcTool*>(const Inkscape::UI::Tools::ToolBase*(obj)) != NULL) + +namespace Inkscape { +namespace UI { +namespace Tools { + +class ArcTool : public ToolBase { +public: + ArcTool(); + virtual ~ArcTool(); + + static const std::string prefsPath; + + virtual void setup(); + virtual void finish(); + virtual bool root_handler(GdkEvent* event); + virtual bool item_handler(SPItem* item, GdkEvent* event); + + virtual const std::string& getPrefsPath(); + +private: + SPGenericEllipse *arc; + + Geom::Point center; + + sigc::connection sel_changed_connection; + + void selection_changed(Inkscape::Selection* selection); + + void drag(Geom::Point pt, guint state); + void finishItem(); + void cancel(); +}; + +} +} +} + +#endif /* !SEEN_ARC_CONTEXT_H */ + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/tools/box3d-tool.cpp b/src/ui/tools/box3d-tool.cpp new file mode 100644 index 000000000..e00894d55 --- /dev/null +++ b/src/ui/tools/box3d-tool.cpp @@ -0,0 +1,628 @@ +/* + * 3D box drawing context + * + * Author: + * Lauris Kaplinski <lauris@kaplinski.com> + * bulia byak <buliabyak@users.sf.net> + * Jon A. Cruz <jon@joncruz.org> + * Abhishek Sharma + * + * Copyright (C) 2007 Maximilian Albert <Anhalter42@gmx.de> + * Copyright (C) 2006 Johan Engelen <johan@shouraizou.nl> + * Copyright (C) 2000-2005 authors + * Copyright (C) 2000-2001 Ximian, Inc. + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "config.h" + +#include <gdk/gdkkeysyms.h> + +#include "macros.h" +#include "display/sp-canvas.h" +#include "document.h" +#include "document-undo.h" +#include "sp-namedview.h" +#include "selection.h" +#include "selection-chemistry.h" +#include "desktop-handles.h" +#include "snap.h" +#include "display/curve.h" +#include "display/sp-canvas-item.h" +#include "desktop.h" +#include "message-context.h" +#include "pixmaps/cursor-3dbox.xpm" +#include "box3d.h" +#include "ui/tools/box3d-tool.h" +#include <glibmm/i18n.h> +#include "xml/repr.h" +#include "xml/node-event-vector.h" +#include "preferences.h" +#include "context-fns.h" +#include "desktop-style.h" +#include "transf_mat_3x4.h" +#include "perspective-line.h" +#include "persp3d.h" +#include "box3d-side.h" +#include "document-private.h" +#include "line-geometry.h" +#include "shape-editor.h" +#include "verbs.h" + +using Inkscape::DocumentUndo; + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +namespace { + ToolBase* createBox3dTool() { + return new Box3dTool(); + } + + bool Box3dToolRegistered = ToolFactory::instance().registerObject("/tools/shapes/3dbox", createBox3dTool); +} + +const std::string& Box3dTool::getPrefsPath() { + return Box3dTool::prefsPath; +} + +const std::string Box3dTool::prefsPath = "/tools/shapes/3dbox"; + +Box3dTool::Box3dTool() + : ToolBase(cursor_3dbox_xpm, 4, 4) + , _vpdrag(NULL) + , box3d(NULL) + , ctrl_dragged(false) + , extruded(false) +{ +} + +void Box3dTool::finish() { + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), GDK_CURRENT_TIME); + this->finishItem(); + this->sel_changed_connection.disconnect(); + + ToolBase::finish(); +} + + +Box3dTool::~Box3dTool() { + this->enableGrDrag(false); + + delete (this->_vpdrag); + this->_vpdrag = NULL; + + this->sel_changed_connection.disconnect(); + + delete this->shape_editor; + this->shape_editor = NULL; + + /* fixme: This is necessary because we do not grab */ + if (this->box3d) { + this->finishItem(); + } +} + +/** + * Callback that processes the "changed" signal on the selection; + * destroys old and creates new knotholder. + */ +void Box3dTool::selection_changed(Inkscape::Selection* selection) { + this->shape_editor->unset_item(SH_KNOTHOLDER); + this->shape_editor->set_item(selection->singleItem(), SH_KNOTHOLDER); + + if (selection->perspList().size() == 1) { + // selecting a single box changes the current perspective + this->desktop->doc()->setCurrentPersp3D(selection->perspList().front()); + } +} + +/* Create a default perspective in document defs if none is present (which can happen, among other + * circumstances, after 'vacuum defs' or when a pre-0.46 file is opened). + */ +static void sp_box3d_context_ensure_persp_in_defs(SPDocument *document) { + SPDefs *defs = document->getDefs(); + + bool has_persp = false; + for ( SPObject *child = defs->firstChild(); child; child = child->getNext() ) { + if (SP_IS_PERSP3D(child)) { + has_persp = true; + break; + } + } + + if (!has_persp) { + document->setCurrentPersp3D(persp3d_create_xml_element (document)); + } +} + +void Box3dTool::setup() { + ToolBase::setup(); + + this->shape_editor = new ShapeEditor(this->desktop); + + SPItem *item = sp_desktop_selection(this->desktop)->singleItem(); + if (item) { + this->shape_editor->set_item(item, SH_KNOTHOLDER); + } + + this->sel_changed_connection.disconnect(); + this->sel_changed_connection = sp_desktop_selection(this->desktop)->connectChanged( + sigc::mem_fun(this, &Box3dTool::selection_changed) + ); + + this->_vpdrag = new Box3D::VPDrag(sp_desktop_document(this->desktop)); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + if (prefs->getBool("/tools/shapes/selcue")) { + this->enableSelectionCue(); + } + + if (prefs->getBool("/tools/shapes/gradientdrag")) { + this->enableGrDrag(); + } +} + +bool Box3dTool::item_handler(SPItem* item, GdkEvent* event) { + gint ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + if ( event->button.button == 1 && !this->space_panning) { + Inkscape::setup_for_drag_start(desktop, this, event); + ret = TRUE; + } + break; + // motion and release are always on root (why?) + default: + break; + } + +// if (((ToolBaseClass *) sp_box3d_context_parent_class)->item_handler) { +// ret = ((ToolBaseClass *) sp_box3d_context_parent_class)->item_handler(event_context, item, event); +// } + // CPPIFY: ret is always overwritten... + ret = ToolBase::item_handler(item, event); + + return ret; +} + +bool Box3dTool::root_handler(GdkEvent* event) { + static bool dragging; + + SPDocument *document = sp_desktop_document (desktop); + Inkscape::Selection *selection = sp_desktop_selection (desktop); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int const snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12); + + Persp3D *cur_persp = document->getCurrentPersp3D(); + + this->tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + + gint ret = FALSE; + switch (event->type) { + case GDK_BUTTON_PRESS: + if ( event->button.button == 1 && !this->space_panning) { + Geom::Point const button_w(event->button.x, event->button.y); + Geom::Point button_dt(desktop->w2d(button_w)); + + // save drag origin + this->xp = (gint) button_w[Geom::X]; + this->yp = (gint) button_w[Geom::Y]; + this->within_tolerance = true; + + // remember clicked box3d, *not* disregarding groups (since a 3D box is a group), honoring Alt + this->item_to_select = sp_event_context_find_item (desktop, button_w, event->button.state & GDK_MOD1_MASK, event->button.state & GDK_CONTROL_MASK); + + dragging = true; + + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop, true, this->box3d); + m.freeSnapReturnByRef(button_dt, Inkscape::SNAPSOURCE_NODE_HANDLE); + m.unSetup(); + this->center = button_dt; + + this->drag_origin = button_dt; + this->drag_ptB = button_dt; + this->drag_ptC = button_dt; + + // This can happen after saving when the last remaining perspective was purged and must be recreated. + if (!cur_persp) { + sp_box3d_context_ensure_persp_in_defs(document); + cur_persp = document->getCurrentPersp3D(); + } + + /* Projective preimages of clicked point under current perspective */ + this->drag_origin_proj = cur_persp->perspective_impl->tmat.preimage (button_dt, 0, Proj::Z); + this->drag_ptB_proj = this->drag_origin_proj; + this->drag_ptC_proj = this->drag_origin_proj; + this->drag_ptC_proj.normalize(); + this->drag_ptC_proj[Proj::Z] = 0.25; + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + ( GDK_KEY_PRESS_MASK | + GDK_BUTTON_RELEASE_MASK | + GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | + GDK_BUTTON_PRESS_MASK ), + NULL, event->button.time); + ret = TRUE; + } + break; + + case GDK_MOTION_NOTIFY: + if (dragging && ( event->motion.state & GDK_BUTTON1_MASK ) && !this->space_panning) { + if ( this->within_tolerance + && ( abs( (gint) event->motion.x - this->xp ) < this->tolerance ) + && ( abs( (gint) event->motion.y - this->yp ) < this->tolerance ) ) { + break; // do not drag if we're within tolerance from origin + } + // Once the user has moved farther than tolerance from the original location + // (indicating they intend to draw, not click), then always process the + // motion notify coordinates as given (no snapping back to origin) + this->within_tolerance = false; + + Geom::Point const motion_w(event->motion.x, + event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); + + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop, true, this->box3d); + m.freeSnapReturnByRef(motion_dt, Inkscape::SNAPSOURCE_NODE_HANDLE); + this->ctrl_dragged = event->motion.state & GDK_CONTROL_MASK; + + if ((event->motion.state & GDK_SHIFT_MASK) && !this->extruded && this->box3d) { + // once shift is pressed, set this->extruded + this->extruded = true; + } + + if (!this->extruded) { + this->drag_ptB = motion_dt; + this->drag_ptC = motion_dt; + + this->drag_ptB_proj = cur_persp->perspective_impl->tmat.preimage (motion_dt, 0, Proj::Z); + this->drag_ptC_proj = this->drag_ptB_proj; + this->drag_ptC_proj.normalize(); + this->drag_ptC_proj[Proj::Z] = 0.25; + } else { + // Without Ctrl, motion of the extruded corner is constrained to the + // perspective line from drag_ptB to vanishing point Y. + if (!this->ctrl_dragged) { + /* snapping */ + Box3D::PerspectiveLine pline (this->drag_ptB, Proj::Z, document->getCurrentPersp3D()); + this->drag_ptC = pline.closest_to (motion_dt); + + this->drag_ptB_proj.normalize(); + this->drag_ptC_proj = cur_persp->perspective_impl->tmat.preimage (this->drag_ptC, this->drag_ptB_proj[Proj::X], Proj::X); + } else { + this->drag_ptC = motion_dt; + + this->drag_ptB_proj.normalize(); + this->drag_ptC_proj = cur_persp->perspective_impl->tmat.preimage (motion_dt, this->drag_ptB_proj[Proj::X], Proj::X); + } + + m.freeSnapReturnByRef(this->drag_ptC, Inkscape::SNAPSOURCE_NODE_HANDLE); + } + + m.unSetup(); + + this->drag(event->motion.state); + + ret = TRUE; + } else if (!this->sp_event_context_knot_mouseover()) { + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); + m.preSnap(Inkscape::SnapCandidatePoint(motion_dt, Inkscape::SNAPSOURCE_NODE_HANDLE)); + m.unSetup(); + } + break; + + case GDK_BUTTON_RELEASE: + this->xp = this->yp = 0; + + if (event->button.button == 1 && !this->space_panning) { + dragging = false; + sp_event_context_discard_delayed_snap_event(this); + + if (!this->within_tolerance) { + // we've been dragging, finish the box + this->finishItem(); + } else if (this->item_to_select) { + // no dragging, select clicked box3d if any + if (event->button.state & GDK_SHIFT_MASK) { + selection->toggle(this->item_to_select); + } else { + selection->set(this->item_to_select); + } + } else { + // click in an empty space + selection->clear(); + } + + this->item_to_select = NULL; + ret = TRUE; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), + event->button.time); + } + break; + + case GDK_KEY_PRESS: + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Up: + case GDK_KEY_Down: + case GDK_KEY_KP_Up: + case GDK_KEY_KP_Down: + // prevent the zoom field from activation + if (!MOD__CTRL_ONLY(event)) + ret = TRUE; + break; + + case GDK_KEY_bracketright: + persp3d_rotate_VP (document->getCurrentPersp3D(), Proj::X, -180/snaps, MOD__ALT(event)); + DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, + _("Change perspective (angle of PLs)")); + ret = true; + break; + + case GDK_KEY_bracketleft: + persp3d_rotate_VP (document->getCurrentPersp3D(), Proj::X, 180/snaps, MOD__ALT(event)); + DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, + _("Change perspective (angle of PLs)")); + ret = true; + break; + + case GDK_KEY_parenright: + persp3d_rotate_VP (document->getCurrentPersp3D(), Proj::Y, -180/snaps, MOD__ALT(event)); + DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, + _("Change perspective (angle of PLs)")); + ret = true; + break; + + case GDK_KEY_parenleft: + persp3d_rotate_VP (document->getCurrentPersp3D(), Proj::Y, 180/snaps, MOD__ALT(event)); + DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, + _("Change perspective (angle of PLs)")); + ret = true; + break; + + case GDK_KEY_braceright: + persp3d_rotate_VP (document->getCurrentPersp3D(), Proj::Z, -180/snaps, MOD__ALT(event)); + DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, + _("Change perspective (angle of PLs)")); + ret = true; + break; + + case GDK_KEY_braceleft: + persp3d_rotate_VP (document->getCurrentPersp3D(), Proj::Z, 180/snaps, MOD__ALT(event)); + DocumentUndo::done(document, SP_VERB_CONTEXT_3DBOX, + _("Change perspective (angle of PLs)")); + ret = true; + break; + + /* TODO: what is this??? + case GDK_O: + if (MOD__CTRL(event) && MOD__SHIFT(event)) { + Box3D::create_canvas_point(persp3d_get_VP(document()->getCurrentPersp3D(), Proj::W).affine(), + 6, 0xff00ff00); + } + ret = true; + break; + */ + + case GDK_KEY_g: + case GDK_KEY_G: + if (MOD__SHIFT_ONLY(event)) { + sp_selection_to_guides(desktop); + ret = true; + } + break; + + case GDK_KEY_p: + case GDK_KEY_P: + if (MOD__SHIFT_ONLY(event)) { + if (document->getCurrentPersp3D()) { + persp3d_print_debugging_info (document->getCurrentPersp3D()); + } + ret = true; + } + break; + + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo ("altx-box3d"); + ret = TRUE; + } + if (MOD__SHIFT_ONLY(event)) { + persp3d_toggle_VPs(selection->perspList(), Proj::X); + this->_vpdrag->updateLines(); // FIXME: Shouldn't this be done automatically? + ret = true; + } + break; + + case GDK_KEY_y: + case GDK_KEY_Y: + if (MOD__SHIFT_ONLY(event)) { + persp3d_toggle_VPs(selection->perspList(), Proj::Y); + this->_vpdrag->updateLines(); // FIXME: Shouldn't this be done automatically? + ret = true; + } + break; + + case GDK_KEY_z: + case GDK_KEY_Z: + if (MOD__SHIFT_ONLY(event)) { + persp3d_toggle_VPs(selection->perspList(), Proj::Z); + this->_vpdrag->updateLines(); // FIXME: Shouldn't this be done automatically? + ret = true; + } + break; + + case GDK_KEY_Escape: + sp_desktop_selection(desktop)->clear(); + //TODO: make dragging escapable by Esc + break; + + case GDK_KEY_space: + if (dragging) { + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), + event->button.time); + dragging = false; + sp_event_context_discard_delayed_snap_event(this); + if (!this->within_tolerance) { + // we've been dragging, finish the box + this->finishItem(); + } + // do not return true, so that space would work switching to selector + } + break; + + case GDK_KEY_Delete: + case GDK_KEY_KP_Delete: + case GDK_KEY_BackSpace: + ret = this->deleteSelectedDrag(MOD__CTRL_ONLY(event)); + break; + + default: + break; + } + break; + + default: + break; + } + + if (!ret) { + ret = ToolBase::root_handler(event); + } + + return ret; +} + +void Box3dTool::drag(guint /*state*/) { + if (!this->box3d) { + if (Inkscape::have_viable_layer(desktop, this->message_context) == false) { + return; + } + + // Create object + SPBox3D *box3d = SPBox3D::createBox3D((SPItem*)desktop->currentLayer()); + + // Set style + desktop->applyCurrentOrToolStyle(box3d, "/tools/shapes/3dbox", false); + + this->box3d = box3d; + + // TODO: Incorporate this in box3d-side.cpp! + for (int i = 0; i < 6; ++i) { + Box3DSide *side = Box3DSide::createBox3DSide(box3d); + + guint desc = Box3D::int_to_face(i); + + Box3D::Axis plane = (Box3D::Axis) (desc & 0x7); + plane = (Box3D::is_plane(plane) ? plane : Box3D::orth_plane_or_axis(plane)); + side->dir1 = Box3D::extract_first_axis_direction(plane); + side->dir2 = Box3D::extract_second_axis_direction(plane); + side->front_or_rear = (Box3D::FrontOrRear) (desc & 0x8); + + // Set style + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + Glib::ustring descr = "/desktop/"; + descr += box3d_side_axes_string(side); + descr += "/style"; + + Glib::ustring cur_style = prefs->getString(descr); + + bool use_current = prefs->getBool("/tools/shapes/3dbox/usecurrent", false); + + if (use_current && !cur_style.empty()) { + // use last used style + side->setAttribute("style", cur_style.data()); + } else { + // use default style + GString *pstring = g_string_new(""); + g_string_printf (pstring, "/tools/shapes/3dbox/%s", box3d_side_axes_string(side)); + desktop->applyCurrentOrToolStyle (side, pstring->str, false); + } + + side->updateRepr(); // calls box3d_side_write() and updates, e.g., the axes string description + } + + box3d_set_z_orders(this->box3d); + this->box3d->updateRepr(); + + // TODO: It would be nice to show the VPs during dragging, but since there is no selection + // at this point (only after finishing the box), we must do this "manually" + /* this._vpdrag->updateDraggers(); */ + + desktop->canvas->forceFullRedrawAfterInterruptions(5); + } + + g_assert(this->box3d); + + this->box3d->orig_corner0 = this->drag_origin_proj; + this->box3d->orig_corner7 = this->drag_ptC_proj; + + box3d_check_for_swapped_coords(this->box3d); + + /* we need to call this from here (instead of from box3d_position_set(), for example) + because z-order setting must not interfere with display updates during undo/redo */ + box3d_set_z_orders (this->box3d); + + box3d_position_set(this->box3d); + + // status text + this->message_context->setF(Inkscape::NORMAL_MESSAGE, "%s", _("<b>3D Box</b>; with <b>Shift</b> to extrude along the Z axis")); +} + +void Box3dTool::finishItem() { + this->message_context->clear(); + this->ctrl_dragged = false; + this->extruded = false; + + if (this->box3d != NULL) { + SPDocument *doc = sp_desktop_document(this->desktop); + + if (!doc || !doc->getCurrentPersp3D()) { + return; + } + + this->box3d->orig_corner0 = this->drag_origin_proj; + this->box3d->orig_corner7 = this->drag_ptC_proj; + + this->box3d->updateRepr(); + + box3d_relabel_corners(this->box3d); + + desktop->canvas->endForcedFullRedraws(); + + sp_desktop_selection(desktop)->set(this->box3d); + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_3DBOX, + _("Create 3D box")); + + this->box3d = NULL; + } +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/box3d-tool.h b/src/ui/tools/box3d-tool.h new file mode 100644 index 000000000..99bf99a7a --- /dev/null +++ b/src/ui/tools/box3d-tool.h @@ -0,0 +1,95 @@ +#ifndef __SP_BOX3D_CONTEXT_H__ +#define __SP_BOX3D_CONTEXT_H__ + +/* + * 3D box drawing context + * + * Author: + * Lauris Kaplinski <lauris@kaplinski.com> + * + * Copyright (C) 2000 Lauris Kaplinski + * Copyright (C) 2000-2001 Ximian, Inc. + * Copyright (C) 2002 Lauris Kaplinski + * Copyright (C) 2007 Maximilian Albert <Anhalter42@gmx.de> + * + * Released under GNU GPL + */ + +#include <stddef.h> +#include <sigc++/sigc++.h> +#include "ui/tools/tool-base.h" +#include "proj_pt.h" +#include "vanishing-point.h" + +#include "box3d.h" + +#define SP_BOX3D_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::Box3dTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_BOX3D_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::Box3dTool*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +namespace Inkscape { +namespace UI { +namespace Tools { + +class Box3dTool : public ToolBase { +public: + Box3dTool(); + virtual ~Box3dTool(); + + Box3D::VPDrag * _vpdrag; + + static const std::string prefsPath; + + virtual void setup(); + virtual void finish(); + virtual bool root_handler(GdkEvent* event); + virtual bool item_handler(SPItem* item, GdkEvent* event); + + virtual const std::string& getPrefsPath(); + +private: + SPBox3D* box3d; + Geom::Point center; + + /** + * save three corners while dragging: + * 1) the starting point (already done by the event_context) + * 2) drag_ptB --> the opposite corner of the front face (before pressing shift) + * 3) drag_ptC --> the "extruded corner" (which coincides with the mouse pointer location + * if we are ctrl-dragging but is constrained to the perspective line from drag_ptC + * to the vanishing point Y otherwise) + */ + Geom::Point drag_origin; + Geom::Point drag_ptB; + Geom::Point drag_ptC; + + Proj::Pt3 drag_origin_proj; + Proj::Pt3 drag_ptB_proj; + Proj::Pt3 drag_ptC_proj; + + bool ctrl_dragged; /* whether we are ctrl-dragging */ + bool extruded; /* whether shift-dragging already occured (i.e. the box is already extruded) */ + + sigc::connection sel_changed_connection; + + void selection_changed(Inkscape::Selection* selection); + + void drag(guint state); + void finishItem(); +}; + +} +} +} + +#endif /* __SP_BOX3D_CONTEXT_H__ */ + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/calligraphic-tool.cpp b/src/ui/tools/calligraphic-tool.cpp new file mode 100644 index 000000000..64097e834 --- /dev/null +++ b/src/ui/tools/calligraphic-tool.cpp @@ -0,0 +1,1210 @@ +/* + * Handwriting-like drawing mode + * + * Authors: + * Mitsuru Oka <oka326@parkcity.ne.jp> + * Lauris Kaplinski <lauris@kaplinski.com> + * bulia byak <buliabyak@users.sf.net> + * MenTaLguY <mental@rydia.net> + * Abhishek Sharma + * Jon A. Cruz <jon@joncruz.org> + * + * The original dynadraw code: + * Paul Haeberli <paul@sgi.com> + * + * Copyright (C) 1998 The Free Software Foundation + * Copyright (C) 1999-2005 authors + * Copyright (C) 2001-2002 Ximian, Inc. + * Copyright (C) 2005-2007 bulia byak + * Copyright (C) 2006 MenTaLguY + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#define noDYNA_DRAW_VERBOSE + +#include "config.h" + +#include <gtk/gtk.h> +#include <gdk/gdkkeysyms.h> +#include <glibmm/i18n.h> +#include <string> +#include <cstring> +#include <numeric> + +#include "svg/svg.h" +#include "display/canvas-bpath.h" +#include "display/cairo-utils.h" +#include <2geom/math-utils.h> +#include <2geom/pathvector.h> +#include <2geom/bezier-utils.h> +#include <2geom/circle.h> +#include "display/curve.h" +#include <glib.h> +#include "macros.h" +#include "document.h" +#include "document-undo.h" +#include "selection.h" +#include "desktop.h" +#include "desktop-events.h" +#include "desktop-handles.h" +#include "desktop-style.h" +#include "message-context.h" +#include "preferences.h" +#include "pixmaps/cursor-calligraphy.xpm" +#include "xml/repr.h" +#include "context-fns.h" +#include "sp-item.h" +#include "inkscape.h" +#include "color.h" +#include "splivarot.h" +#include "sp-item-group.h" +#include "sp-shape.h" +#include "sp-path.h" +#include "sp-text.h" +#include "display/sp-canvas.h" +#include "display/canvas-bpath.h" +#include "display/canvas-arena.h" +#include "livarot/Shape.h" +#include "verbs.h" + +#include "ui/tools/calligraphic-tool.h" + +using Inkscape::DocumentUndo; + +#define DDC_RED_RGBA 0xff0000ff + +#define TOLERANCE_CALLIGRAPHIC 0.1 + +#define DYNA_EPSILON 0.5e-6 +#define DYNA_EPSILON_START 0.5e-2 +#define DYNA_VEL_START 1e-5 + +#define DYNA_MIN_WIDTH 1.0e-6 + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +static void add_cap(SPCurve *curve, Geom::Point const &from, Geom::Point const &to, double rounding); + +namespace { + ToolBase* createCalligraphicContext() { + return new CalligraphicTool(); + } + + bool calligraphicContextRegistered = ToolFactory::instance().registerObject("/tools/calligraphic", createCalligraphicContext); +} + +const std::string& CalligraphicTool::getPrefsPath() { + return CalligraphicTool::prefsPath; +} + + +const std::string CalligraphicTool::prefsPath = "/tools/calligraphic"; + +CalligraphicTool::CalligraphicTool() + : DynamicBase(cursor_calligraphy_xpm, 4, 4) + , keep_selected(true) + , hatch_spacing(0) + , hatch_spacing_step(0) + , hatch_item(NULL) + , hatch_livarot_path(NULL) + , hatch_last_nearest(Geom::Point(0,0)) + , hatch_last_pointer(Geom::Point(0,0)) + , hatch_escaped(false) + , hatch_area(NULL) + , just_started_drawing(false) + , trace_bg(false) +{ + this->vel_thin = 0.1; + this->flatness = 0.9; + this->cap_rounding = 0.0; + this->abs_width = false; +} + +CalligraphicTool::~CalligraphicTool() { + if (this->hatch_area) { + sp_canvas_item_destroy(this->hatch_area); + this->hatch_area = NULL; + } +} + +void CalligraphicTool::setup() { + DynamicBase::setup(); + + this->accumulated = new SPCurve(); + this->currentcurve = new SPCurve(); + + this->cal1 = new SPCurve(); + this->cal2 = new SPCurve(); + + this->currentshape = sp_canvas_item_new(sp_desktop_sketch(this->desktop), SP_TYPE_CANVAS_BPATH, NULL); + sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(this->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + + /* fixme: Cannot we cascade it to root more clearly? */ + g_signal_connect(G_OBJECT(this->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), this->desktop); + + { + /* TODO: have a look at DropperTool::setup where the same is done.. generalize? */ + Geom::PathVector path; + Geom::Circle(0, 0, 1).getPath(path); + + SPCurve *c = new SPCurve(path); + + this->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(this->desktop), c); + + c->unref(); + + sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(this->hatch_area), 0x00000000,(SPWindRule)0); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_item_hide(this->hatch_area); + } + + sp_event_context_read(this, "mass"); + sp_event_context_read(this, "wiggle"); + sp_event_context_read(this, "angle"); + sp_event_context_read(this, "width"); + sp_event_context_read(this, "thinning"); + sp_event_context_read(this, "tremor"); + sp_event_context_read(this, "flatness"); + sp_event_context_read(this, "tracebackground"); + sp_event_context_read(this, "usepressure"); + sp_event_context_read(this, "usetilt"); + sp_event_context_read(this, "abs_width"); + sp_event_context_read(this, "keep_selected"); + sp_event_context_read(this, "cap_rounding"); + + this->is_drawing = false; + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/tools/calligraphic/selcue")) { + this->enableSelectionCue(); + } +} + +void CalligraphicTool::set(const Inkscape::Preferences::Entry& val) { + Glib::ustring path = val.getEntryName(); + + if (path == "tracebackground") { + this->trace_bg = val.getBool(); + } else if (path == "keep_selected") { + this->keep_selected = val.getBool(); + } else { + //pass on up to parent class to handle common attributes. + DynamicBase::set(val); + } + + //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width); +} + +static double +flerp(double f0, double f1, double p) +{ + return f0 + ( f1 - f0 ) * p; +} + +///* Get normalized point */ +//Geom::Point CalligraphicTool::getNormalizedPoint(Geom::Point v) const { +// Geom::Rect drect = desktop->get_display_area(); +// +// double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] ); +// +// return Geom::Point(( v[Geom::X] - drect.min()[Geom::X] ) / max, ( v[Geom::Y] - drect.min()[Geom::Y] ) / max); +//} +// +///* Get view point */ +//Geom::Point CalligraphicTool::getViewPoint(Geom::Point n) const { +// Geom::Rect drect = desktop->get_display_area(); +// +// double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] ); +// +// return Geom::Point(n[Geom::X] * max + drect.min()[Geom::X], n[Geom::Y] * max + drect.min()[Geom::Y]); +//} + +void CalligraphicTool::reset(Geom::Point p) { + this->last = this->cur = this->getNormalizedPoint(p); + + this->vel = Geom::Point(0,0); + this->vel_max = 0; + this->acc = Geom::Point(0,0); + this->ang = Geom::Point(0,0); + this->del = Geom::Point(0,0); +} + +void CalligraphicTool::extinput(GdkEvent *event) { + if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &this->pressure)) { + this->pressure = CLAMP (this->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE); + } else { + this->pressure = DDC_DEFAULT_PRESSURE; + } + + if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &this->xtilt)) { + this->xtilt = CLAMP (this->xtilt, DDC_MIN_TILT, DDC_MAX_TILT); + } else { + this->xtilt = DDC_DEFAULT_TILT; + } + + if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &this->ytilt)) { + this->ytilt = CLAMP (this->ytilt, DDC_MIN_TILT, DDC_MAX_TILT); + } else { + this->ytilt = DDC_DEFAULT_TILT; + } +} + + +bool CalligraphicTool::apply(Geom::Point p) { + Geom::Point n = this->getNormalizedPoint(p); + + /* Calculate mass and drag */ + double const mass = flerp(1.0, 160.0, this->mass); + double const drag = flerp(0.0, 0.5, this->drag * this->drag); + + /* Calculate force and acceleration */ + Geom::Point force = n - this->cur; + + // If force is below the absolute threshold DYNA_EPSILON, + // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke) + // _and_ the force is below the (higher) DYNA_EPSILON_START threshold, + // discard this move. + // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen, + // especially bothersome at the start of the stroke where we don't yet have the inertia to + // smooth them out. + if ( Geom::L2(force) < DYNA_EPSILON || (this->vel_max < DYNA_VEL_START && Geom::L2(force) < DYNA_EPSILON_START)) { + return FALSE; + } + + this->acc = force / mass; + + /* Calculate new velocity */ + this->vel += this->acc; + + if (Geom::L2(this->vel) > this->vel_max) + this->vel_max = Geom::L2(this->vel); + + /* Calculate angle of drawing tool */ + + double a1; + if (this->usetilt) { + // 1a. calculate nib angle from input device tilt: + gdouble length = std::sqrt(this->xtilt*this->xtilt + this->ytilt*this->ytilt);; + + if (length > 0) { + Geom::Point ang1 = Geom::Point(this->ytilt/length, this->xtilt/length); + a1 = atan2(ang1); + } + else + a1 = 0.0; + } + else { + // 1b. fixed dc->angle (absolutely flat nib): + double const radians = ( (this->angle - 90) / 180.0 ) * M_PI; + Geom::Point ang1 = Geom::Point(-sin(radians), cos(radians)); + a1 = atan2(ang1); + } + + // 2. perpendicular to dc->vel (absolutely non-flat nib): + gdouble const mag_vel = Geom::L2(this->vel); + if ( mag_vel < DYNA_EPSILON ) { + return FALSE; + } + Geom::Point ang2 = Geom::rot90(this->vel) / mag_vel; + + // 3. Average them using flatness parameter: + // calculate angles + double a2 = atan2(ang2); + // flip a2 to force it to be in the same half-circle as a1 + bool flipped = false; + if (fabs (a2-a1) > 0.5*M_PI) { + a2 += M_PI; + flipped = true; + } + // normalize a2 + if (a2 > M_PI) + a2 -= 2*M_PI; + if (a2 < -M_PI) + a2 += 2*M_PI; + // find the flatness-weighted bisector angle, unflip if a2 was flipped + // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this? + double new_ang = a1 + (1 - this->flatness) * (a2 - a1) - (flipped? M_PI : 0); + + // Try to detect a sudden flip when the new angle differs too much from the previous for the + // current velocity; in that case discard this move + double angle_delta = Geom::L2(Geom::Point (cos (new_ang), sin (new_ang)) - this->ang); + if ( angle_delta / Geom::L2(this->vel) > 4000 ) { + return FALSE; + } + + // convert to point + this->ang = Geom::Point (cos (new_ang), sin (new_ang)); + +// g_print ("force %g acc %g vel_max %g vel %g a1 %g a2 %g new_ang %g\n", Geom::L2(force), Geom::L2(dc->acc), dc->vel_max, Geom::L2(dc->vel), a1, a2, new_ang); + + /* Apply drag */ + this->vel *= 1.0 - drag; + + /* Update position */ + this->last = this->cur; + this->cur += this->vel; + + return TRUE; +} + +void CalligraphicTool::brush() { + g_assert( this->npoints >= 0 && this->npoints < SAMPLING_SIZE ); + + // How much velocity thins strokestyle + double vel_thin = flerp (0, 160, this->vel_thin); + + // Influence of pressure on thickness + double pressure_thick = (this->usepressure ? this->pressure : 1.0); + + // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass + // drag) + Geom::Point brush = this->getViewPoint(this->cur); + Geom::Point brush_w = SP_EVENT_CONTEXT(this)->desktop->d2w(brush); + + double trace_thick = 1; + if (this->trace_bg) { + // pick single pixel + double R, G, B, A; + Geom::IntRect area = Geom::IntRect::from_xywh(brush_w.floor(), Geom::IntPoint(1, 1)); + cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1, 1); + sp_canvas_arena_render_surface(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(this)->desktop)), s, area); + ink_cairo_surface_average_color_premul(s, R, G, B, A); + cairo_surface_destroy(s); + double max = MAX (MAX (R, G), B); + double min = MIN (MIN (R, G), B); + double L = A * (max + min)/2 + (1 - A); // blend with white bg + trace_thick = 1 - L; + //g_print ("L %g thick %g\n", L, trace_thick); + } + + double width = (pressure_thick * trace_thick - vel_thin * Geom::L2(this->vel)) * this->width; + + double tremble_left = 0, tremble_right = 0; + if (this->tremor > 0) { + // obtain two normally distributed random variables, using polar Box-Muller transform + double x1, x2, w, y1, y2; + do { + x1 = 2.0 * g_random_double_range(0,1) - 1.0; + x2 = 2.0 * g_random_double_range(0,1) - 1.0; + w = x1 * x1 + x2 * x2; + } while ( w >= 1.0 ); + w = sqrt( (-2.0 * log( w ) ) / w ); + y1 = x1 * w; + y2 = x2 * w; + + // deflect both left and right edges randomly and independently, so that: + // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve; + // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths; + // (3) deflection somewhat depends on speed, to prevent fast strokes looking + // comparatively smooth and slow ones excessively jittery + tremble_left = (y1)*this->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(this->vel)); + tremble_right = (y2)*this->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(this->vel)); + } + + if ( width < 0.02 * this->width ) { + width = 0.02 * this->width; + } + + double dezoomify_factor = 0.05 * 1000; + if (!this->abs_width) { + dezoomify_factor /= SP_EVENT_CONTEXT(this)->desktop->current_zoom(); + } + + Geom::Point del_left = dezoomify_factor * (width + tremble_left) * this->ang; + Geom::Point del_right = dezoomify_factor * (width + tremble_right) * this->ang; + + this->point1[this->npoints] = brush + del_left; + this->point2[this->npoints] = brush - del_right; + + this->del = 0.5*(del_left + del_right); + + this->npoints++; +} + +static void +sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value) +{ + desktop->setToolboxAdjustmentValue (id, value); +} + +void CalligraphicTool::cancel() { + this->dragging = false; + this->is_drawing = false; + + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0); + + /* Remove all temporary line segments */ + while (this->segments) { + sp_canvas_item_destroy(SP_CANVAS_ITEM(this->segments->data)); + this->segments = g_slist_remove(this->segments, this->segments->data); + } + + /* reset accumulated curve */ + this->accumulated->reset(); + this->clear_current(); + + if (this->repr) { + this->repr = NULL; + } +} + +bool CalligraphicTool::root_handler(GdkEvent* event) { + gint ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + if (Inkscape::have_viable_layer(desktop, this->message_context) == false) { + return TRUE; + } + + this->accumulated->reset(); + + if (this->repr) { + this->repr = NULL; + } + + /* initialize first point */ + this->npoints = 0; + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + ( GDK_KEY_PRESS_MASK | + GDK_BUTTON_RELEASE_MASK | + GDK_POINTER_MOTION_MASK | + GDK_BUTTON_PRESS_MASK ), + NULL, + event->button.time); + + ret = TRUE; + + desktop->canvas->forceFullRedrawAfterInterruptions(3); + this->is_drawing = true; + this->just_started_drawing = true; + } + break; + case GDK_MOTION_NOTIFY: + { + Geom::Point const motion_w(event->motion.x, + event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); + this->extinput(event); + + this->message_context->clear(); + + // for hatching: + double hatch_dist = 0; + Geom::Point hatch_unit_vector(0,0); + Geom::Point nearest(0,0); + Geom::Point pointer(0,0); + Geom::Affine motion_to_curve(Geom::identity()); + + if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item + + SPItem *selected = sp_desktop_selection(desktop)->singleItem(); + if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) { + // One item selected, and it's a path; + // let's try to track it as a guide + + if (selected != this->hatch_item) { + this->hatch_item = selected; + if (this->hatch_livarot_path) + delete this->hatch_livarot_path; + this->hatch_livarot_path = Path_for_item (this->hatch_item, true, true); + this->hatch_livarot_path->ConvertWithBackData(0.01); + } + + // calculate pointer point in the guide item's coords + motion_to_curve = selected->dt2i_affine() * selected->i2doc_affine(); + pointer = motion_dt * motion_to_curve; + + // calculate the nearest point on the guide path + boost::optional<Path::cut_position> position = get_nearest_position_on_Path(this->hatch_livarot_path, pointer); + nearest = get_point_on_Path(this->hatch_livarot_path, position->piece, position->t); + + + // distance from pointer to nearest + hatch_dist = Geom::L2(pointer - nearest); + // unit-length vector + hatch_unit_vector = (pointer - nearest)/hatch_dist; + + this->message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>")); + } else { + this->message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>")); + } + } + + if ( this->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !this->space_panning) { + this->dragging = TRUE; + + if (event->motion.state & GDK_CONTROL_MASK && this->hatch_item) { // hatching + +#define HATCH_VECTOR_ELEMENTS 12 +#define INERTIA_ELEMENTS 24 +#define SPEED_ELEMENTS 12 +#define SPEED_MIN 0.3 +#define SPEED_NORMAL 0.35 +#define INERTIA_FORCE 0.5 + + // speed is the movement of the nearest point along the guide path, divided by + // the movement of the pointer at the same period; it is averaged for the last + // SPEED_ELEMENTS motion events. Normally, as you track the guide path, speed + // is about 1, i.e. the nearest point on the path is moved by about the same + // distance as the pointer. If the speed starts to decrease, we are losing + // contact with the guide; if it drops below SPEED_MIN, we are on our own and + // not attracted to guide anymore. Most often this happens when you have + // tracked to the end of a guide calligraphic stroke and keep moving + // further. We try to handle this situation gracefully: not stick with the + // guide forever but let go of it smoothly and without sharp jerks (non-zero + // mass recommended; with zero mass, jerks are still quite noticeable). + + double speed = 1; + if (Geom::L2(this->hatch_last_nearest) != 0) { + // the distance nearest moved since the last motion event + double nearest_moved = Geom::L2(nearest - this->hatch_last_nearest); + // the distance pointer moved since the last motion event + double pointer_moved = Geom::L2(pointer - this->hatch_last_pointer); + // store them in stacks limited to SPEED_ELEMENTS + this->hatch_nearest_past.push_front(nearest_moved); + if (this->hatch_nearest_past.size() > SPEED_ELEMENTS) + this->hatch_nearest_past.pop_back(); + this->hatch_pointer_past.push_front(pointer_moved); + if (this->hatch_pointer_past.size() > SPEED_ELEMENTS) + this->hatch_pointer_past.pop_back(); + + // If the stacks are full, + if (this->hatch_nearest_past.size() == SPEED_ELEMENTS) { + // calculate the sums of all stored movements + double nearest_sum = std::accumulate (this->hatch_nearest_past.begin(), this->hatch_nearest_past.end(), 0.0); + double pointer_sum = std::accumulate (this->hatch_pointer_past.begin(), this->hatch_pointer_past.end(), 0.0); + // and divide to get the speed + speed = nearest_sum/pointer_sum; + //g_print ("nearest sum %g pointer_sum %g speed %g\n", nearest_sum, pointer_sum, speed); + } + } + + if ( this->hatch_escaped // already escaped, do not reattach + || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke + || (this->hatch_spacing > 0 && hatch_dist > 50 * this->hatch_spacing) // went too far from the guide + ) { + // We are NOT attracted to the guide! + + //g_print ("\nlast_nearest %g %g nearest %g %g pointer %g %g pos %d %g\n", dc->last_nearest[Geom::X], dc->last_nearest[Geom::Y], nearest[Geom::X], nearest[Geom::Y], pointer[Geom::X], pointer[Geom::Y], position->piece, position->t); + + // Remember hatch_escaped so we don't get + // attracted again until the end of this stroke + this->hatch_escaped = true; + + if (this->inertia_vectors.size() >= INERTIA_ELEMENTS/2) { // move by inertia + Geom::Point moved_past_escape = motion_dt - this->inertia_vectors.front(); + Geom::Point inertia = + this->inertia_vectors.front() - this->inertia_vectors.back(); + + double dot = Geom::dot (moved_past_escape, inertia); + dot /= Geom::L2(moved_past_escape) * Geom::L2(inertia); + + if (dot > 0) { // mouse is still moving in approx the same direction + Geom::Point should_have_moved = + (inertia) * (1/Geom::L2(inertia)) * Geom::L2(moved_past_escape); + motion_dt = this->inertia_vectors.front() + + (INERTIA_FORCE * should_have_moved + (1 - INERTIA_FORCE) * moved_past_escape); + } + } + + } else { + + // Calculate angle cosine of this vector-to-guide and all past vectors + // summed, to detect if we accidentally flipped to the other side of the + // guide + Geom::Point hatch_vector_accumulated = std::accumulate + (this->hatch_vectors.begin(), this->hatch_vectors.end(), Geom::Point(0,0)); + double dot = Geom::dot (pointer - nearest, hatch_vector_accumulated); + dot /= Geom::L2(pointer - nearest) * Geom::L2(hatch_vector_accumulated); + + if (this->hatch_spacing != 0) { // spacing was already set + double target; + if (speed > SPEED_NORMAL) { + // all ok, strictly obey the spacing + target = this->hatch_spacing; + } else { + // looks like we're starting to lose speed, + // so _gradually_ let go attraction to prevent jerks + target = (this->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL; + } + if (!IS_NAN(dot) && dot < -0.5) {// flip + target = -target; + } + + // This is the track pointer that we will use instead of the real one + Geom::Point new_pointer = nearest + target * hatch_unit_vector; + + // some limited feedback: allow persistent pulling to slightly change + // the spacing + this->hatch_spacing += (hatch_dist - this->hatch_spacing)/3500; + + // return it to the desktop coords + motion_dt = new_pointer * motion_to_curve.inverse(); + + if (speed >= SPEED_NORMAL) { + this->inertia_vectors.push_front(motion_dt); + if (this->inertia_vectors.size() > INERTIA_ELEMENTS) + this->inertia_vectors.pop_back(); + } + + } else { + // this is the first motion event, set the dist + this->hatch_spacing = hatch_dist; + } + + // remember last points + this->hatch_last_pointer = pointer; + this->hatch_last_nearest = nearest; + + this->hatch_vectors.push_front(pointer - nearest); + if (this->hatch_vectors.size() > HATCH_VECTOR_ELEMENTS) + this->hatch_vectors.pop_back(); + } + + this->message_context->set(Inkscape::NORMAL_MESSAGE, this->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path")); + + } else { + this->message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke")); + } + + if (this->just_started_drawing) { + this->just_started_drawing = false; + this->reset(motion_dt); + } + + if (!this->apply(motion_dt)) { + ret = TRUE; + break; + } + + if ( this->cur != this->last ) { + this->brush(); + g_assert( this->npoints > 0 ); + this->fit_and_split(false); + } + ret = TRUE; + } + + // Draw the hatching circle if necessary + if (event->motion.state & GDK_CONTROL_MASK) { + if (this->hatch_spacing == 0 && hatch_dist != 0) { + // Haven't set spacing yet: gray, center free, update radius live + Geom::Point c = desktop->w2d(motion_w); + Geom::Affine const sm (Geom::Scale(hatch_dist, hatch_dist) * Geom::Translate(c)); + sp_canvas_item_affine_absolute(this->hatch_area, sm); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_item_show(this->hatch_area); + } else if (this->dragging && !this->hatch_escaped) { + // Tracking: green, center snapped, fixed radius + Geom::Point c = motion_dt; + Geom::Affine const sm (Geom::Scale(this->hatch_spacing, this->hatch_spacing) * Geom::Translate(c)); + sp_canvas_item_affine_absolute(this->hatch_area, sm); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_item_show(this->hatch_area); + } else if (this->dragging && this->hatch_escaped) { + // Tracking escaped: red, center free, fixed radius + Geom::Point c = motion_dt; + Geom::Affine const sm (Geom::Scale(this->hatch_spacing, this->hatch_spacing) * Geom::Translate(c)); + + sp_canvas_item_affine_absolute(this->hatch_area, sm); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_item_show(this->hatch_area); + } else { + // Not drawing but spacing set: gray, center snapped, fixed radius + Geom::Point c = (nearest + this->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse(); + if (!IS_NAN(c[Geom::X]) && !IS_NAN(c[Geom::Y])) { + Geom::Affine const sm (Geom::Scale(this->hatch_spacing, this->hatch_spacing) * Geom::Translate(c)); + sp_canvas_item_affine_absolute(this->hatch_area, sm); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_item_show(this->hatch_area); + } + } + } else { + sp_canvas_item_hide(this->hatch_area); + } + } + break; + + + case GDK_BUTTON_RELEASE: + { + Geom::Point const motion_w(event->button.x, event->button.y); + Geom::Point const motion_dt(desktop->w2d(motion_w)); + + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time); + desktop->canvas->endForcedFullRedraws(); + this->is_drawing = false; + + if (this->dragging && event->button.button == 1 && !this->space_panning) { + this->dragging = FALSE; + + this->apply(motion_dt); + + /* Remove all temporary line segments */ + while (this->segments) { + sp_canvas_item_destroy(SP_CANVAS_ITEM(this->segments->data)); + this->segments = g_slist_remove(this->segments, this->segments->data); + } + + /* Create object */ + this->fit_and_split(true); + if (this->accumulate()) + this->set_to_accumulated(event->button.state & GDK_SHIFT_MASK, event->button.state & GDK_MOD1_MASK); // performs document_done + else + g_warning ("Failed to create path: invalid data in dc->cal1 or dc->cal2"); + + /* reset accumulated curve */ + this->accumulated->reset(); + + this->clear_current(); + if (this->repr) { + this->repr = NULL; + } + + if (!this->hatch_pointer_past.empty()) this->hatch_pointer_past.clear(); + if (!this->hatch_nearest_past.empty()) this->hatch_nearest_past.clear(); + if (!this->inertia_vectors.empty()) this->inertia_vectors.clear(); + if (!this->hatch_vectors.empty()) this->hatch_vectors.clear(); + this->hatch_last_nearest = Geom::Point(0,0); + this->hatch_last_pointer = Geom::Point(0,0); + this->hatch_escaped = false; + this->hatch_item = NULL; + this->hatch_livarot_path = NULL; + this->just_started_drawing = false; + + if (this->hatch_spacing != 0 && !this->keep_selected) { + // we do not select the newly drawn path, so increase spacing by step + if (this->hatch_spacing_step == 0) { + this->hatch_spacing_step = this->hatch_spacing; + } + this->hatch_spacing += this->hatch_spacing_step; + } + + this->message_context->clear(); + ret = TRUE; + } + break; + } + + case GDK_KEY_PRESS: + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Up: + case GDK_KEY_KP_Up: + if (!MOD__CTRL_ONLY(event)) { + this->angle += 5.0; + if (this->angle > 90.0) + this->angle = 90.0; + sp_ddc_update_toolbox (desktop, "calligraphy-angle", this->angle); + ret = TRUE; + } + break; + case GDK_KEY_Down: + case GDK_KEY_KP_Down: + if (!MOD__CTRL_ONLY(event)) { + this->angle -= 5.0; + if (this->angle < -90.0) + this->angle = -90.0; + sp_ddc_update_toolbox (desktop, "calligraphy-angle", this->angle); + ret = TRUE; + } + break; + case GDK_KEY_Right: + case GDK_KEY_KP_Right: + if (!MOD__CTRL_ONLY(event)) { + this->width += 0.01; + if (this->width > 1.0) + this->width = 1.0; + sp_ddc_update_toolbox (desktop, "altx-calligraphy", this->width * 100); // the same spinbutton is for alt+x + ret = TRUE; + } + break; + case GDK_KEY_Left: + case GDK_KEY_KP_Left: + if (!MOD__CTRL_ONLY(event)) { + this->width -= 0.01; + if (this->width < 0.01) + this->width = 0.01; + sp_ddc_update_toolbox (desktop, "altx-calligraphy", this->width * 100); + ret = TRUE; + } + break; + case GDK_KEY_Home: + case GDK_KEY_KP_Home: + this->width = 0.01; + sp_ddc_update_toolbox (desktop, "altx-calligraphy", this->width * 100); + ret = TRUE; + break; + case GDK_KEY_End: + case GDK_KEY_KP_End: + this->width = 1.0; + sp_ddc_update_toolbox (desktop, "altx-calligraphy", this->width * 100); + ret = TRUE; + break; + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo ("altx-calligraphy"); + ret = TRUE; + } + break; + case GDK_KEY_Escape: + if (this->is_drawing) { + // if drawing, cancel, otherwise pass it up for deselecting + this->cancel(); + ret = TRUE; + } + break; + case GDK_KEY_z: + case GDK_KEY_Z: + if (MOD__CTRL_ONLY(event) && this->is_drawing) { + // if drawing, cancel, otherwise pass it up for undo + this->cancel(); + ret = TRUE; + } + break; + default: + break; + } + break; + + case GDK_KEY_RELEASE: + switch (get_group0_keyval(&event->key)) { + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + this->message_context->clear(); + this->hatch_spacing = 0; + this->hatch_spacing_step = 0; + break; + default: + break; + } + break; + + default: + break; + } + + if (!ret) { +// if ((SP_EVENT_CONTEXT_CLASS(sp_dyna_draw_context_parent_class))->root_handler) { +// ret = (SP_EVENT_CONTEXT_CLASS(sp_dyna_draw_context_parent_class))->root_handler(event_context, event); +// } + ret = DynamicBase::root_handler(event); + } + + return ret; +} + + +void CalligraphicTool::clear_current() { + /* reset bpath */ + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->currentshape), NULL); + /* reset curve */ + this->currentcurve->reset(); + this->cal1->reset(); + this->cal2->reset(); + /* reset points */ + this->npoints = 0; +} + +void CalligraphicTool::set_to_accumulated(bool unionize, bool subtract) { + if (!this->accumulated->is_empty()) { + if (!this->repr) { + /* Create object */ + Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); + Inkscape::XML::Node *repr = xml_doc->createElement("svg:path"); + + /* Set style */ + sp_desktop_apply_style_tool (desktop, repr, "/tools/calligraphic", false); + + this->repr = repr; + + SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(this->repr)); + Inkscape::GC::release(this->repr); + item->transform = SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); + item->updateRepr(); + } + + Geom::PathVector pathv = this->accumulated->get_pathvector() * desktop->dt2doc(); + gchar *str = sp_svg_write_path(pathv); + g_assert( str != NULL ); + this->repr->setAttribute("d", str); + g_free(str); + + if (unionize) { + sp_desktop_selection(desktop)->add(this->repr); + sp_selected_path_union_skip_undo(sp_desktop_selection(desktop), desktop); + } else if (subtract) { + sp_desktop_selection(desktop)->add(this->repr); + sp_selected_path_diff_skip_undo(sp_desktop_selection(desktop), desktop); + } else { + if (this->keep_selected) { + sp_desktop_selection(desktop)->set(this->repr); + } + } + + // Now we need to write the transform information. + // First, find out whether our repr is still linked to a valid object. In this case, + // we need to write the transform data only for this element. + // Either there was no boolean op or it failed. + SPItem *result = SP_ITEM(desktop->doc()->getObjectByRepr(this->repr)); + + if (result == NULL) { + // The boolean operation succeeded. + // Now we fetch the single item, that has been set as selected by the boolean op. + // This is its result. + result = desktop->getSelection()->singleItem(); + } + + result->doWriteTransform(result->getRepr(), result->transform, NULL, true); + } else { + if (this->repr) { + sp_repr_unparent(this->repr); + } + + this->repr = NULL; + } + + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC, + _("Draw calligraphic stroke")); +} + +static void +add_cap(SPCurve *curve, + Geom::Point const &from, + Geom::Point const &to, + double rounding) +{ + if (Geom::L2( to - from ) > DYNA_EPSILON) { + Geom::Point vel = rounding * Geom::rot90( to - from ) / sqrt(2.0); + double mag = Geom::L2(vel); + + Geom::Point v = mag * Geom::rot90( to - from ) / Geom::L2( to - from ); + curve->curveto(from + v, to + v, to); + } +} + +bool CalligraphicTool::accumulate() { + if ( + this->cal1->is_empty() || + this->cal2->is_empty() || + (this->cal1->get_segment_count() <= 0) || + this->cal1->first_path()->closed() + ) { + + this->cal1->reset(); + this->cal2->reset(); + + return false; // failure + } + + SPCurve *rev_cal2 = this->cal2->create_reverse(); + + if ((rev_cal2->get_segment_count() <= 0) || rev_cal2->first_path()->closed()) { + rev_cal2->unref(); + + this->cal1->reset(); + this->cal2->reset(); + + return false; // failure + } + + Geom::Curve const * dc_cal1_firstseg = this->cal1->first_segment(); + Geom::Curve const * rev_cal2_firstseg = rev_cal2->first_segment(); + Geom::Curve const * dc_cal1_lastseg = this->cal1->last_segment(); + Geom::Curve const * rev_cal2_lastseg = rev_cal2->last_segment(); + + this->accumulated->reset(); /* Is this required ?? */ + + this->accumulated->append(this->cal1, false); + + add_cap(this->accumulated, dc_cal1_lastseg->finalPoint(), rev_cal2_firstseg->initialPoint(), this->cap_rounding); + + this->accumulated->append(rev_cal2, true); + + add_cap(this->accumulated, rev_cal2_lastseg->finalPoint(), dc_cal1_firstseg->initialPoint(), this->cap_rounding); + + this->accumulated->closepath(); + + rev_cal2->unref(); + + this->cal1->reset(); + this->cal2->reset(); + + return true; // success +} + +static double square(double const x) +{ + return x * x; +} + +void CalligraphicTool::fit_and_split(bool release) { + double const tolerance_sq = square( desktop->w2d().descrim() * TOLERANCE_CALLIGRAPHIC ); + +#ifdef DYNA_DRAW_VERBOSE + g_print("[F&S:R=%c]", release?'T':'F'); +#endif + + if (!( this->npoints > 0 && this->npoints < SAMPLING_SIZE )) { + return; // just clicked + } + + if ( this->npoints == SAMPLING_SIZE - 1 || release ) { +#define BEZIER_SIZE 4 +#define BEZIER_MAX_BEZIERS 8 +#define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS ) + +#ifdef DYNA_DRAW_VERBOSE + g_print("[F&S:#] dc->npoints:%d, release:%s\n", + this->npoints, release ? "TRUE" : "FALSE"); +#endif + + /* Current calligraphic */ + if ( this->cal1->is_empty() || this->cal2->is_empty() ) { + /* dc->npoints > 0 */ + /* g_print("calligraphics(1|2) reset\n"); */ + this->cal1->reset(); + this->cal2->reset(); + + this->cal1->moveto(this->point1[0]); + this->cal2->moveto(this->point2[0]); + } + + Geom::Point b1[BEZIER_MAX_LENGTH]; + gint const nb1 = Geom::bezier_fit_cubic_r(b1, this->point1, this->npoints, + tolerance_sq, BEZIER_MAX_BEZIERS); + g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) ); + + Geom::Point b2[BEZIER_MAX_LENGTH]; + gint const nb2 = Geom::bezier_fit_cubic_r(b2, this->point2, this->npoints, + tolerance_sq, BEZIER_MAX_BEZIERS); + g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) ); + + if ( nb1 != -1 && nb2 != -1 ) { + /* Fit and draw and reset state */ +#ifdef DYNA_DRAW_VERBOSE + g_print("nb1:%d nb2:%d\n", nb1, nb2); +#endif + /* CanvasShape */ + if (! release) { + this->currentcurve->reset(); + this->currentcurve->moveto(b1[0]); + for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) { + this->currentcurve->curveto(bp1[1], bp1[2], bp1[3]); + } + this->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]); + for (Geom::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) { + this->currentcurve->curveto(bp2[2], bp2[1], bp2[0]); + } + // FIXME: dc->segments is always NULL at this point?? + if (!this->segments) { // first segment + add_cap(this->currentcurve, b2[0], b1[0], this->cap_rounding); + } + this->currentcurve->closepath(); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->currentshape), this->currentcurve); + } + + /* Current calligraphic */ + for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) { + this->cal1->curveto(bp1[1], bp1[2], bp1[3]); + } + for (Geom::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) { + this->cal2->curveto(bp2[1], bp2[2], bp2[3]); + } + } else { + /* fixme: ??? */ +#ifdef DYNA_DRAW_VERBOSE + g_print("[fit_and_split] failed to fit-cubic.\n"); +#endif + this->draw_temporary_box(); + + for (gint i = 1; i < this->npoints; i++) { + this->cal1->lineto(this->point1[i]); + } + for (gint i = 1; i < this->npoints; i++) { + this->cal2->lineto(this->point2[i]); + } + } + + /* Fit and draw and copy last point */ +#ifdef DYNA_DRAW_VERBOSE + g_print("[%d]Yup\n", this->npoints); +#endif + if (!release) { + g_assert(!this->currentcurve->is_empty()); + + SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(desktop), + SP_TYPE_CANVAS_BPATH, + NULL); + SPCurve *curve = this->currentcurve->copy(); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve); + curve->unref(); + + guint32 fillColor = sp_desktop_get_color_tool (desktop, "/tools/calligraphic", true); + //guint32 strokeColor = sp_desktop_get_color_tool (desktop, "/tools/calligraphic", false); + double opacity = sp_desktop_get_master_opacity_tool (desktop, "/tools/calligraphic"); + double fillOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/calligraphic", true); + //double strokeOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/calligraphic", false); + sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD); + //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing + //sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), ((strokeColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*strokeOpacity)), 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + /* fixme: Cannot we cascade it to root more clearly? */ + g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), desktop); + + this->segments = g_slist_prepend(this->segments, cbp); + } + + this->point1[0] = this->point1[this->npoints - 1]; + this->point2[0] = this->point2[this->npoints - 1]; + this->npoints = 1; + } else { + this->draw_temporary_box(); + } +} + +void CalligraphicTool::draw_temporary_box() { + this->currentcurve->reset(); + + this->currentcurve->moveto(this->point2[this->npoints-1]); + + for (gint i = this->npoints-2; i >= 0; i--) { + this->currentcurve->lineto(this->point2[i]); + } + + for (gint i = 0; i < this->npoints; i++) { + this->currentcurve->lineto(this->point1[i]); + } + + if (this->npoints >= 2) { + add_cap(this->currentcurve, this->point1[this->npoints-1], this->point2[this->npoints-1], this->cap_rounding); + } + + this->currentcurve->closepath(); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->currentshape), this->currentcurve); +} + +} +} +} + + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/calligraphic-tool.h b/src/ui/tools/calligraphic-tool.h new file mode 100644 index 000000000..926e9d126 --- /dev/null +++ b/src/ui/tools/calligraphic-tool.h @@ -0,0 +1,94 @@ +#ifndef SP_DYNA_DRAW_CONTEXT_H_SEEN +#define SP_DYNA_DRAW_CONTEXT_H_SEEN + +/* + * Handwriting-like drawing mode + * + * Authors: + * Mitsuru Oka <oka326@parkcity.ne.jp> + * Lauris Kaplinski <lauris@kaplinski.com> + * + * The original dynadraw code: + * Paul Haeberli <paul@sgi.com> + * + * Copyright (C) 1998 The Free Software Foundation + * Copyright (C) 1999-2002 authors + * Copyright (C) 2001-2002 Ximian, Inc. + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "ui/tools/dynamic-base.h" +#include "splivarot.h" + +#define DDC_MIN_PRESSURE 0.0 +#define DDC_MAX_PRESSURE 1.0 +#define DDC_DEFAULT_PRESSURE 1.0 + +#define DDC_MIN_TILT -1.0 +#define DDC_MAX_TILT 1.0 +#define DDC_DEFAULT_TILT 0.0 + +namespace Inkscape { +namespace UI { +namespace Tools { + +class CalligraphicTool : public DynamicBase { +public: + CalligraphicTool(); + virtual ~CalligraphicTool(); + + static const std::string prefsPath; + + virtual void setup(); + virtual void set(const Inkscape::Preferences::Entry& val); + virtual bool root_handler(GdkEvent* event); + + virtual const std::string& getPrefsPath(); + +private: + /** newly created object remain selected */ + bool keep_selected; + + double hatch_spacing; + double hatch_spacing_step; + SPItem *hatch_item; + Path *hatch_livarot_path; + std::list<double> hatch_nearest_past; + std::list<double> hatch_pointer_past; + std::list<Geom::Point> inertia_vectors; + Geom::Point hatch_last_nearest, hatch_last_pointer; + std::list<Geom::Point> hatch_vectors; + bool hatch_escaped; + SPCanvasItem *hatch_area; + bool just_started_drawing; + bool trace_bg; + + void clear_current(); + void set_to_accumulated(bool unionize, bool subtract); + bool accumulate(); + void fit_and_split(bool release); + void draw_temporary_box(); + void cancel(); + void brush(); + bool apply(Geom::Point p); + void extinput(GdkEvent *event); + void reset(Geom::Point p); +}; + +} +} +} + +#endif // SP_DYNA_DRAW_CONTEXT_H_SEEN + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/connector-tool.cpp b/src/ui/tools/connector-tool.cpp new file mode 100644 index 000000000..d2e23837c --- /dev/null +++ b/src/ui/tools/connector-tool.cpp @@ -0,0 +1,1426 @@ +/* + * Connector creation tool + * + * Authors: + * Michael Wybrow <mjwybrow@users.sourceforge.net> + * Abhishek Sharma + * Jon A. Cruz <jon@joncruz.org> + * Martin Owens <doctormo@gmail.com> + * + * Copyright (C) 2005-2008 Michael Wybrow + * Copyright (C) 2009 Monash University + * Copyright (C) 2012 Authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + * + * TODO: + * o Show a visual indicator for objects with the 'avoid' property set. + * o Allow user to change a object between a path and connector through + * the interface. + * o Create an interface for setting markers (arrow heads). + * o Better distinguish between paths and connectors to prevent problems + * in the node tool and paths accidentally being turned into connectors + * in the connector tool. Perhaps have a way to convert between. + * o Only call libavoid's updateEndPoint as required. Currently we do it + * for both endpoints, even if only one is moving. + * o Deal sanely with connectors with both endpoints attached to the + * same connection point, and drawing of connectors attaching + * overlapping shapes (currently tries to adjust connector to be + * outside both bounding boxes). + * o Fix many special cases related to connectors updating, + * e.g., copying a couple of shapes and a connector that are + * attached to each other. + * e.g., detach connector when it is moved or transformed in + * one of the other contexts. + * o Cope with shapes whose ids change when they have attached + * connectors. + * o During dragging motion, gobble up to and use the final motion event. + * Gobbling away all duplicates after the current can occasionally result + * in the path lagging behind the mouse cursor if it is no longer being + * dragged. + * o Fix up libavoid's representation after undo actions. It doesn't see + * any transform signals and hence doesn't know shapes have moved back to + * there earlier positions. + * + * ---------------------------------------------------------------------------- + * + * Notes: + * + * Much of the way connectors work for user-defined points has been + * changed so that it no longer defines special attributes to record + * the points. Instead it uses single node paths to define points + * who are then seperate objects that can be fixed on the canvas, + * grouped into objects and take full advantage of all transform, snap + * and align functionality of all other objects. + * + * I think that the style change between polyline and orthogonal + * would be much clearer with two buttons (radio behaviour -- just + * one is true). + * + * The other tools show a label change from "New:" to "Change:" + * depending on whether an object is selected. We could consider + * this but there may not be space. + * + * Likewise for the avoid/ignore shapes buttons. These should be + * inactive when a shape is not selected in the connector context. + * + */ + + + +#include <gdk/gdkkeysyms.h> +#include <string> +#include <cstring> + +#include "ui/tools/connector-tool.h" +#include "pixmaps/cursor-connector.xpm" +#include "xml/node-event-vector.h" +#include "xml/repr.h" +#include "svg/svg.h" +#include "desktop.h" +#include "desktop-style.h" +#include "desktop-handles.h" +#include "document.h" +#include "document-undo.h" +#include "message-context.h" +#include "message-stack.h" +#include "selection.h" +#include "inkscape.h" +#include "preferences.h" +#include "sp-path.h" +#include "display/sp-canvas.h" +#include "display/canvas-bpath.h" +#include "display/sodipodi-ctrl.h" +#include <glibmm/i18n.h> +#include <glibmm/stringutils.h> +#include "snap.h" +#include "knot.h" +#include "sp-conn-end.h" +#include "sp-conn-end-pair.h" +#include "conn-avoid-ref.h" +#include "libavoid/vertices.h" +#include "libavoid/router.h" +#include "context-fns.h" +#include "sp-namedview.h" +#include "sp-text.h" +#include "sp-flowtext.h" +#include "display/curve.h" +#include "verbs.h" + +using Inkscape::DocumentUndo; + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +static void cc_clear_active_knots(SPKnotList k); + +static void shape_event_attr_deleted(Inkscape::XML::Node *repr, + Inkscape::XML::Node *child, Inkscape::XML::Node *ref, gpointer data); + +static void shape_event_attr_changed(Inkscape::XML::Node *repr, gchar const *name, + gchar const *old_value, gchar const *new_value, bool is_interactive, + gpointer data); + +static void cc_select_handle(SPKnot* knot); +static void cc_deselect_handle(SPKnot* knot); +static bool cc_item_is_shape(SPItem *item); + +/*static Geom::Point connector_drag_origin_w(0, 0); +static bool connector_within_tolerance = false;*/ + +static Inkscape::XML::NodeEventVector shape_repr_events = { + NULL, /* child_added */ + NULL, /* child_added */ + shape_event_attr_changed, + NULL, /* content_changed */ + NULL /* order_changed */ +}; + +static Inkscape::XML::NodeEventVector layer_repr_events = { + NULL, /* child_added */ + shape_event_attr_deleted, + NULL, /* child_added */ + NULL, /* content_changed */ + NULL /* order_changed */ +}; + +namespace { + ToolBase* createConnectorContext() { + return new ConnectorTool(); + } + + bool connectorContextRegistered = ToolFactory::instance().registerObject("/tools/connector", createConnectorContext); +} + +const std::string& ConnectorTool::getPrefsPath() { + return ConnectorTool::prefsPath; +} + +const std::string ConnectorTool::prefsPath = "/tools/connector"; + +ConnectorTool::ConnectorTool() + : ToolBase(cursor_connector_xpm, 1, 1) + , selection(NULL) + , npoints(0) + , state(SP_CONNECTOR_CONTEXT_IDLE) + , red_bpath(NULL) + , red_curve(NULL) + , red_color(0xff00007f) + , green_curve(NULL) + , newconn(NULL) + , newConnRef(NULL) + , curvature(0.0) + , isOrthogonal(false) + , active_shape(NULL) + , active_shape_repr(NULL) + , active_shape_layer_repr(NULL) + , active_conn(NULL) + , active_conn_repr(NULL) + , active_handle(NULL) + , selected_handle(NULL) + , clickeditem(NULL) + , clickedhandle(NULL) + , shref(NULL) + , ehref(NULL) + , c0(NULL) + , c1(NULL) + , cl0(NULL) + , cl1(NULL) +{ + for (int i = 0; i < 2; ++i) { + this->endpt_handle[i] = NULL; + this->endpt_handler_id[i] = 0; + } +} + +ConnectorTool::~ConnectorTool() { + this->sel_changed_connection.disconnect(); + + for (int i = 0; i < 2; ++i) { + if (this->endpt_handle[1]) { + g_object_unref(this->endpt_handle[i]); + this->endpt_handle[i] = NULL; + } + } + + if (this->shref) { + g_free(this->shref); + this->shref = NULL; + } + + if (this->ehref) { + g_free(this->shref); + this->shref = NULL; + } + + g_assert( this->newConnRef == NULL ); +} + +void ConnectorTool::setup() { + ToolBase::setup(); + + this->selection = sp_desktop_selection(this->desktop); + + this->sel_changed_connection.disconnect(); + this->sel_changed_connection = this->selection->connectChanged( + sigc::mem_fun(this, &ConnectorTool::_selectionChanged) + ); + + /* Create red bpath */ + this->red_bpath = sp_canvas_bpath_new(sp_desktop_sketch(this->desktop), NULL); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->red_bpath), this->red_color, + 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(this->red_bpath), 0x00000000, + SP_WIND_RULE_NONZERO); + /* Create red curve */ + this->red_curve = new SPCurve(); + + /* Create green curve */ + this->green_curve = new SPCurve(); + + // Notice the initial selection. + //cc_selection_changed(this->selection, (gpointer) this); + this->_selectionChanged(this->selection); + + this->within_tolerance = false; + + sp_event_context_read(this, "curvature"); + sp_event_context_read(this, "orthogonal"); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/tools/connector/selcue", 0)) { + this->enableSelectionCue(); + } + + // Make sure we see all enter events for canvas items, + // even if a mouse button is depressed. + this->desktop->canvas->gen_all_enter_events = true; +} + +void ConnectorTool::set(const Inkscape::Preferences::Entry& val) { + /* fixme: Proper error handling for non-numeric data. Use a locale-independent function like + * g_ascii_strtod (or a thin wrapper that does the right thing for invalid values inf/nan). */ + Glib::ustring name = val.getEntryName(); + + if (name == "curvature") { + this->curvature = val.getDoubleLimited(); // prevents NaN and +/-Inf from messing up + } else if (name == "orthogonal") { + this->isOrthogonal = val.getBool(); + } +} + +void ConnectorTool::finish() { + this->_finish(); + this->state = SP_CONNECTOR_CONTEXT_IDLE; + + ToolBase::finish(); + + if (this->selection) { + this->selection = NULL; + } + + this->cc_clear_active_shape(); + this->cc_clear_active_conn(); + + // Restore the default event generating behaviour. + this->desktop->canvas->gen_all_enter_events = false; +} + +//----------------------------------------------------------------------------- + + +void ConnectorTool::cc_clear_active_shape() { + if (this->active_shape == NULL) { + return; + } + g_assert( this->active_shape_repr ); + g_assert( this->active_shape_layer_repr ); + + this->active_shape = NULL; + + if (this->active_shape_repr) { + sp_repr_remove_listener_by_data(this->active_shape_repr, this); + Inkscape::GC::release(this->active_shape_repr); + this->active_shape_repr = NULL; + + sp_repr_remove_listener_by_data(this->active_shape_layer_repr, this); + Inkscape::GC::release(this->active_shape_layer_repr); + this->active_shape_layer_repr = NULL; + } + + cc_clear_active_knots(this->knots); +} + +static void +cc_clear_active_knots(SPKnotList k) +{ + // Hide the connection points if they exist. + if (k.size()) { + for (SPKnotList::iterator it = k.begin(); it != k.end(); ++it) { + sp_knot_hide(it->first); + } + } +} + +void ConnectorTool::cc_clear_active_conn() { + if (this->active_conn == NULL) { + return; + } + g_assert( this->active_conn_repr ); + + this->active_conn = NULL; + + if (this->active_conn_repr) { + sp_repr_remove_listener_by_data(this->active_conn_repr, this); + Inkscape::GC::release(this->active_conn_repr); + this->active_conn_repr = NULL; + } + + // Hide the endpoint handles. + for (int i = 0; i < 2; ++i) { + if (this->endpt_handle[i]) { + sp_knot_hide(this->endpt_handle[i]); + } + } +} + + +bool ConnectorTool::_ptHandleTest(Geom::Point& p, gchar **href) { + if (this->active_handle && (this->knots.find(this->active_handle) != this->knots.end())) + { + p = this->active_handle->pos; + *href = g_strdup_printf("#%s", this->active_handle->owner->getId()); + return true; + } + *href = NULL; + return false; +} + +static void +cc_select_handle(SPKnot* knot) +{ + knot->setShape(SP_KNOT_SHAPE_SQUARE); + knot->setSize(10); + knot->setAnchor(SP_ANCHOR_CENTER); + knot->setFill(0x0000ffff, 0x0000ffff, 0x0000ffff); + sp_knot_update_ctrl(knot); +} + +static void +cc_deselect_handle(SPKnot* knot) +{ + knot->setShape(SP_KNOT_SHAPE_SQUARE); + knot->setSize(8); + knot->setAnchor(SP_ANCHOR_CENTER); + knot->setFill(0xffffff00, 0xff0000ff, 0xff0000ff); + sp_knot_update_ctrl(knot); +} + +bool ConnectorTool::item_handler(SPItem* item, GdkEvent* event) { + gint ret = FALSE; + + Geom::Point p(event->button.x, event->button.y); + + switch (event->type) { + case GDK_BUTTON_RELEASE: + if (event->button.button == 1 && !this->space_panning) { + if ((this->state == SP_CONNECTOR_CONTEXT_DRAGGING) && this->within_tolerance) { + this->_resetColors(); + this->state = SP_CONNECTOR_CONTEXT_IDLE; + } + + if (this->state != SP_CONNECTOR_CONTEXT_IDLE) { + // Doing something else like rerouting. + break; + } + + // find out clicked item, honoring Alt + SPItem *item = sp_event_context_find_item(desktop, p, event->button.state & GDK_MOD1_MASK, FALSE); + + if (event->button.state & GDK_SHIFT_MASK) { + this->selection->toggle(item); + } else { + this->selection->set(item); + /* When selecting a new item, do not allow showing + connection points on connectors. (yet?) + */ + + if (item != this->active_shape && !cc_item_is_connector(item)) { + this->_setActiveShape(item); + } + } + + ret = TRUE; + } + break; + + case GDK_ENTER_NOTIFY: + if (!this->selected_handle) { + if (cc_item_is_shape(item)) { + this->_setActiveShape(item); + } + + ret = TRUE; + } + break; + + default: + break; + } + + return ret; +} + +bool ConnectorTool::root_handler(GdkEvent* event) { + gint ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + ret = this->_handleButtonPress(event->button); + break; + + case GDK_MOTION_NOTIFY: + ret = this->_handleMotionNotify(event->motion); + break; + + case GDK_BUTTON_RELEASE: + ret = this->_handleButtonRelease(event->button); + break; + + case GDK_KEY_PRESS: + ret = this->_handleKeyPress(get_group0_keyval (&event->key)); + break; + + default: + break; + } + + if (!ret) { + ret = ToolBase::root_handler(event); + } + + return ret; +} + + +gint ConnectorTool::_handleButtonPress(GdkEventButton const &bevent) { + Geom::Point const event_w(bevent.x, bevent.y); + /* Find desktop coordinates */ + Geom::Point p = this->desktop->w2d(event_w); + ToolBase *event_context = SP_EVENT_CONTEXT(this); + + gint ret = FALSE; + + if ( bevent.button == 1 && !event_context->space_panning ) { + + SPDesktop *desktop = this->desktop; + + if (Inkscape::have_viable_layer(desktop, this->message_context) == false) { + return TRUE; + } + + Geom::Point const event_w(bevent.x, + bevent.y); + + this->xp = bevent.x; + this->yp = bevent.y; + this->within_tolerance = true; + + Geom::Point const event_dt = this->desktop->w2d(event_w); + + SnapManager &m = this->desktop->namedview->snap_manager; + + switch (this->state) { + case SP_CONNECTOR_CONTEXT_STOP: + /* This is allowed, if we just canceled curve */ + case SP_CONNECTOR_CONTEXT_IDLE: + { + if ( this->npoints == 0 ) { + this->cc_clear_active_conn(); + + this->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new connector")); + + /* Set start anchor */ + /* Create green anchor */ + Geom::Point p = event_dt; + + // Test whether we clicked on a connection point + bool found = this->_ptHandleTest(p, &this->shref); + + if (!found) { + // This is the first point, so just snap it to the grid + // as there's no other points to go off. + m.setup(this->desktop); + m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_OTHER_HANDLE); + m.unSetup(); + } + this->_setInitialPoint(p); + + } + this->state = SP_CONNECTOR_CONTEXT_DRAGGING; + ret = TRUE; + break; + } + case SP_CONNECTOR_CONTEXT_DRAGGING: + { + // This is the second click of a connector creation. + m.setup(this->desktop); + m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_OTHER_HANDLE); + m.unSetup(); + + this->_setSubsequentPoint(p); + this->_finishSegment(p); + + this->_ptHandleTest(p, &this->ehref); + if (this->npoints != 0) { + this->_finish(); + } + this->cc_set_active_conn(this->newconn); + this->state = SP_CONNECTOR_CONTEXT_IDLE; + ret = TRUE; + break; + } + case SP_CONNECTOR_CONTEXT_CLOSE: + { + g_warning("Button down in CLOSE state"); + break; + } + default: + break; + } + } else if (bevent.button == 3) { + if (this->state == SP_CONNECTOR_CONTEXT_REROUTING) { + // A context menu is going to be triggered here, + // so end the rerouting operation. + this->_reroutingFinish(&p); + + this->state = SP_CONNECTOR_CONTEXT_IDLE; + + // Don't set ret to TRUE, so we drop through to the + // parent handler which will open the context menu. + } + else if (this->npoints != 0) { + this->_finish(); + this->state = SP_CONNECTOR_CONTEXT_IDLE; + ret = TRUE; + } + } + return ret; +} + +gint ConnectorTool::_handleMotionNotify(GdkEventMotion const &mevent) { + gint ret = FALSE; + ToolBase *event_context = SP_EVENT_CONTEXT(this); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) { + // allow middle-button scrolling + return FALSE; + } + + Geom::Point const event_w(mevent.x, mevent.y); + + if (this->within_tolerance) { + this->tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + if ( ( abs( (gint) mevent.x - this->xp ) < this->tolerance ) && + ( abs( (gint) mevent.y - this->yp ) < this->tolerance ) ) { + return FALSE; // Do not drag if we're within tolerance from origin. + } + } + // Once the user has moved farther than tolerance from the original location + // (indicating they intend to move the object, not click), then always process + // the motion notify coordinates as given (no snapping back to origin) + this->within_tolerance = false; + + SPDesktop *const dt = this->desktop; + + /* Find desktop coordinates */ + Geom::Point p = dt->w2d(event_w); + + SnapManager &m = dt->namedview->snap_manager; + + switch (this->state) { + case SP_CONNECTOR_CONTEXT_DRAGGING: + { + gobble_motion_events(mevent.state); + // This is movement during a connector creation. + if ( this->npoints > 0 ) { + m.setup(dt); + m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_OTHER_HANDLE); + m.unSetup(); + this->selection->clear(); + this->_setSubsequentPoint(p); + ret = TRUE; + } + break; + } + case SP_CONNECTOR_CONTEXT_REROUTING: + { + gobble_motion_events(GDK_BUTTON1_MASK); + g_assert( SP_IS_PATH(this->clickeditem)); + + m.setup(dt); + m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_OTHER_HANDLE); + m.unSetup(); + + // Update the hidden path + Geom::Affine i2d ( (this->clickeditem)->i2dt_affine() ); + Geom::Affine d2i = i2d.inverse(); + SPPath *path = SP_PATH(this->clickeditem); + SPCurve *curve = path->get_curve(); + if (this->clickedhandle == this->endpt_handle[0]) { + Geom::Point o = this->endpt_handle[1]->pos; + curve->stretch_endpoints(p * d2i, o * d2i); + } + else { + Geom::Point o = this->endpt_handle[0]->pos; + curve->stretch_endpoints(o * d2i, p * d2i); + } + sp_conn_reroute_path_immediate(path); + + // Copy this to the temporary visible path + this->red_curve = path->get_curve_for_edit(); + this->red_curve->transform(i2d); + + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), this->red_curve); + ret = TRUE; + break; + } + case SP_CONNECTOR_CONTEXT_STOP: + /* This is perfectly valid */ + break; + default: + if (!this->sp_event_context_knot_mouseover()) { + m.setup(dt); + m.preSnap(Inkscape::SnapCandidatePoint(p, Inkscape::SNAPSOURCE_OTHER_HANDLE)); + m.unSetup(); + } + break; + } + return ret; +} + +gint ConnectorTool::_handleButtonRelease(GdkEventButton const &revent) { + gint ret = FALSE; + ToolBase *event_context = SP_EVENT_CONTEXT(this); + if ( revent.button == 1 && !event_context->space_panning ) { + + SPDesktop *desktop = this->desktop; + SPDocument *doc = sp_desktop_document(desktop); + + SnapManager &m = desktop->namedview->snap_manager; + + Geom::Point const event_w(revent.x, revent.y); + + /* Find desktop coordinates */ + Geom::Point p = this->desktop->w2d(event_w); + + switch (this->state) { + //case SP_CONNECTOR_CONTEXT_POINT: + case SP_CONNECTOR_CONTEXT_DRAGGING: + { + m.setup(desktop); + m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_OTHER_HANDLE); + m.unSetup(); + + if (this->within_tolerance) + { + this->_finishSegment(p); + return TRUE; + } + // Connector has been created via a drag, end it now. + this->_setSubsequentPoint(p); + this->_finishSegment(p); + // Test whether we clicked on a connection point + this->_ptHandleTest(p, &this->ehref); + if (this->npoints != 0) { + this->_finish(); + } + this->cc_set_active_conn(this->newconn); + this->state = SP_CONNECTOR_CONTEXT_IDLE; + break; + } + case SP_CONNECTOR_CONTEXT_REROUTING: + { + m.setup(desktop); + m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_OTHER_HANDLE); + m.unSetup(); + this->_reroutingFinish(&p); + + doc->ensureUpToDate(); + this->state = SP_CONNECTOR_CONTEXT_IDLE; + return TRUE; + break; + } + case SP_CONNECTOR_CONTEXT_STOP: + /* This is allowed, if we just cancelled curve */ + break; + default: + break; + } + ret = TRUE; + } + return ret; +} + +gint ConnectorTool::_handleKeyPress(guint const keyval) { + gint ret = FALSE; + + switch (keyval) { + case GDK_KEY_Return: + case GDK_KEY_KP_Enter: + if (this->npoints != 0) { + this->_finish(); + this->state = SP_CONNECTOR_CONTEXT_IDLE; + ret = TRUE; + } + break; + case GDK_KEY_Escape: + if (this->state == SP_CONNECTOR_CONTEXT_REROUTING) { + + SPDesktop *desktop = this->desktop; + SPDocument *doc = sp_desktop_document(desktop); + + this->_reroutingFinish(NULL); + + DocumentUndo::undo(doc); + + this->state = SP_CONNECTOR_CONTEXT_IDLE; + desktop->messageStack()->flash( Inkscape::NORMAL_MESSAGE, + _("Connector endpoint drag cancelled.")); + ret = TRUE; + } + else if (this->npoints != 0) { + // if drawing, cancel, otherwise pass it up for deselecting + this->state = SP_CONNECTOR_CONTEXT_STOP; + this->_resetColors(); + ret = TRUE; + } + break; + default: + break; + } + return ret; +} + +void ConnectorTool::_reroutingFinish(Geom::Point *const p) { + SPDesktop *desktop = this->desktop; + SPDocument *doc = sp_desktop_document(desktop); + + // Clear the temporary path: + this->red_curve->reset(); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), NULL); + + if (p != NULL) + { + // Test whether we clicked on a connection point + gchar *shape_label; + bool found = this->_ptHandleTest(*p, &shape_label); + + if (found) { + if (this->clickedhandle == this->endpt_handle[0]) { + this->clickeditem->setAttribute("inkscape:connection-start", shape_label, NULL); + } + else { + this->clickeditem->setAttribute("inkscape:connection-end", shape_label, NULL); + } + g_free(shape_label); + } + } + this->clickeditem->setHidden(false); + sp_conn_reroute_path_immediate(SP_PATH(this->clickeditem)); + this->clickeditem->updateRepr(); + DocumentUndo::done(doc, SP_VERB_CONTEXT_CONNECTOR, + _("Reroute connector")); + this->cc_set_active_conn(this->clickeditem); +} + + +void ConnectorTool::_resetColors() { + /* Red */ + this->red_curve->reset(); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), NULL); + + this->green_curve->reset(); + this->npoints = 0; +} + +void ConnectorTool::_setInitialPoint(Geom::Point const p) { + g_assert( this->npoints == 0 ); + + this->p[0] = p; + this->p[1] = p; + this->npoints = 2; + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), NULL); +} + +void ConnectorTool::_setSubsequentPoint(Geom::Point const p) { + g_assert( this->npoints != 0 ); + + SPDesktop *dt = this->desktop; + Geom::Point o = dt->dt2doc(this->p[0]); + Geom::Point d = dt->dt2doc(p); + Avoid::Point src(o[Geom::X], o[Geom::Y]); + Avoid::Point dst(d[Geom::X], d[Geom::Y]); + + if (!this->newConnRef) { + Avoid::Router *router = sp_desktop_document(dt)->router; + this->newConnRef = new Avoid::ConnRef(router); + this->newConnRef->setEndpoint(Avoid::VertID::src, src); + if (this->isOrthogonal) + this->newConnRef->setRoutingType(Avoid::ConnType_Orthogonal); + else + this->newConnRef->setRoutingType(Avoid::ConnType_PolyLine); + } + // Set new endpoint. + this->newConnRef->setEndpoint(Avoid::VertID::tar, dst); + // Immediately generate new routes for connector. + this->newConnRef->makePathInvalid(); + this->newConnRef->router()->processTransaction(); + // Recreate curve from libavoid route. + recreateCurve( this->red_curve, this->newConnRef, this->curvature ); + this->red_curve->transform(dt->doc2dt()); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), this->red_curve); +} + + +/** + * Concats red, blue and green. + * If any anchors are defined, process these, optionally removing curves from white list + * Invoke _flush_white to write result back to object. + */ +void ConnectorTool::_concatColorsAndFlush() { + SPCurve *c = this->green_curve; + this->green_curve = new SPCurve(); + + this->red_curve->reset(); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), NULL); + + if (c->is_empty()) { + c->unref(); + return; + } + + this->_flushWhite(c); + + c->unref(); +} + + +/* + * Flushes white curve(s) and additional curve into object + * + * No cleaning of colored curves - this has to be done by caller + * No rereading of white data, so if you cannot rely on ::modified, do it in caller + * + */ + +void ConnectorTool::_flushWhite(SPCurve *gc) { + SPCurve *c; + + if (gc) { + c = gc; + c->ref(); + } else { + return; + } + + /* Now we have to go back to item coordinates at last */ + c->transform(this->desktop->dt2doc()); + + SPDesktop *desktop = this->desktop; + SPDocument *doc = sp_desktop_document(desktop); + Inkscape::XML::Document *xml_doc = doc->getReprDoc(); + + if ( c && !c->is_empty() ) { + /* We actually have something to write */ + + Inkscape::XML::Node *repr = xml_doc->createElement("svg:path"); + /* Set style */ + sp_desktop_apply_style_tool(desktop, repr, "/tools/connector", false); + + gchar *str = sp_svg_write_path( c->get_pathvector() ); + g_assert( str != NULL ); + repr->setAttribute("d", str); + g_free(str); + + /* Attach repr */ + this->newconn = SP_ITEM(desktop->currentLayer()->appendChildRepr(repr)); + this->newconn->transform = SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); + + bool connection = false; + this->newconn->setAttribute( "inkscape:connector-type", + this->isOrthogonal ? "orthogonal" : "polyline", NULL ); + this->newconn->setAttribute( "inkscape:connector-curvature", + Glib::Ascii::dtostr(this->curvature).c_str(), NULL ); + if (this->shref) + { + this->newconn->setAttribute( "inkscape:connection-start", this->shref, NULL); + connection = true; + } + + if (this->ehref) + { + this->newconn->setAttribute( "inkscape:connection-end", this->ehref, NULL); + connection = true; + } + // Process pending updates. + this->newconn->updateRepr(); + doc->ensureUpToDate(); + + if (connection) { + // Adjust endpoints to shape edge. + sp_conn_reroute_path_immediate(SP_PATH(this->newconn)); + this->newconn->updateRepr(); + } + + this->newconn->doWriteTransform(this->newconn->getRepr(), this->newconn->transform, NULL, true); + + // Only set the selection after we are finished with creating the attributes of + // the connector. Otherwise, the selection change may alter the defaults for + // values like curvature in the connector context, preventing subsequent lookup + // of their original values. + this->selection->set(repr); + Inkscape::GC::release(repr); + } + + c->unref(); + + DocumentUndo::done(doc, SP_VERB_CONTEXT_CONNECTOR, _("Create connector")); +} + + +void ConnectorTool::_finishSegment(Geom::Point const /*p*/) { + if (!this->red_curve->is_empty()) { + this->green_curve->append_continuous(this->red_curve, 0.0625); + + this->p[0] = this->p[3]; + this->p[1] = this->p[4]; + this->npoints = 2; + + this->red_curve->reset(); + } +} + +void ConnectorTool::_finish() { + SPDesktop *const desktop = this->desktop; + desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing connector")); + + this->red_curve->reset(); + this->_concatColorsAndFlush(); + + this->npoints = 0; + + if (this->newConnRef) { + this->newConnRef->removeFromGraph(); + delete this->newConnRef; + this->newConnRef = NULL; + } +} + + +static gboolean +cc_generic_knot_handler(SPCanvasItem *, GdkEvent *event, SPKnot *knot) +{ + g_assert (knot != NULL); + + g_object_ref(knot); + + ConnectorTool *cc = SP_CONNECTOR_CONTEXT( + knot->desktop->event_context); + + gboolean consumed = FALSE; + + gchar const *knot_tip = "Click to join at this point"; + switch (event->type) { + case GDK_ENTER_NOTIFY: + sp_knot_set_flag(knot, SP_KNOT_MOUSEOVER, TRUE); + + cc->active_handle = knot; + if (knot_tip) + { + knot->desktop->event_context->defaultMessageContext()->set( + Inkscape::NORMAL_MESSAGE, knot_tip); + } + + consumed = TRUE; + break; + case GDK_LEAVE_NOTIFY: + sp_knot_set_flag(knot, SP_KNOT_MOUSEOVER, FALSE); + + /* FIXME: the following test is a workaround for LP Bug #1273510. + * It seems that a signal is not correctly disconnected, maybe + * something missing in cc_clear_active_conn()? */ + if (cc) { + cc->active_handle = NULL; + } + + if (knot_tip) { + knot->desktop->event_context->defaultMessageContext()->clear(); + } + + consumed = TRUE; + break; + default: + break; + } + + g_object_unref(knot); + + return consumed; +} + + +static gboolean +endpt_handler(SPKnot */*knot*/, GdkEvent *event, ConnectorTool *cc) +{ + //g_assert( SP_IS_CONNECTOR_CONTEXT(cc) ); + + gboolean consumed = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + g_assert( (cc->active_handle == cc->endpt_handle[0]) || + (cc->active_handle == cc->endpt_handle[1]) ); + if (cc->state == SP_CONNECTOR_CONTEXT_IDLE) { + cc->clickeditem = cc->active_conn; + cc->clickedhandle = cc->active_handle; + cc->cc_clear_active_conn(); + cc->state = SP_CONNECTOR_CONTEXT_REROUTING; + + // Disconnect from attached shape + unsigned ind = (cc->active_handle == cc->endpt_handle[0]) ? 0 : 1; + sp_conn_end_detach(cc->clickeditem, ind); + + Geom::Point origin; + if (cc->clickedhandle == cc->endpt_handle[0]) { + origin = cc->endpt_handle[1]->pos; + } + else { + origin = cc->endpt_handle[0]->pos; + } + + // Show the red path for dragging. + cc->red_curve = SP_PATH(cc->clickeditem)->get_curve_for_edit(); + Geom::Affine i2d = (cc->clickeditem)->i2dt_affine(); + cc->red_curve->transform(i2d); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(cc->red_bpath), cc->red_curve); + + cc->clickeditem->setHidden(true); + + // The rest of the interaction rerouting the connector is + // handled by the context root handler. + consumed = TRUE; + } + break; + default: + break; + } + + return consumed; +} + +void ConnectorTool::_activeShapeAddKnot(SPItem* item) { + SPDesktop *desktop = this->desktop; + SPKnot *knot = sp_knot_new(desktop, 0); + + knot->owner = item; + knot->setShape(SP_KNOT_SHAPE_SQUARE); + knot->setSize(8); + knot->setAnchor(SP_ANCHOR_CENTER); + knot->setFill(0xffffff00, 0xff0000ff, 0xff0000ff); + sp_knot_update_ctrl(knot); + + // We don't want to use the standard knot handler. + g_signal_handler_disconnect(G_OBJECT(knot->item), + knot->_event_handler_id); + knot->_event_handler_id = 0; + + g_signal_connect(G_OBJECT(knot->item), "event", + G_CALLBACK(cc_generic_knot_handler), knot); + sp_knot_set_position(knot, item->avoidRef->getConnectionPointPos() * desktop->doc2dt(), 0); + sp_knot_show(knot); + this->knots[knot] = 1; +} + +void ConnectorTool::_setActiveShape(SPItem *item) { + g_assert(item != NULL ); + + if (this->active_shape != item) + { + // The active shape has changed + // Rebuild everything + this->active_shape = item; + // Remove existing active shape listeners + if (this->active_shape_repr) { + sp_repr_remove_listener_by_data(this->active_shape_repr, this); + Inkscape::GC::release(this->active_shape_repr); + + sp_repr_remove_listener_by_data(this->active_shape_layer_repr, this); + Inkscape::GC::release(this->active_shape_layer_repr); + } + + // Listen in case the active shape changes + this->active_shape_repr = item->getRepr(); + if (this->active_shape_repr) { + Inkscape::GC::anchor(this->active_shape_repr); + sp_repr_add_listener(this->active_shape_repr, &shape_repr_events, this); + + this->active_shape_layer_repr = this->active_shape_repr->parent(); + Inkscape::GC::anchor(this->active_shape_layer_repr); + sp_repr_add_listener(this->active_shape_layer_repr, &layer_repr_events, this); + } + + cc_clear_active_knots(this->knots); + + // The idea here is to try and add a group's children to solidify + // connection handling. We react to path objects with only one node. + for (SPObject *child = item->firstChild() ; child ; child = child->getNext() ) { + if (SP_IS_PATH(child) && SP_PATH(child)->nodesInPath() == 1) { + this->_activeShapeAddKnot((SPItem *) child); + } + } + this->_activeShapeAddKnot(item); + + } + else + { + // Ensure the item's connection_points map + // has been updated + item->document->ensureUpToDate(); + } +} + +void ConnectorTool::cc_set_active_conn(SPItem *item) { + g_assert( SP_IS_PATH(item) ); + + const SPCurve *curve = SP_PATH(item)->get_curve_reference(); + Geom::Affine i2dt = item->i2dt_affine(); + + if (this->active_conn == item) + { + if (curve->is_empty()) + { + // Connector is invisible because it is clipped to the boundary of + // two overlpapping shapes. + sp_knot_hide(this->endpt_handle[0]); + sp_knot_hide(this->endpt_handle[1]); + } + else + { + // Just adjust handle positions. + Geom::Point startpt = *(curve->first_point()) * i2dt; + sp_knot_set_position(this->endpt_handle[0], startpt, 0); + + Geom::Point endpt = *(curve->last_point()) * i2dt; + sp_knot_set_position(this->endpt_handle[1], endpt, 0); + } + + return; + } + + this->active_conn = item; + + // Remove existing active conn listeners + if (this->active_conn_repr) { + sp_repr_remove_listener_by_data(this->active_conn_repr, this); + Inkscape::GC::release(this->active_conn_repr); + this->active_conn_repr = NULL; + } + + // Listen in case the active conn changes + this->active_conn_repr = item->getRepr(); + if (this->active_conn_repr) { + Inkscape::GC::anchor(this->active_conn_repr); + sp_repr_add_listener(this->active_conn_repr, &shape_repr_events, this); + } + + for (int i = 0; i < 2; ++i) { + + // Create the handle if it doesn't exist + if ( this->endpt_handle[i] == NULL ) { + SPKnot *knot = sp_knot_new(this->desktop, + _("<b>Connector endpoint</b>: drag to reroute or connect to new shapes")); + + knot->setShape(SP_KNOT_SHAPE_SQUARE); + knot->setSize(7); + knot->setAnchor(SP_ANCHOR_CENTER); + knot->setFill(0xffffff00, 0xff0000ff, 0xff0000ff); + knot->setStroke(0x000000ff, 0x000000ff, 0x000000ff); + sp_knot_update_ctrl(knot); + + // We don't want to use the standard knot handler, + // since we don't want this knot to be draggable. + g_signal_handler_disconnect(G_OBJECT(knot->item), + knot->_event_handler_id); + knot->_event_handler_id = 0; + + g_signal_connect(G_OBJECT(knot->item), "event", + G_CALLBACK(cc_generic_knot_handler), knot); + + this->endpt_handle[i] = knot; + } + + // Remove any existing handlers + if (this->endpt_handler_id[i]) { + g_signal_handlers_disconnect_by_func( + G_OBJECT(this->endpt_handle[i]->item), + (void*)G_CALLBACK(endpt_handler), (gpointer) this ); + this->endpt_handler_id[i] = 0; + } + + // Setup handlers for connector endpoints, this is + // is as 'after' so that cc_generic_knot_handler is + // triggered first for any endpoint. + this->endpt_handler_id[i] = g_signal_connect_after( + G_OBJECT(this->endpt_handle[i]->item), "event", + G_CALLBACK(endpt_handler), this); + } + + if (curve->is_empty()) + { + // Connector is invisible because it is clipped to the boundary + // of two overlpapping shapes. So, it doesn't need endpoints. + return; + } + + Geom::Point startpt = *(curve->first_point()) * i2dt; + sp_knot_set_position(this->endpt_handle[0], startpt, 0); + + Geom::Point endpt = *(curve->last_point()) * i2dt; + sp_knot_set_position(this->endpt_handle[1], endpt, 0); + + sp_knot_show(this->endpt_handle[0]); + sp_knot_show(this->endpt_handle[1]); +} + +void cc_create_connection_point(ConnectorTool* cc) +{ + if (cc->active_shape && cc->state == SP_CONNECTOR_CONTEXT_IDLE) + { + if (cc->selected_handle) + { + cc_deselect_handle( cc->selected_handle ); + } + SPKnot *knot = sp_knot_new(cc->desktop, 0); + // We do not process events on this knot. + g_signal_handler_disconnect(G_OBJECT(knot->item), + knot->_event_handler_id); + knot->_event_handler_id = 0; + + cc_select_handle( knot ); + cc->selected_handle = knot; + sp_knot_show(cc->selected_handle); + cc->state = SP_CONNECTOR_CONTEXT_NEWCONNPOINT; + } +} + +static bool cc_item_is_shape(SPItem *item) +{ + if (SP_IS_PATH(item)) { + const SPCurve * curve = (SP_SHAPE(item))->_curve; + if ( curve && !(curve->is_closed()) ) { + // Open paths are connectors. + return false; + } + } + else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item)) { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/tools/connector/ignoretext", true)) { + // Don't count text as a shape we can connect connector to. + return false; + } + } + return true; +} + + +bool cc_item_is_connector(SPItem *item) +{ + if (SP_IS_PATH(item)) { + bool closed = SP_PATH(item)->get_curve_reference()->is_closed(); + if (SP_PATH(item)->connEndPair.isAutoRoutingConn() && !closed) { + // To be considered a connector, an object must be a non-closed + // path that is marked with a "inkscape:connector-type" attribute. + return true; + } + } + return false; +} + + +void cc_selection_set_avoid(bool const set_avoid) +{ + SPDesktop *desktop = inkscape_active_desktop(); + if (desktop == NULL) { + return; + } + + SPDocument *document = sp_desktop_document(desktop); + + Inkscape::Selection *selection = sp_desktop_selection(desktop); + + GSList *l = const_cast<GSList *>(selection->itemList()); + + int changes = 0; + + while (l) { + SPItem *item = SP_ITEM(l->data); + + char const *value = (set_avoid) ? "true" : NULL; + + if (cc_item_is_shape(item)) { + item->setAttribute("inkscape:connector-avoid", value, NULL); + item->avoidRef->handleSettingChange(); + changes++; + } + + l = l->next; + } + + if (changes == 0) { + desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, + _("Select <b>at least one non-connector object</b>.")); + return; + } + + char *event_desc = (set_avoid) ? + _("Make connectors avoid selected objects") : + _("Make connectors ignore selected objects"); + DocumentUndo::done(document, SP_VERB_CONTEXT_CONNECTOR, event_desc); +} + +void ConnectorTool::_selectionChanged(Inkscape::Selection *selection) { + SPItem *item = selection->singleItem(); + + if (this->active_conn == item) { + // Nothing to change. + return; + } + + if (item == NULL) { + this->cc_clear_active_conn(); + return; + } + + if (cc_item_is_connector(item)) { + this->cc_set_active_conn(item); + } +} + +static void +shape_event_attr_deleted(Inkscape::XML::Node */*repr*/, Inkscape::XML::Node *child, + Inkscape::XML::Node */*ref*/, gpointer data) +{ + g_assert(data); + ConnectorTool *cc = SP_CONNECTOR_CONTEXT(data); + + if (child == cc->active_shape_repr) { + // The active shape has been deleted. Clear active shape. + cc->cc_clear_active_shape(); + } +} + + +static void +shape_event_attr_changed(Inkscape::XML::Node *repr, gchar const *name, + gchar const */*old_value*/, gchar const */*new_value*/, + bool /*is_interactive*/, gpointer data) +{ + g_assert(data); + ConnectorTool *cc = SP_CONNECTOR_CONTEXT(data); + + // Look for changes that result in onscreen movement. + if (!strcmp(name, "d") || !strcmp(name, "x") || !strcmp(name, "y") || + !strcmp(name, "width") || !strcmp(name, "height") || + !strcmp(name, "transform")) + { + if (repr == cc->active_shape_repr) { + // Active shape has moved. Clear active shape. + cc->cc_clear_active_shape(); + } + else if (repr == cc->active_conn_repr) { + // The active conn has been moved. + // Set it again, which just sets new handle positions. + cc->cc_set_active_conn(cc->active_conn); + } + } +} + +} +} +} + + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/connector-tool.h b/src/ui/tools/connector-tool.h new file mode 100644 index 000000000..59534a173 --- /dev/null +++ b/src/ui/tools/connector-tool.h @@ -0,0 +1,158 @@ +#ifndef SEEN_CONNECTOR_CONTEXT_H +#define SEEN_CONNECTOR_CONTEXT_H + +/* + * Connector creation tool + * + * Authors: + * Michael Wybrow <mjwybrow@users.sourceforge.net> + * + * Copyright (C) 2005 Michael Wybrow + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include <stddef.h> +#include <sigc++/sigc++.h> +#include <sigc++/connection.h> +#include "ui/tools/tool-base.h" +#include <2geom/point.h> +#include "libavoid/connector.h" +#include <glibmm/i18n.h> + +#define SP_CONNECTOR_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::ConnectorTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +//#define SP_IS_CONNECTOR_CONTEXT(obj) (dynamic_cast<const ConnectorTool*>((const ToolBase*)obj) != NULL) + +struct SPKnot; +class SPCurve; + +namespace Inkscape +{ + class Selection; +} + +enum { + SP_CONNECTOR_CONTEXT_IDLE, + SP_CONNECTOR_CONTEXT_DRAGGING, + SP_CONNECTOR_CONTEXT_CLOSE, + SP_CONNECTOR_CONTEXT_STOP, + SP_CONNECTOR_CONTEXT_REROUTING, + SP_CONNECTOR_CONTEXT_NEWCONNPOINT +}; + +typedef std::map<SPKnot *, int> SPKnotList; + +namespace Inkscape { +namespace UI { +namespace Tools { + +class ConnectorTool : public ToolBase { +public: + ConnectorTool(); + virtual ~ConnectorTool(); + + Inkscape::Selection *selection; + Geom::Point p[5]; + + /** \invar npoints in {0, 2}. */ + gint npoints; + unsigned int state : 4; + + // Red curve + SPCanvasItem *red_bpath; + SPCurve *red_curve; + guint32 red_color; + + // Green curve + SPCurve *green_curve; + + // The new connector + SPItem *newconn; + Avoid::ConnRef *newConnRef; + gdouble curvature; + bool isOrthogonal; + + // The active shape + SPItem *active_shape; + Inkscape::XML::Node *active_shape_repr; + Inkscape::XML::Node *active_shape_layer_repr; + + // Same as above, but for the active connector + SPItem *active_conn; + Inkscape::XML::Node *active_conn_repr; + sigc::connection sel_changed_connection; + + // The activehandle + SPKnot *active_handle; + + // The selected handle, used in editing mode + SPKnot *selected_handle; + + SPItem *clickeditem; + SPKnot *clickedhandle; + + SPKnotList knots; + SPKnot *endpt_handle[2]; + guint endpt_handler_id[2]; + gchar *shref; + gchar *ehref; + SPCanvasItem *c0, *c1, *cl0, *cl1; + + static const std::string prefsPath; + + virtual void setup(); + virtual void finish(); + virtual void set(const Inkscape::Preferences::Entry& val); + virtual bool root_handler(GdkEvent* event); + virtual bool item_handler(SPItem* item, GdkEvent* event); + + virtual const std::string& getPrefsPath(); + + void cc_clear_active_shape(); + void cc_set_active_conn(SPItem *item); + void cc_clear_active_conn(); + +private: + void _selectionChanged(Inkscape::Selection *selection); + + gint _handleButtonPress(GdkEventButton const &bevent); + gint _handleMotionNotify(GdkEventMotion const &mevent); + gint _handleButtonRelease(GdkEventButton const &revent); + gint _handleKeyPress(guint const keyval); + + void _setInitialPoint(Geom::Point const p); + void _setSubsequentPoint(Geom::Point const p); + void _finishSegment(Geom::Point p); + void _resetColors(); + void _finish(); + void _concatColorsAndFlush(); + void _flushWhite(SPCurve *gc); + + void _activeShapeAddKnot(SPItem* item); + void _setActiveShape(SPItem *item); + bool _ptHandleTest(Geom::Point& p, gchar **href); + + void _reroutingFinish(Geom::Point *const p); +}; + +void cc_selection_set_avoid(bool const set_ignore); +void cc_create_connection_point(ConnectorTool* cc); +void cc_remove_connection_point(ConnectorTool* cc); +bool cc_item_is_connector(SPItem *item); + +} +} +} + +#endif /* !SEEN_CONNECTOR_CONTEXT_H */ + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/dropper-tool.cpp b/src/ui/tools/dropper-tool.cpp new file mode 100644 index 000000000..99d42a211 --- /dev/null +++ b/src/ui/tools/dropper-tool.cpp @@ -0,0 +1,416 @@ +/* + * Tool for picking colors from drawing + * + * Authors: + * Lauris Kaplinski <lauris@kaplinski.com> + * bulia byak <buliabyak@users.sf.net> + * Abhishek Sharma + * + * Copyright (C) 1999-2005 Authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#include <glibmm/i18n.h> +#include <gdk/gdk.h> +#include <gdk/gdkkeysyms.h> +#include <2geom/transforms.h> +#include <2geom/circle.h> + +#include "macros.h" +#include "display/canvas-bpath.h" +#include "display/canvas-arena.h" +#include "display/curve.h" +#include "display/cairo-utils.h" +#include "svg/svg-color.h" +#include "color.h" +#include "color-rgba.h" +#include "desktop-style.h" +#include "preferences.h" +#include "sp-namedview.h" +#include "sp-cursor.h" +#include "desktop.h" +#include "desktop-handles.h" +#include "selection.h" +#include "document.h" +#include "document-undo.h" + +#include "pixmaps/cursor-dropper-f.xpm" +#include "pixmaps/cursor-dropper-s.xpm" + +#include "ui/tools/dropper-tool.h" +#include "message-context.h" +#include "verbs.h" +#include "ui/tools/tool-base.h" + +using Inkscape::DocumentUndo; + +static GdkCursor *cursor_dropper_fill = NULL; +static GdkCursor *cursor_dropper_stroke = NULL; + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +namespace { + ToolBase* createDropperContext() { + return new DropperTool(); + } + + bool dropperContextRegistered = ToolFactory::instance().registerObject("/tools/dropper", createDropperContext); +} + +const std::string& DropperTool::getPrefsPath() { + return DropperTool::prefsPath; +} + +const std::string DropperTool::prefsPath = "/tools/dropper"; + +DropperTool::DropperTool() + : ToolBase(cursor_dropper_f_xpm, 7, 7) + , R(0) + , G(0) + , B(0) + , alpha(0) + , dragging(false) + , grabbed(NULL) + , area(NULL) + , centre(0, 0) +{ + cursor_dropper_fill = sp_cursor_new_from_xpm(cursor_dropper_f_xpm , 7, 7); + cursor_dropper_stroke = sp_cursor_new_from_xpm(cursor_dropper_s_xpm , 7, 7); +} + +DropperTool::~DropperTool() { +} + +void DropperTool::setup() { + ToolBase::setup(); + + /* TODO: have a look at CalligraphicTool::setup where the same is done.. generalize? */ + Geom::PathVector path; + Geom::Circle(0, 0, 1).getPath(path); + + SPCurve *c = new SPCurve(path); + + this->area = sp_canvas_bpath_new(sp_desktop_controls(this->desktop), c); + + c->unref(); + + sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(this->area), 0x00000000,(SPWindRule)0); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_item_hide(this->area); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + if (prefs->getBool("/tools/dropper/selcue")) { + this->enableSelectionCue(); + } + + if (prefs->getBool("/tools/dropper/gradientdrag")) { + this->enableGrDrag(); + } +} + +void DropperTool::finish() { + this->enableGrDrag(false); + + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed, GDK_CURRENT_TIME); + this->grabbed = NULL; + } + + if (this->area) { + sp_canvas_item_destroy(this->area); + this->area = NULL; + } + + if (cursor_dropper_fill) { +#if GTK_CHECK_VERSION(3,0,0) + g_object_unref(cursor_dropper_fill); +#else + gdk_cursor_unref (cursor_dropper_fill); +#endif + cursor_dropper_fill = NULL; + } + + if (cursor_dropper_stroke) { +#if GTK_CHECK_VERSION(3,0,0) + g_object_unref(cursor_dropper_stroke); +#else + gdk_cursor_unref (cursor_dropper_stroke); +#endif + cursor_dropper_fill = NULL; + } + + ToolBase::finish(); +} + +/** + * Returns the current dropper context color. + */ +guint32 DropperTool::get_color() { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + int pick = prefs->getInt("/tools/dropper/pick", SP_DROPPER_PICK_VISIBLE); + bool setalpha = prefs->getBool("/tools/dropper/setalpha", true); + + return SP_RGBA32_F_COMPOSE(this->R, + this->G, + this->B, + (pick == SP_DROPPER_PICK_ACTUAL && setalpha) ? this->alpha : 1.0); +} + +bool DropperTool::root_handler(GdkEvent* event) { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + int ret = FALSE; + + int pick = prefs->getInt("/tools/dropper/pick", SP_DROPPER_PICK_VISIBLE); + bool setalpha = prefs->getBool("/tools/dropper/setalpha", true); + + switch (event->type) { + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + this->centre = Geom::Point(event->button.x, event->button.y); + this->dragging = true; + ret = TRUE; + } + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK, + NULL, event->button.time); + this->grabbed = SP_CANVAS_ITEM(desktop->acetate); + + break; + case GDK_MOTION_NOTIFY: + if (event->motion.state & GDK_BUTTON2_MASK || event->motion.state & GDK_BUTTON3_MASK) { + // pass on middle and right drag + ret = FALSE; + break; + } else if (!this->space_panning) { + // otherwise, constantly calculate color no matter is any button pressed or not + + // If one time pick with stroke set the pixmap + if (prefs->getBool("/tools/dropper/onetimepick", false) && prefs->getInt("/dialogs/fillstroke/page", 0) == 1) { + //TODO Only set when not set already + GdkWindow* window = gtk_widget_get_window(GTK_WIDGET(sp_desktop_canvas(desktop))); + gdk_window_set_cursor(window, cursor_dropper_stroke); + } + + double rw = 0.0; + double R(0), G(0), B(0), A(0); + + if (this->dragging) { + // calculate average + + // radius + rw = std::min(Geom::L2(Geom::Point(event->button.x, event->button.y) - this->centre), 400.0); + + if (rw == 0) { // happens sometimes, little idea why... + break; + } + + Geom::Point const cd = desktop->w2d(this->centre); + Geom::Affine const w2dt = desktop->w2d(); + const double scale = rw * w2dt.descrim(); + Geom::Affine const sm( Geom::Scale(scale, scale) * Geom::Translate(cd) ); + sp_canvas_item_affine_absolute(this->area, sm); + sp_canvas_item_show(this->area); + + /* Get buffer */ + Geom::Rect r(this->centre, this->centre); + r.expandBy(rw); + if (!r.hasZeroArea()) { + Geom::IntRect area = r.roundOutwards(); + cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, area.width(), area.height()); + sp_canvas_arena_render_surface(SP_CANVAS_ARENA(sp_desktop_drawing(desktop)), s, area); + ink_cairo_surface_average_color_premul(s, R, G, B, A); + cairo_surface_destroy(s); + } + } else { + // pick single pixel + Geom::IntRect area = Geom::IntRect::from_xywh(floor(event->button.x), floor(event->button.y), 1, 1); + cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1, 1); + sp_canvas_arena_render_surface(SP_CANVAS_ARENA(sp_desktop_drawing(desktop)), s, area); + ink_cairo_surface_average_color_premul(s, R, G, B, A); + cairo_surface_destroy(s); + } + + if (pick == SP_DROPPER_PICK_VISIBLE) { + // compose with page color + guint32 bg = sp_desktop_namedview(desktop)->pagecolor; + R = R + (SP_RGBA32_R_F(bg)) * (1 - A); + G = G + (SP_RGBA32_G_F(bg)) * (1 - A); + B = B + (SP_RGBA32_B_F(bg)) * (1 - A); + A = 1.0; + } else { + // un-premultiply color channels + if (A > 0) { + R /= A; + G /= A; + B /= A; + } + } + + if (fabs(A) < 1e-4) { + A = 0; // suppress exponentials, CSS does not allow that + } + + // remember color + this->R = R; + this->G = G; + this->B = B; + this->alpha = A; + + // status message + double alpha_to_set = setalpha? this->alpha : 1.0; + guint32 c32 = SP_RGBA32_F_COMPOSE(R, G, B, alpha_to_set); + + gchar c[64]; + sp_svg_write_color(c, sizeof(c), c32); + + // alpha of color under cursor, to show in the statusbar + // locale-sensitive printf is OK, since this goes to the UI, not into SVG + gchar *alpha = g_strdup_printf(_(" alpha %.3g"), alpha_to_set); + // where the color is picked, to show in the statusbar + gchar *where = this->dragging ? g_strdup_printf(_(", averaged with radius %d"), (int) rw) : g_strdup_printf("%s", _(" under cursor")); + // message, to show in the statusbar + const gchar *message = this->dragging ? _("<b>Release mouse</b> to set color.") : _("<b>Click</b> to set fill, <b>Shift+click</b> to set stroke; <b>drag</b> to average color in area; with <b>Alt</b> to pick inverse color; <b>Ctrl+C</b> to copy the color under mouse to clipboard"); + + this->defaultMessageContext()->setF( + Inkscape::NORMAL_MESSAGE, + "<b>%s%s</b>%s. %s", c, + (pick == SP_DROPPER_PICK_VISIBLE) ? "" : alpha, where, message); + + g_free(where); + g_free(alpha); + + ret = TRUE; + } + break; + + case GDK_BUTTON_RELEASE: + if (event->button.button == 1 && !this->space_panning) { + sp_canvas_item_hide(this->area); + this->dragging = false; + + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed, event->button.time); + this->grabbed = NULL; + } + + double alpha_to_set = setalpha? this->alpha : 1.0; + + bool fill = !(event->button.state & GDK_SHIFT_MASK); // Stroke if Shift key held + + if (prefs->getBool("/tools/dropper/onetimepick", false)) { + // "One time" pick from Fill/Stroke dialog stroke page, always apply fill or stroke (ignore <Shift> key) + fill = (prefs->getInt("/dialogs/fillstroke/page", 0) == 0) ? true : false; + } + + // do the actual color setting + sp_desktop_set_color(desktop, + (event->button.state & GDK_MOD1_MASK)? + ColorRGBA(1 - this->R, 1 - this->G, 1 - this->B, alpha_to_set) : ColorRGBA(this->R, this->G, this->B, alpha_to_set), + false, fill); + + // REJON: set aux. toolbar input to hex color! + + if (event->button.state & GDK_SHIFT_MASK) { + GdkWindow* window = gtk_widget_get_window(GTK_WIDGET(sp_desktop_canvas(desktop))); + gdk_window_set_cursor(window, cursor_dropper_stroke); + } + + if (!(sp_desktop_selection(desktop)->isEmpty())) { + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_DROPPER, + _("Set picked color")); + } + + if (prefs->getBool("/tools/dropper/onetimepick", false)) { + prefs->setBool("/tools/dropper/onetimepick", false); + sp_toggle_dropper(desktop); + + // sp_toggle_dropper will delete ourselves. + // Thus, make sure we return immediately. + return true; + } + + ret = TRUE; + } + break; + + case GDK_KEY_PRESS: + switch (get_group0_keyval(&event->key)) { + case GDK_KEY_Up: + case GDK_KEY_Down: + case GDK_KEY_KP_Up: + case GDK_KEY_KP_Down: + // prevent the zoom field from activation + if (!MOD__CTRL_ONLY(event)) { + ret = TRUE; + } + break; + + case GDK_KEY_Escape: + sp_desktop_selection(desktop)->clear(); + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + if (!desktop->isWaitingCursor() && !prefs->getBool("/tools/dropper/onetimepick", false)) { + GdkWindow* window = gtk_widget_get_window(GTK_WIDGET(sp_desktop_canvas(desktop))); + gdk_window_set_cursor(window, cursor_dropper_stroke); + } + + break; + default: + break; + } + break; + + case GDK_KEY_RELEASE: + switch (get_group0_keyval(&event->key)) { + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + if (!desktop->isWaitingCursor() && !prefs->getBool("/tools/dropper/onetimepick", false)) { + GdkWindow* window = gtk_widget_get_window(GTK_WIDGET(sp_desktop_canvas(desktop))); + gdk_window_set_cursor(window, cursor_dropper_fill); + } + break; + + default: + break; + } + break; + + default: + break; + } + + if (!ret) { + ret = ToolBase::root_handler(event); + } + + return ret; +} + +} +} +} + + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/tools/dropper-tool.h b/src/ui/tools/dropper-tool.h new file mode 100644 index 000000000..dd6f25bb6 --- /dev/null +++ b/src/ui/tools/dropper-tool.h @@ -0,0 +1,73 @@ +#ifndef __SP_DROPPER_CONTEXT_H__ +#define __SP_DROPPER_CONTEXT_H__ + +/* + * Tool for picking colors from drawing + * + * Authors: + * Lauris Kaplinski <lauris@kaplinski.com> + * + * Copyright (C) 1999-2002 Authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "ui/tools/tool-base.h" + +#define SP_DROPPER_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::DropperTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_DROPPER_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::DropperTool*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +enum { + SP_DROPPER_PICK_VISIBLE, + SP_DROPPER_PICK_ACTUAL +}; + +namespace Inkscape { +namespace UI { +namespace Tools { + +class DropperTool : public ToolBase { +public: + DropperTool(); + virtual ~DropperTool(); + + static const std::string prefsPath; + + virtual const std::string& getPrefsPath(); + + guint32 get_color(); + +protected: + virtual void setup(); + virtual void finish(); + virtual bool root_handler(GdkEvent* event); + +private: + double R; + double G; + double B; + double alpha; + + bool dragging; + + SPCanvasItem* grabbed; + SPCanvasItem* area; + Geom::Point centre; +}; + +} +} +} + +#endif + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/dynamic-base.cpp b/src/ui/tools/dynamic-base.cpp new file mode 100644 index 000000000..21b4b0532 --- /dev/null +++ b/src/ui/tools/dynamic-base.cpp @@ -0,0 +1,163 @@ + +#include "ui/tools/dynamic-base.h" + +#include <gtk/gtk.h> + +#include "config.h" + +#include "message-context.h" +#include "streq.h" +#include "preferences.h" +#include "display/sp-canvas-item.h" +#include "desktop.h" + +#define MIN_PRESSURE 0.0 +#define MAX_PRESSURE 1.0 +#define DEFAULT_PRESSURE 1.0 + +#define DRAG_MIN 0.0 +#define DRAG_DEFAULT 1.0 +#define DRAG_MAX 1.0 + +namespace Inkscape { +namespace UI { +namespace Tools { + +DynamicBase::DynamicBase(gchar const *const *cursor_shape, gint hot_x, gint hot_y) + : ToolBase(cursor_shape, hot_x, hot_y) + , accumulated(NULL) + , segments(NULL) + , currentshape(NULL) + , currentcurve(NULL) + , cal1(NULL) + , cal2(NULL) + , point1() + , point2() + , npoints(0) + , repr(NULL) + , cur(0, 0) + , vel(0, 0) + , vel_max(0) + , acc(0, 0) + , ang(0, 0) + , last(0, 0) + , del(0, 0) + , pressure(DEFAULT_PRESSURE) + , xtilt(0) + , ytilt(0) + , dragging(false) + , usepressure(false) + , usetilt(false) + , mass(0.3) + , drag(DRAG_DEFAULT) + , angle(30.0) + , width(0.2) + , vel_thin(0.1) + , flatness(0.9) + , tremor(0) + , cap_rounding(0) + , is_drawing(false) + , abs_width(false) +{ +} + +DynamicBase::~DynamicBase() { + if (this->accumulated) { + this->accumulated = this->accumulated->unref(); + this->accumulated = 0; + } + + while (this->segments) { + sp_canvas_item_destroy(SP_CANVAS_ITEM(this->segments->data)); + this->segments = g_slist_remove(this->segments, this->segments->data); + } + + if (this->currentcurve) { + this->currentcurve = this->currentcurve->unref(); + this->currentcurve = 0; + } + + if (this->cal1) { + this->cal1 = this->cal1->unref(); + this->cal1 = 0; + } + + if (this->cal2) { + this->cal2 = this->cal2->unref(); + this->cal2 = 0; + } + + if (this->currentshape) { + sp_canvas_item_destroy(this->currentshape); + this->currentshape = 0; + } +} + +void DynamicBase::set(const Inkscape::Preferences::Entry& value) { + Glib::ustring path = value.getEntryName(); + + // ignore preset modifications + static Glib::ustring const presets_path = this->pref_observer->observed_path + "/preset"; + Glib::ustring const &full_path = value.getPath(); + + if (full_path.compare(0, presets_path.size(), presets_path) == 0) { + return; + } + + if (path == "mass") { + this->mass = 0.01 * CLAMP(value.getInt(10), 0, 100); + } else if (path == "wiggle") { + this->drag = CLAMP((1 - 0.01 * value.getInt()), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle + } else if (path == "angle") { + this->angle = CLAMP(value.getDouble(), -90, 90); + } else if (path == "width") { + this->width = 0.01 * CLAMP(value.getInt(10), 1, 100); + } else if (path == "thinning") { + this->vel_thin = 0.01 * CLAMP(value.getInt(10), -100, 100); + } else if (path == "tremor") { + this->tremor = 0.01 * CLAMP(value.getInt(), 0, 100); + } else if (path == "flatness") { + this->flatness = 0.01 * CLAMP(value.getInt(), 0, 100); + } else if (path == "usepressure") { + this->usepressure = value.getBool(); + } else if (path == "usetilt") { + this->usetilt = value.getBool(); + } else if (path == "abs_width") { + this->abs_width = value.getBool(); + } else if (path == "cap_rounding") { + this->cap_rounding = value.getDouble(); + } +} + +/* Get normalized point */ +Geom::Point DynamicBase::getNormalizedPoint(Geom::Point v) const { + Geom::Rect drect = this->desktop->get_display_area(); + + double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] ); + + return Geom::Point(( v[Geom::X] - drect.min()[Geom::X] ) / max, ( v[Geom::Y] - drect.min()[Geom::Y] ) / max); +} + +/* Get view point */ +Geom::Point DynamicBase::getViewPoint(Geom::Point n) const { + Geom::Rect drect = this->desktop->get_display_area(); + + double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] ); + + return Geom::Point(n[Geom::X] * max + drect.min()[Geom::X], n[Geom::Y] * max + drect.min()[Geom::Y]); +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/dynamic-base.h b/src/ui/tools/dynamic-base.h new file mode 100644 index 000000000..76fcd0f02 --- /dev/null +++ b/src/ui/tools/dynamic-base.h @@ -0,0 +1,123 @@ +#ifndef COMMON_CONTEXT_H_SEEN +#define COMMON_CONTEXT_H_SEEN + +/* + * Common drawing mode + * + * Authors: + * Mitsuru Oka <oka326@parkcity.ne.jp> + * Lauris Kaplinski <lauris@kaplinski.com> + * + * The original dynadraw code: + * Paul Haeberli <paul@sgi.com> + * + * Copyright (C) 1998 The Free Software Foundation + * Copyright (C) 1999-2002 authors + * Copyright (C) 2001-2002 Ximian, Inc. + * Copyright (C) 2008 Jon A. Cruz + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "ui/tools/tool-base.h" +#include "display/curve.h" +#include <2geom/point.h> + +#define SAMPLING_SIZE 8 /* fixme: ?? */ + +namespace Inkscape { +namespace UI { +namespace Tools { + +class DynamicBase : public ToolBase { +public: + DynamicBase(gchar const *const *cursor_shape, gint hot_x, gint hot_y); + virtual ~DynamicBase(); + + virtual void set(const Inkscape::Preferences::Entry& val); + +protected: + /** accumulated shape which ultimately goes in svg:path */ + SPCurve *accumulated; + + /** canvas items for "comitted" segments */ + GSList *segments; + + /** canvas item for red "leading" segment */ + SPCanvasItem *currentshape; + /** shape of red "leading" segment */ + SPCurve *currentcurve; + + /** left edge of the stroke; combined to get accumulated */ + SPCurve *cal1; + + /** right edge of the stroke; combined to get accumulated */ + SPCurve *cal2; + + /** left edge points for this segment */ + Geom::Point point1[SAMPLING_SIZE]; + + /** right edge points for this segment */ + Geom::Point point2[SAMPLING_SIZE]; + + /** number of edge points for this segment */ + gint npoints; + + /* repr */ + Inkscape::XML::Node *repr; + + /* common */ + Geom::Point cur; + Geom::Point vel; + double vel_max; + Geom::Point acc; + Geom::Point ang; + Geom::Point last; + Geom::Point del; + + /* extended input data */ + gdouble pressure; + gdouble xtilt; + gdouble ytilt; + + /* attributes */ + bool dragging; /* mouse state: mouse is dragging */ + bool usepressure; + bool usetilt; + double mass, drag; + double angle; + double width; + + double vel_thin; + double flatness; + double tremor; + double cap_rounding; + + //Inkscape::MessageContext *_message_context; + + bool is_drawing; + + /** uses absolute width independent of zoom */ + bool abs_width; + + Geom::Point getViewPoint(Geom::Point n) const; + Geom::Point getNormalizedPoint(Geom::Point v) const; +}; + +} +} +} + +#endif // COMMON_CONTEXT_H_SEEN + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : + diff --git a/src/ui/tools/eraser-tool.cpp b/src/ui/tools/eraser-tool.cpp new file mode 100644 index 000000000..011d28663 --- /dev/null +++ b/src/ui/tools/eraser-tool.cpp @@ -0,0 +1,1018 @@ +/* + * Eraser drawing mode + * + * Authors: + * Mitsuru Oka <oka326@parkcity.ne.jp> + * Lauris Kaplinski <lauris@kaplinski.com> + * bulia byak <buliabyak@users.sf.net> + * MenTaLguY <mental@rydia.net> + * Jon A. Cruz <jon@joncruz.org> + * Abhishek Sharma + * + * The original dynadraw code: + * Paul Haeberli <paul@sgi.com> + * + * Copyright (C) 1998 The Free Software Foundation + * Copyright (C) 1999-2005 authors + * Copyright (C) 2001-2002 Ximian, Inc. + * Copyright (C) 2005-2007 bulia byak + * Copyright (C) 2006 MenTaLguY + * Copyright (C) 2008 Jon A. Cruz + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#define noERASER_VERBOSE + +#include "config.h" + +#include <gtk/gtk.h> +#include <gdk/gdkkeysyms.h> +#include <glibmm/i18n.h> +#include <string> +#include <cstring> +#include <numeric> + +#include "svg/svg.h" +#include "display/sp-canvas.h" +#include "display/canvas-bpath.h" +#include <2geom/bezier-utils.h> + +#include <glib.h> +#include "macros.h" +#include "document.h" +#include "selection.h" +#include "desktop.h" +#include "desktop-events.h" +#include "desktop-handles.h" +#include "desktop-style.h" +#include "message-context.h" +#include "preferences.h" +#include "pixmaps/cursor-eraser.xpm" +#include "xml/repr.h" +#include "context-fns.h" +#include "sp-item.h" +#include "color.h" +#include "rubberband.h" +#include "splivarot.h" +#include "sp-item-group.h" +#include "sp-shape.h" +#include "sp-path.h" +#include "sp-text.h" +#include "display/canvas-bpath.h" +#include "display/canvas-arena.h" +#include "livarot/Shape.h" +#include "document-undo.h" +#include "verbs.h" +#include <2geom/math-utils.h> +#include <2geom/pathvector.h> + +#include "ui/tools/eraser-tool.h" + +using Inkscape::DocumentUndo; + +#define ERC_RED_RGBA 0xff0000ff + +#define TOLERANCE_ERASER 0.1 + +#define ERASER_EPSILON 0.5e-6 +#define ERASER_EPSILON_START 0.5e-2 +#define ERASER_VEL_START 1e-5 + +#define DRAG_MIN 0.0 +#define DRAG_DEFAULT 1.0 +#define DRAG_MAX 1.0 + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +namespace { + ToolBase* createEraserContext() { + return new EraserTool(); + } + + bool eraserContextRegistered = ToolFactory::instance().registerObject("/tools/eraser", createEraserContext); +} + +const std::string& EraserTool::getPrefsPath() { + return EraserTool::prefsPath; +} + +const std::string EraserTool::prefsPath = "/tools/eraser"; + +EraserTool::EraserTool() + : DynamicBase(cursor_eraser_xpm, 4, 4) +{ +} + +EraserTool::~EraserTool() { +} + +void EraserTool::setup() { + DynamicBase::setup(); + + this->accumulated = new SPCurve(); + this->currentcurve = new SPCurve(); + + this->cal1 = new SPCurve(); + this->cal2 = new SPCurve(); + + this->currentshape = sp_canvas_item_new(sp_desktop_sketch(desktop), SP_TYPE_CANVAS_BPATH, NULL); + + sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(this->currentshape), ERC_RED_RGBA, SP_WIND_RULE_EVENODD); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + + /* fixme: Cannot we cascade it to root more clearly? */ + g_signal_connect(G_OBJECT(this->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), desktop); + +/* +static ProfileFloatElement f_profile[PROFILE_FLOAT_SIZE] = { + {"mass",0.02, 0.0, 1.0}, + {"wiggle",0.0, 0.0, 1.0}, + {"angle",30.0, -90.0, 90.0}, + {"thinning",0.1, -1.0, 1.0}, + {"tremor",0.0, 0.0, 1.0}, + {"flatness",0.9, 0.0, 1.0}, + {"cap_rounding",0.0, 0.0, 5.0} +}; +*/ + + sp_event_context_read(this, "mass"); + sp_event_context_read(this, "wiggle"); + sp_event_context_read(this, "angle"); + sp_event_context_read(this, "width"); + sp_event_context_read(this, "thinning"); + sp_event_context_read(this, "tremor"); + sp_event_context_read(this, "flatness"); + sp_event_context_read(this, "tracebackground"); + sp_event_context_read(this, "usepressure"); + sp_event_context_read(this, "usetilt"); + sp_event_context_read(this, "abs_width"); + sp_event_context_read(this, "cap_rounding"); + + this->is_drawing = false; + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/tools/eraser/selcue", 0) != 0) { + this->enableSelectionCue(); + } + + // TODO temp force: + this->enableSelectionCue(); +} + +static double +flerp(double f0, double f1, double p) +{ + return f0 + ( f1 - f0 ) * p; +} + +void EraserTool::reset(Geom::Point p) { + this->last = this->cur = getNormalizedPoint(p); + this->vel = Geom::Point(0,0); + this->vel_max = 0; + this->acc = Geom::Point(0,0); + this->ang = Geom::Point(0,0); + this->del = Geom::Point(0,0); +} + +void EraserTool::extinput(GdkEvent *event) { + if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &this->pressure)) + this->pressure = CLAMP (this->pressure, ERC_MIN_PRESSURE, ERC_MAX_PRESSURE); + else + this->pressure = ERC_DEFAULT_PRESSURE; + + if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &this->xtilt)) + this->xtilt = CLAMP (this->xtilt, ERC_MIN_TILT, ERC_MAX_TILT); + else + this->xtilt = ERC_DEFAULT_TILT; + + if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &this->ytilt)) + this->ytilt = CLAMP (this->ytilt, ERC_MIN_TILT, ERC_MAX_TILT); + else + this->ytilt = ERC_DEFAULT_TILT; +} + + +bool EraserTool::apply(Geom::Point p) { + Geom::Point n = getNormalizedPoint(p); + + /* Calculate mass and drag */ + double const mass = flerp(1.0, 160.0, this->mass); + double const drag = flerp(0.0, 0.5, this->drag * this->drag); + + /* Calculate force and acceleration */ + Geom::Point force = n - this->cur; + + // If force is below the absolute threshold ERASER_EPSILON, + // or we haven't yet reached ERASER_VEL_START (i.e. at the beginning of stroke) + // _and_ the force is below the (higher) ERASER_EPSILON_START threshold, + // discard this move. + // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen, + // especially bothersome at the start of the stroke where we don't yet have the inertia to + // smooth them out. + if ( Geom::L2(force) < ERASER_EPSILON || (this->vel_max < ERASER_VEL_START && Geom::L2(force) < ERASER_EPSILON_START)) { + return FALSE; + } + + this->acc = force / mass; + + /* Calculate new velocity */ + this->vel += this->acc; + + if (Geom::L2(this->vel) > this->vel_max) + this->vel_max = Geom::L2(this->vel); + + /* Calculate angle of drawing tool */ + + double a1; + if (this->usetilt) { + // 1a. calculate nib angle from input device tilt: + gdouble length = std::sqrt(this->xtilt*this->xtilt + this->ytilt*this->ytilt);; + + if (length > 0) { + Geom::Point ang1 = Geom::Point(this->ytilt/length, this->xtilt/length); + a1 = atan2(ang1); + } + else + a1 = 0.0; + } + else { + // 1b. fixed dc->angle (absolutely flat nib): + double const radians = ( (this->angle - 90) / 180.0 ) * M_PI; + Geom::Point ang1 = Geom::Point(-sin(radians), cos(radians)); + a1 = atan2(ang1); + } + + // 2. perpendicular to dc->vel (absolutely non-flat nib): + gdouble const mag_vel = Geom::L2(this->vel); + if ( mag_vel < ERASER_EPSILON ) { + return FALSE; + } + Geom::Point ang2 = Geom::rot90(this->vel) / mag_vel; + + // 3. Average them using flatness parameter: + // calculate angles + double a2 = atan2(ang2); + // flip a2 to force it to be in the same half-circle as a1 + bool flipped = false; + if (fabs (a2-a1) > 0.5*M_PI) { + a2 += M_PI; + flipped = true; + } + // normalize a2 + if (a2 > M_PI) + a2 -= 2*M_PI; + if (a2 < -M_PI) + a2 += 2*M_PI; + // find the flatness-weighted bisector angle, unflip if a2 was flipped + // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this? + double new_ang = a1 + (1 - this->flatness) * (a2 - a1) - (flipped? M_PI : 0); + + // Try to detect a sudden flip when the new angle differs too much from the previous for the + // current velocity; in that case discard this move + double angle_delta = Geom::L2(Geom::Point (cos (new_ang), sin (new_ang)) - this->ang); + if ( angle_delta / Geom::L2(this->vel) > 4000 ) { + return FALSE; + } + + // convert to point + this->ang = Geom::Point (cos (new_ang), sin (new_ang)); + +// g_print ("force %g acc %g vel_max %g vel %g a1 %g a2 %g new_ang %g\n", Geom::L2(force), Geom::L2(dc->acc), dc->vel_max, Geom::L2(dc->vel), a1, a2, new_ang); + + /* Apply drag */ + this->vel *= 1.0 - drag; + + /* Update position */ + this->last = this->cur; + this->cur += this->vel; + + return TRUE; +} + +void EraserTool::brush() { + g_assert( this->npoints >= 0 && this->npoints < SAMPLING_SIZE ); + + // How much velocity thins strokestyle + double vel_thin = flerp (0, 160, this->vel_thin); + + // Influence of pressure on thickness + double pressure_thick = (this->usepressure ? this->pressure : 1.0); + + // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass + // drag) + Geom::Point brush = getViewPoint(this->cur); + //Geom::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush); + + double trace_thick = 1; + + double width = (pressure_thick * trace_thick - vel_thin * Geom::L2(this->vel)) * this->width; + + double tremble_left = 0, tremble_right = 0; + if (this->tremor > 0) { + // obtain two normally distributed random variables, using polar Box-Muller transform + double x1, x2, w, y1, y2; + do { + x1 = 2.0 * g_random_double_range(0,1) - 1.0; + x2 = 2.0 * g_random_double_range(0,1) - 1.0; + w = x1 * x1 + x2 * x2; + } while ( w >= 1.0 ); + w = sqrt( (-2.0 * log( w ) ) / w ); + y1 = x1 * w; + y2 = x2 * w; + + // deflect both left and right edges randomly and independently, so that: + // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve; + // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths; + // (3) deflection somewhat depends on speed, to prevent fast strokes looking + // comparatively smooth and slow ones excessively jittery + tremble_left = (y1)*this->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(this->vel)); + tremble_right = (y2)*this->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(this->vel)); + } + + if ( width < 0.02 * this->width ) { + width = 0.02 * this->width; + } + + double dezoomify_factor = 0.05 * 1000; + if (!this->abs_width) { + dezoomify_factor /= SP_EVENT_CONTEXT(this)->desktop->current_zoom(); + } + + Geom::Point del_left = dezoomify_factor * (width + tremble_left) * this->ang; + Geom::Point del_right = dezoomify_factor * (width + tremble_right) * this->ang; + + this->point1[this->npoints] = brush + del_left; + this->point2[this->npoints] = brush - del_right; + + this->del = 0.5*(del_left + del_right); + + this->npoints++; +} + +static void +sp_erc_update_toolbox (SPDesktop *desktop, const gchar *id, double value) +{ + desktop->setToolboxAdjustmentValue (id, value); +} + +void EraserTool::cancel() { + SPDesktop *desktop = SP_EVENT_CONTEXT(this)->desktop; + this->dragging = FALSE; + this->is_drawing = false; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0); + /* Remove all temporary line segments */ + while (this->segments) { + sp_canvas_item_destroy(SP_CANVAS_ITEM(this->segments->data)); + this->segments = g_slist_remove(this->segments, this->segments->data); + } + /* reset accumulated curve */ + this->accumulated->reset(); + this->clear_current(); + if (this->repr) { + this->repr = NULL; + } +} + +bool EraserTool::root_handler(GdkEvent* event) { + gint ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + if (Inkscape::have_viable_layer(desktop, this->message_context) == false) { + return TRUE; + } + + Geom::Point const button_w(event->button.x, event->button.y); + Geom::Point const button_dt(desktop->w2d(button_w)); + + this->reset(button_dt); + this->extinput(event); + this->apply(button_dt); + + this->accumulated->reset(); + + if (this->repr) { + this->repr = NULL; + } + + Inkscape::Rubberband::get(desktop)->start(desktop, button_dt); + Inkscape::Rubberband::get(desktop)->setMode(RUBBERBAND_MODE_TOUCHPATH); + + /* initialize first point */ + this->npoints = 0; + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + ( GDK_KEY_PRESS_MASK | + GDK_BUTTON_RELEASE_MASK | + GDK_POINTER_MOTION_MASK | + GDK_BUTTON_PRESS_MASK ), + NULL, + event->button.time); + + ret = TRUE; + + desktop->canvas->forceFullRedrawAfterInterruptions(3); + this->is_drawing = true; + } + break; + + case GDK_MOTION_NOTIFY: { + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w) + ); + this->extinput(event); + + this->message_context->clear(); + + if ( this->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !this->space_panning) { + this->dragging = TRUE; + + this->message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> an eraser stroke")); + + if (!this->apply(motion_dt)) { + ret = TRUE; + break; + } + + if ( this->cur != this->last ) { + this->brush(); + g_assert( this->npoints > 0 ); + this->fit_and_split(false); + } + + ret = TRUE; + } + + Inkscape::Rubberband::get(desktop)->move(motion_dt); + } + break; + + case GDK_BUTTON_RELEASE: { + Geom::Point const motion_w(event->button.x, event->button.y); + Geom::Point const motion_dt(desktop->w2d(motion_w)); + + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time); + desktop->canvas->endForcedFullRedraws(); + this->is_drawing = false; + + if (this->dragging && event->button.button == 1 && !this->space_panning) { + this->dragging = FALSE; + + this->apply(motion_dt); + + /* Remove all temporary line segments */ + while (this->segments) { + sp_canvas_item_destroy(SP_CANVAS_ITEM(this->segments->data)); + this->segments = g_slist_remove(this->segments, this->segments->data); + } + + /* Create object */ + this->fit_and_split(true); + this->accumulate(); + this->set_to_accumulated(); // performs document_done + + /* reset accumulated curve */ + this->accumulated->reset(); + + this->clear_current(); + if (this->repr) { + this->repr = NULL; + } + + this->message_context->clear(); + ret = TRUE; + } + + if (Inkscape::Rubberband::get(desktop)->is_started()) { + Inkscape::Rubberband::get(desktop)->stop(); + } + + break; + } + + case GDK_KEY_PRESS: + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Up: + case GDK_KEY_KP_Up: + if (!MOD__CTRL_ONLY(event)) { + this->angle += 5.0; + + if (this->angle > 90.0) { + this->angle = 90.0; + } + + sp_erc_update_toolbox (desktop, "eraser-angle", this->angle); + ret = TRUE; + } + break; + + case GDK_KEY_Down: + case GDK_KEY_KP_Down: + if (!MOD__CTRL_ONLY(event)) { + this->angle -= 5.0; + + if (this->angle < -90.0) { + this->angle = -90.0; + } + + sp_erc_update_toolbox (desktop, "eraser-angle", this->angle); + ret = TRUE; + } + break; + + case GDK_KEY_Right: + case GDK_KEY_KP_Right: + if (!MOD__CTRL_ONLY(event)) { + this->width += 0.01; + + if (this->width > 1.0) { + this->width = 1.0; + } + + sp_erc_update_toolbox (desktop, "altx-eraser", this->width * 100); // the same spinbutton is for alt+x + ret = TRUE; + } + break; + + case GDK_KEY_Left: + case GDK_KEY_KP_Left: + if (!MOD__CTRL_ONLY(event)) { + this->width -= 0.01; + + if (this->width < 0.01) { + this->width = 0.01; + } + + sp_erc_update_toolbox (desktop, "altx-eraser", this->width * 100); + ret = TRUE; + } + break; + + case GDK_KEY_Home: + case GDK_KEY_KP_Home: + this->width = 0.01; + sp_erc_update_toolbox (desktop, "altx-eraser", this->width * 100); + ret = TRUE; + break; + + case GDK_KEY_End: + case GDK_KEY_KP_End: + this->width = 1.0; + sp_erc_update_toolbox (desktop, "altx-eraser", this->width * 100); + ret = TRUE; + break; + + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo ("altx-eraser"); + ret = TRUE; + } + break; + + case GDK_KEY_Escape: + Inkscape::Rubberband::get(desktop)->stop(); + + if (this->is_drawing) { + // if drawing, cancel, otherwise pass it up for deselecting + this->cancel(); + ret = TRUE; + } + break; + + case GDK_KEY_z: + case GDK_KEY_Z: + if (MOD__CTRL_ONLY(event) && this->is_drawing) { + // if drawing, cancel, otherwise pass it up for undo + this->cancel(); + ret = TRUE; + } + break; + + default: + break; + } + break; + + case GDK_KEY_RELEASE: + switch (get_group0_keyval(&event->key)) { + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + this->message_context->clear(); + break; + + default: + break; + } + break; + + default: + break; + } + + if (!ret) { + ret = DynamicBase::root_handler(event); + } + + return ret; +} + +void EraserTool::clear_current() { + // reset bpath + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->currentshape), NULL); + + // reset curve + this->currentcurve->reset(); + this->cal1->reset(); + this->cal2->reset(); + + // reset points + this->npoints = 0; +} + +void EraserTool::set_to_accumulated() { + bool workDone = false; + + if (!this->accumulated->is_empty()) { + if (!this->repr) { + /* Create object */ + Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); + Inkscape::XML::Node *repr = xml_doc->createElement("svg:path"); + + /* Set style */ + sp_desktop_apply_style_tool (desktop, repr, "/tools/eraser", false); + + this->repr = repr; + + SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(this->repr)); + Inkscape::GC::release(this->repr); + + item->transform = SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); + item->updateRepr(); + } + + Geom::PathVector pathv = this->accumulated->get_pathvector() * desktop->dt2doc(); + gchar *str = sp_svg_write_path(pathv); + g_assert( str != NULL ); + this->repr->setAttribute("d", str); + g_free(str); + + if ( this->repr ) { + bool wasSelection = false; + Inkscape::Selection *selection = sp_desktop_selection(desktop); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + gint eraserMode = prefs->getBool("/tools/eraser/mode") ? 1 : 0; + Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); + + SPItem* acid = SP_ITEM(desktop->doc()->getObjectByRepr(this->repr)); + Geom::OptRect eraserBbox = acid->visualBounds(); + Geom::Rect bounds = (*eraserBbox) * desktop->doc2dt(); + std::vector<SPItem*> remainingItems; + GSList* toWorkOn = 0; + + if (selection->isEmpty()) { + if ( eraserMode ) { + toWorkOn = sp_desktop_document(desktop)->getItemsPartiallyInBox(desktop->dkey, bounds); + } else { + Inkscape::Rubberband *r = Inkscape::Rubberband::get(desktop); + toWorkOn = sp_desktop_document(desktop)->getItemsAtPoints(desktop->dkey, r->getPoints()); + } + + toWorkOn = g_slist_remove( toWorkOn, acid ); + } else { + toWorkOn = g_slist_copy(const_cast<GSList*>(selection->itemList())); + wasSelection = true; + } + + if ( g_slist_length(toWorkOn) > 0 ) { + if ( eraserMode ) { + for (GSList *i = toWorkOn ; i ; i = i->next ) { + SPItem *item = SP_ITEM(i->data); + + if ( eraserMode ) { + Geom::OptRect bbox = item->visualBounds(); + + if (bbox && bbox->intersects(*eraserBbox)) { + Inkscape::XML::Node* dup = this->repr->duplicate(xml_doc); + this->repr->parent()->appendChild(dup); + Inkscape::GC::release(dup); // parent takes over + + selection->set(item); + selection->add(dup); + sp_selected_path_diff_skip_undo(selection, desktop); + workDone = true; // TODO set this only if something was cut. + + if ( !selection->isEmpty() ) { + // If the item was not completely erased, track the new remainder. + GSList *nowSel = g_slist_copy(const_cast<GSList *>(selection->itemList())); + + for (GSList const *i2 = nowSel ; i2 ; i2 = i2->next ) { + remainingItems.push_back(SP_ITEM(i2->data)); + } + + g_slist_free(nowSel); + } + } else { + remainingItems.push_back(item); + } + } + } + } else { + for (GSList *i = toWorkOn ; i ; i = i->next ) { + sp_object_ref( SP_ITEM(i->data), 0 ); + } + + for (GSList *i = toWorkOn ; i ; i = i->next ) { + SPItem *item = SP_ITEM(i->data); + item->deleteObject(true); + sp_object_unref(item); + workDone = true; + } + } + + g_slist_free(toWorkOn); + + if ( !eraserMode ) { + //sp_selection_delete(desktop); + remainingItems.clear(); + } + + selection->clear(); + + if ( wasSelection ) { + if ( !remainingItems.empty() ) { + selection->add(remainingItems.begin(), remainingItems.end()); + } + } + } + + // Remove the eraser stroke itself: + sp_repr_unparent( this->repr ); + this->repr = 0; + } + } else { + if (this->repr) { + sp_repr_unparent(this->repr); + this->repr = 0; + } + } + + + if ( workDone ) { + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_ERASER, _("Draw eraser stroke")); + } else { + DocumentUndo::cancel(sp_desktop_document(desktop)); + } +} + +static void +add_cap(SPCurve *curve, + Geom::Point const &pre, Geom::Point const &from, + Geom::Point const &to, Geom::Point const &post, + double rounding) +{ + Geom::Point vel = rounding * Geom::rot90( to - from ) / sqrt(2.0); + double mag = Geom::L2(vel); + + Geom::Point v_in = from - pre; + double mag_in = Geom::L2(v_in); + + if ( mag_in > ERASER_EPSILON ) { + v_in = mag * v_in / mag_in; + } else { + v_in = Geom::Point(0, 0); + } + + Geom::Point v_out = to - post; + double mag_out = Geom::L2(v_out); + + if ( mag_out > ERASER_EPSILON ) { + v_out = mag * v_out / mag_out; + } else { + v_out = Geom::Point(0, 0); + } + + if ( Geom::L2(v_in) > ERASER_EPSILON || Geom::L2(v_out) > ERASER_EPSILON ) { + curve->curveto(from + v_in, to + v_out, to); + } +} + +void EraserTool::accumulate() { + if ( !this->cal1->is_empty() && !this->cal2->is_empty() ) { + this->accumulated->reset(); /* Is this required ?? */ + SPCurve *rev_cal2 = this->cal2->create_reverse(); + + g_assert(this->cal1->get_segment_count() > 0); + g_assert(rev_cal2->get_segment_count() > 0); + g_assert( ! this->cal1->first_path()->closed() ); + g_assert( ! rev_cal2->first_path()->closed() ); + + Geom::CubicBezier const * dc_cal1_firstseg = dynamic_cast<Geom::CubicBezier const *>( this->cal1->first_segment() ); + Geom::CubicBezier const * rev_cal2_firstseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->first_segment() ); + Geom::CubicBezier const * dc_cal1_lastseg = dynamic_cast<Geom::CubicBezier const *>( this->cal1->last_segment() ); + Geom::CubicBezier const * rev_cal2_lastseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->last_segment() ); + + g_assert( dc_cal1_firstseg ); + g_assert( rev_cal2_firstseg ); + g_assert( dc_cal1_lastseg ); + g_assert( rev_cal2_lastseg ); + + this->accumulated->append(this->cal1, FALSE); + + add_cap(this->accumulated, (*dc_cal1_lastseg)[2], (*dc_cal1_lastseg)[3], (*rev_cal2_firstseg)[0], (*rev_cal2_firstseg)[1], this->cap_rounding); + + this->accumulated->append(rev_cal2, TRUE); + + add_cap(this->accumulated, (*rev_cal2_lastseg)[2], (*rev_cal2_lastseg)[3], (*dc_cal1_firstseg)[0], (*dc_cal1_firstseg)[1], this->cap_rounding); + + this->accumulated->closepath(); + + rev_cal2->unref(); + + this->cal1->reset(); + this->cal2->reset(); + } +} + +static double square(double const x) +{ + return x * x; +} + +void EraserTool::fit_and_split(bool release) { + double const tolerance_sq = square( desktop->w2d().descrim() * TOLERANCE_ERASER ); + +#ifdef ERASER_VERBOSE + g_print("[F&S:R=%c]", release?'T':'F'); +#endif + + if (!( this->npoints > 0 && this->npoints < SAMPLING_SIZE )) + return; // just clicked + + if ( this->npoints == SAMPLING_SIZE - 1 || release ) { +#define BEZIER_SIZE 4 +#define BEZIER_MAX_BEZIERS 8 +#define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS ) + +#ifdef ERASER_VERBOSE + g_print("[F&S:#] this->npoints:%d, release:%s\n", + dc->npoints, release ? "TRUE" : "FALSE"); +#endif + + /* Current eraser */ + if ( this->cal1->is_empty() || this->cal2->is_empty() ) { + /* dc->npoints > 0 */ + /* g_print("erasers(1|2) reset\n"); */ + this->cal1->reset(); + this->cal2->reset(); + + this->cal1->moveto(this->point1[0]); + this->cal2->moveto(this->point2[0]); + } + + Geom::Point b1[BEZIER_MAX_LENGTH]; + gint const nb1 = Geom::bezier_fit_cubic_r(b1, this->point1, this->npoints, tolerance_sq, BEZIER_MAX_BEZIERS); + g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) ); + + Geom::Point b2[BEZIER_MAX_LENGTH]; + gint const nb2 = Geom::bezier_fit_cubic_r(b2, this->point2, this->npoints, tolerance_sq, BEZIER_MAX_BEZIERS); + g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) ); + + if ( nb1 != -1 && nb2 != -1 ) { + /* Fit and draw and reset state */ +#ifdef ERASER_VERBOSE + g_print("nb1:%d nb2:%d\n", nb1, nb2); +#endif + + /* CanvasShape */ + if (! release) { + this->currentcurve->reset(); + this->currentcurve->moveto(b1[0]); + + for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) { + this->currentcurve->curveto(bp1[1], bp1[2], bp1[3]); + } + + this->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]); + + for (Geom::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) { + this->currentcurve->curveto(bp2[2], bp2[1], bp2[0]); + } + + // FIXME: this->segments is always NULL at this point?? + if (!this->segments) { // first segment + add_cap(this->currentcurve, b2[1], b2[0], b1[0], b1[1], this->cap_rounding); + } + + this->currentcurve->closepath(); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->currentshape), this->currentcurve); + } + + /* Current eraser */ + for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) { + this->cal1->curveto(bp1[1], bp1[2], bp1[3]); + } + + for (Geom::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) { + this->cal2->curveto(bp2[1], bp2[2], bp2[3]); + } + } else { + /* fixme: ??? */ +#ifdef ERASER_VERBOSE + g_print("[fit_and_split] failed to fit-cubic.\n"); +#endif + this->draw_temporary_box(); + + for (gint i = 1; i < this->npoints; i++) { + this->cal1->lineto(this->point1[i]); + } + + for (gint i = 1; i < this->npoints; i++) { + this->cal2->lineto(this->point2[i]); + } + } + + /* Fit and draw and copy last point */ +#ifdef ERASER_VERBOSE + g_print("[%d]Yup\n", this->npoints); +#endif + if (!release) { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + gint eraserMode = prefs->getBool("/tools/eraser/mode") ? 1 : 0; + g_assert(!this->currentcurve->is_empty()); + + SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(desktop), SP_TYPE_CANVAS_BPATH, NULL); + SPCurve *curve = this->currentcurve->copy(); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve); + curve->unref(); + + guint32 fillColor = sp_desktop_get_color_tool (desktop, "/tools/eraser", true); + //guint32 strokeColor = sp_desktop_get_color_tool (desktop, "/tools/eraser", false); + double opacity = sp_desktop_get_master_opacity_tool (desktop, "/tools/eraser"); + double fillOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/eraser", true); + //double strokeOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/eraser", false); + sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD); + //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing + //sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), ((strokeColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*strokeOpacity)), 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + /* fixme: Cannot we cascade it to root more clearly? */ + g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), desktop); + + this->segments = g_slist_prepend(this->segments, cbp); + + if ( !eraserMode ) { + sp_canvas_item_hide(cbp); + sp_canvas_item_hide(this->currentshape); + } + } + + this->point1[0] = this->point1[this->npoints - 1]; + this->point2[0] = this->point2[this->npoints - 1]; + this->npoints = 1; + } else { + this->draw_temporary_box(); + } +} + +void EraserTool::draw_temporary_box() { + this->currentcurve->reset(); + + this->currentcurve->moveto(this->point1[this->npoints-1]); + + for (gint i = this->npoints-2; i >= 0; i--) { + this->currentcurve->lineto(this->point1[i]); + } + + for (gint i = 0; i < this->npoints; i++) { + this->currentcurve->lineto(this->point2[i]); + } + + if (this->npoints >= 2) { + add_cap(this->currentcurve, this->point2[this->npoints-2], this->point2[this->npoints-1], this->point1[this->npoints-1], this->point1[this->npoints-2], this->cap_rounding); + } + + this->currentcurve->closepath(); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->currentshape), this->currentcurve); +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/eraser-tool.h b/src/ui/tools/eraser-tool.h new file mode 100644 index 000000000..eb7eb16e8 --- /dev/null +++ b/src/ui/tools/eraser-tool.h @@ -0,0 +1,76 @@ +#ifndef SP_ERASER_CONTEXT_H_SEEN +#define SP_ERASER_CONTEXT_H_SEEN + +/* + * Handwriting-like drawing mode + * + * Authors: + * Mitsuru Oka <oka326@parkcity.ne.jp> + * Lauris Kaplinski <lauris@kaplinski.com> + * + * The original dynadraw code: + * Paul Haeberli <paul@sgi.com> + * + * Copyright (C) 1998 The Free Software Foundation + * Copyright (C) 1999-2002 authors + * Copyright (C) 2001-2002 Ximian, Inc. + * Copyright (C) 2008 Jon A. Cruz + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "ui/tools/dynamic-base.h" + +#define ERC_MIN_PRESSURE 0.0 +#define ERC_MAX_PRESSURE 1.0 +#define ERC_DEFAULT_PRESSURE 1.0 + +#define ERC_MIN_TILT -1.0 +#define ERC_MAX_TILT 1.0 +#define ERC_DEFAULT_TILT 0.0 + +namespace Inkscape { +namespace UI { +namespace Tools { + +class EraserTool : public DynamicBase { +public: + EraserTool(); + virtual ~EraserTool(); + + static const std::string prefsPath; + + virtual void setup(); + virtual bool root_handler(GdkEvent* event); + + virtual const std::string& getPrefsPath(); + +private: + void reset(Geom::Point p); + void extinput(GdkEvent *event); + bool apply(Geom::Point p); + void brush(); + void cancel(); + void clear_current(); + void set_to_accumulated(); + void accumulate(); + void fit_and_split(bool release); + void draw_temporary_box(); +}; + +} +} +} + +#endif // SP_ERASER_CONTEXT_H_SEEN + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/flood-tool.cpp b/src/ui/tools/flood-tool.cpp new file mode 100644 index 000000000..d74848dc6 --- /dev/null +++ b/src/ui/tools/flood-tool.cpp @@ -0,0 +1,1258 @@ +/** + * @file + * Bucket fill drawing context, works by bitmap filling an area on a rendered version + * of the current display and then tracing the result using potrace. + */ +/* Author: + * Lauris Kaplinski <lauris@kaplinski.com> + * bulia byak <buliabyak@users.sf.net> + * John Bintz <jcoswell@coswellproductions.org> + * Jon A. Cruz <jon@joncruz.org> + * Abhishek Sharma + * + * Copyright (C) 2006 Johan Engelen <johan@shouraizou.nl> + * Copyright (C) 2000-2005 authors + * Copyright (C) 2000-2001 Ximian, Inc. + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "trace/potrace/inkscape-potrace.h" +#include <2geom/pathvector.h> +#include <gdk/gdkkeysyms.h> +#include <queue> +#include <deque> +#include <glibmm/i18n.h> + +#include "color.h" +#include "context-fns.h" +#include "desktop.h" +#include "desktop-handles.h" +#include "desktop-style.h" +#include "display/cairo-utils.h" +#include "display/drawing-context.h" +#include "display/drawing-image.h" +#include "display/drawing-item.h" +#include "display/drawing.h" +#include "display/sp-canvas.h" +#include "document.h" +#include "document-undo.h" +#include "ui/tools/flood-tool.h" +#include "livarot/Path.h" +#include "livarot/Shape.h" +#include "macros.h" +#include "message-context.h" +#include "message-stack.h" +#include "preferences.h" +#include "rubberband.h" +#include "selection.h" +#include "shape-editor.h" +#include "sp-defs.h" +#include "sp-item.h" +#include "splivarot.h" +#include "sp-namedview.h" +#include "sp-object.h" +#include "sp-path.h" +#include "sp-rect.h" +#include "sp-root.h" +#include "svg/svg.h" +#include "trace/imagemap.h" +#include "trace/trace.h" +#include "xml/node-event-vector.h" +#include "xml/repr.h" +#include "verbs.h" + +#include "pixmaps/cursor-paintbucket.xpm" + +using Inkscape::DocumentUndo; + +using Inkscape::Display::ExtractARGB32; +using Inkscape::Display::ExtractRGB32; +using Inkscape::Display::AssembleARGB32; + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +namespace { + ToolBase* createPaintbucketContext() { + return new FloodTool(); + } + + bool paintbucketContextRegistered = ToolFactory::instance().registerObject("/tools/paintbucket", createPaintbucketContext); +} + +const std::string& FloodTool::getPrefsPath() { + return FloodTool::prefsPath; +} + +const std::string FloodTool::prefsPath = "/tools/paintbucket"; + +FloodTool::FloodTool() + : ToolBase(cursor_paintbucket_xpm, 11, 30) + , item(NULL) +{ + // TODO: Why does the flood tool use a hardcoded tolerance instead of a pref? + this->tolerance = 4; +} + +FloodTool::~FloodTool() { + this->sel_changed_connection.disconnect(); + + delete this->shape_editor; + this->shape_editor = NULL; + + /* fixme: This is necessary because we do not grab */ + if (this->item) { + this->finishItem(); + } +} + +/** + * Callback that processes the "changed" signal on the selection; + * destroys old and creates new knotholder. + */ +void FloodTool::selection_changed(Inkscape::Selection* selection) { + this->shape_editor->unset_item(SH_KNOTHOLDER); + this->shape_editor->set_item(selection->singleItem(), SH_KNOTHOLDER); +} + +void FloodTool::setup() { + ToolBase::setup(); + + this->shape_editor = new ShapeEditor(this->desktop); + + SPItem *item = sp_desktop_selection(this->desktop)->singleItem(); + if (item) { + this->shape_editor->set_item(item, SH_KNOTHOLDER); + } + + this->sel_changed_connection.disconnect(); + this->sel_changed_connection = sp_desktop_selection(this->desktop)->connectChanged( + sigc::mem_fun(this, &FloodTool::selection_changed) + ); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + if (prefs->getBool("/tools/paintbucket/selcue")) { + this->enableSelectionCue(); + } +} + + +// Changes from 0.48 -> 0.49 (Cairo) +// 0.49: Ignores alpha in background +// 0.48: RGBA, 0.49 ARGB +// 0.49: premultiplied alpha +inline static guint32 compose_onto(guint32 px, guint32 bg) +{ + guint ap = 0, rp = 0, gp = 0, bp = 0; + guint rb = 0, gb = 0, bb = 0; + ExtractARGB32(px, ap, rp, gp, bp); + ExtractRGB32(bg, rb, gb, bb); + + // guint ao = 255*255 - (255-ap)*(255-bp); ao = (ao + 127) / 255; + // guint ao = (255-ap)*ab + 255*ap; ao = (ao + 127) / 255; + guint ao = 255; // Cairo version doesn't allow background to have alpha != 1. + guint ro = (255-ap)*rb + 255*rp; ro = (ro + 127) / 255; + guint go = (255-ap)*gb + 255*gp; go = (go + 127) / 255; + guint bo = (255-ap)*bb + 255*bp; bo = (bo + 127) / 255; + + guint pxout = AssembleARGB32(ao, ro, go, bo); + return pxout; +} + +/** + * Get the pointer to a pixel in a pixel buffer. + * @param px The pixel buffer. + * @param x The X coordinate. + * @param y The Y coordinate. + * @param stride The rowstride of the pixel buffer. + */ +inline guint32 get_pixel(guchar *px, int x, int y, int stride) { + return *reinterpret_cast<guint32*>(px + y * stride + x * 4); +} + +inline unsigned char * get_trace_pixel(guchar *trace_px, int x, int y, int width) { + return trace_px + (x + y * width); +} + +/** + * Generate the list of trace channel selection entries. + */ +GList * flood_channels_dropdown_items_list() { + GList *glist = NULL; + + glist = g_list_append (glist, _("Visible Colors")); + glist = g_list_append (glist, _("Red")); + glist = g_list_append (glist, _("Green")); + glist = g_list_append (glist, _("Blue")); + glist = g_list_append (glist, _("Hue")); + glist = g_list_append (glist, _("Saturation")); + glist = g_list_append (glist, _("Lightness")); + glist = g_list_append (glist, _("Alpha")); + + return glist; +} + +/** + * Generate the list of autogap selection entries. + */ +GList * flood_autogap_dropdown_items_list() { + GList *glist = NULL; + + glist = g_list_append (glist, (void*) C_("Flood autogap", "None")); + glist = g_list_append (glist, (void*) C_("Flood autogap", "Small")); + glist = g_list_append (glist, (void*) C_("Flood autogap", "Medium")); + glist = g_list_append (glist, (void*) C_("Flood autogap", "Large")); + + return glist; +} + +/** + * Compare a pixel in a pixel buffer with another pixel to determine if a point should be included in the fill operation. + * @param check The pixel in the pixel buffer to check. + * @param orig The original selected pixel to use as the fill target color. + * @param merged_orig_pixel The original pixel merged with the background. + * @param dtc The desktop background color. + * @param threshold The fill threshold. + * @param method The fill method to use as defined in PaintBucketChannels. + */ +static bool compare_pixels(guint32 check, guint32 orig, guint32 merged_orig_pixel, guint32 dtc, int threshold, PaintBucketChannels method) +{ + int diff = 0; + float hsl_check[3] = {0,0,0}, hsl_orig[3] = {0,0,0}; + + guint32 ac = 0, rc = 0, gc = 0, bc = 0; + ExtractARGB32(check, ac, rc, gc, bc); + + guint32 ao = 0, ro = 0, go = 0, bo = 0; + ExtractARGB32(orig, ao, ro, go, bo); + + guint32 ad = 0, rd = 0, gd = 0, bd = 0; + ExtractARGB32(dtc, ad, rd, gd, bd); + + guint32 amop = 0, rmop = 0, gmop = 0, bmop = 0; + ExtractARGB32(merged_orig_pixel, amop, rmop, gmop, bmop); + + if ((method == FLOOD_CHANNELS_H) || + (method == FLOOD_CHANNELS_S) || + (method == FLOOD_CHANNELS_L)) { + double dac = ac; + double dao = ao; + sp_color_rgb_to_hsl_floatv(hsl_check, rc / dac, gc / dac, bc / dac); + sp_color_rgb_to_hsl_floatv(hsl_orig, ro / dao, go / dao, bo / dao); + } + + switch (method) { + case FLOOD_CHANNELS_ALPHA: + return abs(static_cast<int>(ac) - ao) <= threshold; + case FLOOD_CHANNELS_R: + return abs(static_cast<int>(ac ? unpremul_alpha(rc, ac) : 0) - (ao ? unpremul_alpha(ro, ao) : 0)) <= threshold; + case FLOOD_CHANNELS_G: + return abs(static_cast<int>(ac ? unpremul_alpha(gc, ac) : 0) - (ao ? unpremul_alpha(go, ao) : 0)) <= threshold; + case FLOOD_CHANNELS_B: + return abs(static_cast<int>(ac ? unpremul_alpha(bc, ac) : 0) - (ao ? unpremul_alpha(bo, ao) : 0)) <= threshold; + case FLOOD_CHANNELS_RGB: + guint32 amc, rmc, bmc, gmc; + //amc = 255*255 - (255-ac)*(255-ad); amc = (amc + 127) / 255; + //amc = (255-ac)*ad + 255*ac; amc = (amc + 127) / 255; + amc = 255; // Why are we looking at desktop? Cairo version ignores destop alpha + rmc = (255-ac)*rd + 255*rc; rmc = (rmc + 127) / 255; + gmc = (255-ac)*gd + 255*gc; gmc = (gmc + 127) / 255; + bmc = (255-ac)*bd + 255*bc; bmc = (bmc + 127) / 255; + + diff += abs(static_cast<int>(amc ? unpremul_alpha(rmc, amc) : 0) - (amop ? unpremul_alpha(rmop, amop) : 0)); + diff += abs(static_cast<int>(amc ? unpremul_alpha(gmc, amc) : 0) - (amop ? unpremul_alpha(gmop, amop) : 0)); + diff += abs(static_cast<int>(amc ? unpremul_alpha(bmc, amc) : 0) - (amop ? unpremul_alpha(bmop, amop) : 0)); + return ((diff / 3) <= ((threshold * 3) / 4)); + + case FLOOD_CHANNELS_H: + return ((int)(fabs(hsl_check[0] - hsl_orig[0]) * 100.0) <= threshold); + case FLOOD_CHANNELS_S: + return ((int)(fabs(hsl_check[1] - hsl_orig[1]) * 100.0) <= threshold); + case FLOOD_CHANNELS_L: + return ((int)(fabs(hsl_check[2] - hsl_orig[2]) * 100.0) <= threshold); + } + + return false; +} + +enum { + PIXEL_CHECKED = 1, + PIXEL_QUEUED = 2, + PIXEL_PAINTABLE = 4, + PIXEL_NOT_PAINTABLE = 8, + PIXEL_COLORED = 16 +}; + +static inline bool is_pixel_checked(unsigned char *t) { return (*t & PIXEL_CHECKED) == PIXEL_CHECKED; } +static inline bool is_pixel_queued(unsigned char *t) { return (*t & PIXEL_QUEUED) == PIXEL_QUEUED; } +static inline bool is_pixel_paintability_checked(unsigned char *t) { + return !((*t & PIXEL_PAINTABLE) == 0) && ((*t & PIXEL_NOT_PAINTABLE) == 0); +} +static inline bool is_pixel_paintable(unsigned char *t) { return (*t & PIXEL_PAINTABLE) == PIXEL_PAINTABLE; } +static inline bool is_pixel_colored(unsigned char *t) { return (*t & PIXEL_COLORED) == PIXEL_COLORED; } + +static inline void mark_pixel_checked(unsigned char *t) { *t |= PIXEL_CHECKED; } +static inline void mark_pixel_unchecked(unsigned char *t) { *t ^= PIXEL_CHECKED; } +static inline void mark_pixel_queued(unsigned char *t) { *t |= PIXEL_QUEUED; } +static inline void mark_pixel_paintable(unsigned char *t) { *t |= PIXEL_PAINTABLE; *t ^= PIXEL_NOT_PAINTABLE; } +static inline void mark_pixel_not_paintable(unsigned char *t) { *t |= PIXEL_NOT_PAINTABLE; *t ^= PIXEL_PAINTABLE; } +static inline void mark_pixel_colored(unsigned char *t) { *t |= PIXEL_COLORED; } + +static inline void clear_pixel_paintability(unsigned char *t) { *t ^= PIXEL_PAINTABLE; *t ^= PIXEL_NOT_PAINTABLE; } + +struct bitmap_coords_info { + bool is_left; + unsigned int x; + unsigned int y; + int y_limit; + unsigned int width; + unsigned int height; + unsigned int stride; + unsigned int threshold; + unsigned int radius; + PaintBucketChannels method; + guint32 dtc; + guint32 merged_orig_pixel; + Geom::Rect bbox; + Geom::Rect screen; + unsigned int max_queue_size; + unsigned int current_step; +}; + +/** + * Check if a pixel can be included in the fill. + * @param px The rendered pixel buffer to check. + * @param trace_t The pixel in the trace pixel buffer to check or mark. + * @param x The X coordinate. + * @param y The y coordinate. + * @param orig_color The original selected pixel to use as the fill target color. + * @param bci The bitmap_coords_info structure. + */ +inline static bool check_if_pixel_is_paintable(guchar *px, unsigned char *trace_t, int x, int y, guint32 orig_color, bitmap_coords_info bci) { + if (is_pixel_paintability_checked(trace_t)) { + return is_pixel_paintable(trace_t); + } else { + guint32 pixel = get_pixel(px, x, y, bci.stride); + if (compare_pixels(pixel, orig_color, bci.merged_orig_pixel, bci.dtc, bci.threshold, bci.method)) { + mark_pixel_paintable(trace_t); + return true; + } else { + mark_pixel_not_paintable(trace_t); + return false; + } + } +} + +/** + * Perform the bitmap-to-vector tracing and place the traced path onto the document. + * @param px The trace pixel buffer to trace to SVG. + * @param desktop The desktop on which to place the final SVG path. + * @param transform The transform to apply to the final SVG path. + * @param union_with_selection If true, merge the final SVG path with the current selection. + */ +static void do_trace(bitmap_coords_info bci, guchar *trace_px, SPDesktop *desktop, Geom::Affine transform, unsigned int min_x, unsigned int max_x, unsigned int min_y, unsigned int max_y, bool union_with_selection) { + SPDocument *document = sp_desktop_document(desktop); + + unsigned char *trace_t; + + GrayMap *gray_map = GrayMapCreate((max_x - min_x + 1), (max_y - min_y + 1)); + unsigned int gray_map_y = 0; + for (unsigned int y = min_y; y <= max_y; y++) { + unsigned long *gray_map_t = gray_map->rows[gray_map_y]; + + trace_t = get_trace_pixel(trace_px, min_x, y, bci.width); + for (unsigned int x = min_x; x <= max_x; x++) { + *gray_map_t = is_pixel_colored(trace_t) ? GRAYMAP_BLACK : GRAYMAP_WHITE; + gray_map_t++; + trace_t++; + } + gray_map_y++; + } + + Inkscape::Trace::Potrace::PotraceTracingEngine pte; + pte.keepGoing = 1; + std::vector<Inkscape::Trace::TracingEngineResult> results = pte.traceGrayMap(gray_map); + gray_map->destroy(gray_map); + + //XML Tree being used here directly while it shouldn't be...." + Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); + + long totalNodeCount = 0L; + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + double offset = prefs->getDouble("/tools/paintbucket/offset", 0.0); + + for (unsigned int i=0 ; i<results.size() ; i++) { + Inkscape::Trace::TracingEngineResult result = results[i]; + totalNodeCount += result.getNodeCount(); + + Inkscape::XML::Node *pathRepr = xml_doc->createElement("svg:path"); + /* Set style */ + sp_desktop_apply_style_tool (desktop, pathRepr, "/tools/paintbucket", false); + + Geom::PathVector pathv = sp_svg_read_pathv(result.getPathData().c_str()); + Path *path = new Path; + path->LoadPathVector(pathv); + + if (offset != 0) { + + Shape *path_shape = new Shape(); + + path->ConvertWithBackData(0.03); + path->Fill(path_shape, 0); + delete path; + + Shape *expanded_path_shape = new Shape(); + + expanded_path_shape->ConvertToShape(path_shape, fill_nonZero); + path_shape->MakeOffset(expanded_path_shape, offset * desktop->current_zoom(), join_round, 4); + expanded_path_shape->ConvertToShape(path_shape, fill_positive); + + Path *expanded_path = new Path(); + + expanded_path->Reset(); + expanded_path_shape->ConvertToForme(expanded_path); + expanded_path->ConvertEvenLines(1.0); + expanded_path->Simplify(1.0); + + delete path_shape; + delete expanded_path_shape; + + gchar *str = expanded_path->svg_dump_path(); + if (str && *str) { + pathRepr->setAttribute("d", str); + g_free(str); + } else { + desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Too much inset</b>, the result is empty.")); + Inkscape::GC::release(pathRepr); + g_free(str); + return; + } + + delete expanded_path; + + } else { + gchar *str = path->svg_dump_path(); + delete path; + pathRepr->setAttribute("d", str); + g_free(str); + } + + desktop->currentLayer()->addChild(pathRepr,NULL); + + SPObject *reprobj = document->getObjectByRepr(pathRepr); + if (reprobj) { + SP_ITEM(reprobj)->doWriteTransform(pathRepr, transform, NULL); + + // premultiply the item transform by the accumulated parent transform in the paste layer + Geom::Affine local (SP_GROUP(desktop->currentLayer())->i2doc_affine()); + if (!local.isIdentity()) { + gchar const *t_str = pathRepr->attribute("transform"); + Geom::Affine item_t (Geom::identity()); + if (t_str) + sp_svg_transform_read(t_str, &item_t); + item_t *= local.inverse(); + // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform) + gchar *affinestr=sp_svg_transform_write(item_t); + pathRepr->setAttribute("transform", affinestr); + g_free(affinestr); + } + + Inkscape::Selection *selection = sp_desktop_selection(desktop); + + pathRepr->setPosition(-1); + + if (union_with_selection) { + desktop->messageStack()->flashF( Inkscape::WARNING_MESSAGE, + ngettext("Area filled, path with <b>%d</b> node created and unioned with selection.","Area filled, path with <b>%d</b> nodes created and unioned with selection.", + SP_PATH(reprobj)->nodesInPath()), SP_PATH(reprobj)->nodesInPath() ); + selection->add(reprobj); + sp_selected_path_union_skip_undo(sp_desktop_selection(desktop), desktop); + } else { + desktop->messageStack()->flashF( Inkscape::WARNING_MESSAGE, + ngettext("Area filled, path with <b>%d</b> node created.","Area filled, path with <b>%d</b> nodes created.", + SP_PATH(reprobj)->nodesInPath()), SP_PATH(reprobj)->nodesInPath() ); + selection->set(reprobj); + } + + } + + Inkscape::GC::release(pathRepr); + + } +} + +/** + * The possible return states of perform_bitmap_scanline_check(). + */ +enum ScanlineCheckResult { + SCANLINE_CHECK_OK, + SCANLINE_CHECK_ABORTED, + SCANLINE_CHECK_BOUNDARY +}; + +/** + * Determine if the provided coordinates are within the pixel buffer limits. + * @param x The X coordinate. + * @param y The Y coordinate. + * @param bci The bitmap_coords_info structure. + */ +inline static bool coords_in_range(unsigned int x, unsigned int y, bitmap_coords_info bci) { + return (x < bci.width) && + (y < bci.height); +} + +#define PAINT_DIRECTION_LEFT 1 +#define PAINT_DIRECTION_RIGHT 2 +#define PAINT_DIRECTION_UP 4 +#define PAINT_DIRECTION_DOWN 8 +#define PAINT_DIRECTION_ALL 15 + +/** + * Paint a pixel or a square (if autogap is enabled) on the trace pixel buffer. + * @param px The rendered pixel buffer to check. + * @param trace_px The trace pixel buffer. + * @param orig_color The original selected pixel to use as the fill target color. + * @param bci The bitmap_coords_info structure. + * @param original_point_trace_t The original pixel in the trace pixel buffer to check. + */ +inline static unsigned int paint_pixel(guchar *px, guchar *trace_px, guint32 orig_color, bitmap_coords_info bci, unsigned char *original_point_trace_t) { + if (bci.radius == 0) { + mark_pixel_colored(original_point_trace_t); + return PAINT_DIRECTION_ALL; + } else { + unsigned char *trace_t; + + bool can_paint_up = true; + bool can_paint_down = true; + bool can_paint_left = true; + bool can_paint_right = true; + + for (unsigned int ty = bci.y - bci.radius; ty <= bci.y + bci.radius; ty++) { + for (unsigned int tx = bci.x - bci.radius; tx <= bci.x + bci.radius; tx++) { + if (coords_in_range(tx, ty, bci)) { + trace_t = get_trace_pixel(trace_px, tx, ty, bci.width); + if (!is_pixel_colored(trace_t)) { + if (check_if_pixel_is_paintable(px, trace_t, tx, ty, orig_color, bci)) { + mark_pixel_colored(trace_t); + } else { + if (tx < bci.x) { can_paint_left = false; } + if (tx > bci.x) { can_paint_right = false; } + if (ty < bci.y) { can_paint_up = false; } + if (ty > bci.y) { can_paint_down = false; } + } + } + } + } + } + + unsigned int paint_directions = 0; + if (can_paint_left) { paint_directions += PAINT_DIRECTION_LEFT; } + if (can_paint_right) { paint_directions += PAINT_DIRECTION_RIGHT; } + if (can_paint_up) { paint_directions += PAINT_DIRECTION_UP; } + if (can_paint_down) { paint_directions += PAINT_DIRECTION_DOWN; } + + return paint_directions; + } +} + +/** + * Push a point to be checked onto the bottom of the rendered pixel buffer check queue. + * @param fill_queue The fill queue to add the point to. + * @param max_queue_size The maximum size of the fill queue. + * @param trace_t The trace pixel buffer pixel. + * @param x The X coordinate. + * @param y The Y coordinate. + */ +static void push_point_onto_queue(std::deque<Geom::Point> *fill_queue, unsigned int max_queue_size, unsigned char *trace_t, unsigned int x, unsigned int y) { + if (!is_pixel_queued(trace_t)) { + if ((fill_queue->size() < max_queue_size)) { + fill_queue->push_back(Geom::Point(x, y)); + mark_pixel_queued(trace_t); + } + } +} + +/** + * Shift a point to be checked onto the top of the rendered pixel buffer check queue. + * @param fill_queue The fill queue to add the point to. + * @param max_queue_size The maximum size of the fill queue. + * @param trace_t The trace pixel buffer pixel. + * @param x The X coordinate. + * @param y The Y coordinate. + */ +static void shift_point_onto_queue(std::deque<Geom::Point> *fill_queue, unsigned int max_queue_size, unsigned char *trace_t, unsigned int x, unsigned int y) { + if (!is_pixel_queued(trace_t)) { + if ((fill_queue->size() < max_queue_size)) { + fill_queue->push_front(Geom::Point(x, y)); + mark_pixel_queued(trace_t); + } + } +} + +/** + * Scan a row in the rendered pixel buffer and add points to the fill queue as necessary. + * @param fill_queue The fill queue to add the point to. + * @param px The rendered pixel buffer. + * @param trace_px The trace pixel buffer. + * @param orig_color The original selected pixel to use as the fill target color. + * @param bci The bitmap_coords_info structure. + */ +static ScanlineCheckResult perform_bitmap_scanline_check(std::deque<Geom::Point> *fill_queue, guchar *px, guchar *trace_px, guint32 orig_color, bitmap_coords_info bci, unsigned int *min_x, unsigned int *max_x) { + bool aborted = false; + bool reached_screen_boundary = false; + bool ok; + + bool keep_tracing; + bool initial_paint = true; + + unsigned char *current_trace_t = get_trace_pixel(trace_px, bci.x, bci.y, bci.width); + unsigned int paint_directions; + + bool currently_painting_top = false; + bool currently_painting_bottom = false; + + unsigned int top_ty = bci.y - 1; + unsigned int bottom_ty = bci.y + 1; + + bool can_paint_top = (top_ty > 0); + bool can_paint_bottom = (bottom_ty < bci.height); + + Geom::Point t = fill_queue->front(); + + do { + ok = false; + if (bci.is_left) { + keep_tracing = (bci.x != 0); + } else { + keep_tracing = (bci.x < bci.width); + } + + *min_x = MIN(*min_x, bci.x); + *max_x = MAX(*max_x, bci.x); + + if (keep_tracing) { + if (check_if_pixel_is_paintable(px, current_trace_t, bci.x, bci.y, orig_color, bci)) { + paint_directions = paint_pixel(px, trace_px, orig_color, bci, current_trace_t); + if (bci.radius == 0) { + mark_pixel_checked(current_trace_t); + if ((t[Geom::X] == bci.x) && (t[Geom::Y] == bci.y)) { + fill_queue->pop_front(); t = fill_queue->front(); + } + } + + if (can_paint_top) { + if (paint_directions & PAINT_DIRECTION_UP) { + unsigned char *trace_t = current_trace_t - bci.width; + if (!is_pixel_queued(trace_t)) { + bool ok_to_paint = check_if_pixel_is_paintable(px, trace_t, bci.x, top_ty, orig_color, bci); + + if (initial_paint) { currently_painting_top = !ok_to_paint; } + + if (ok_to_paint && (!currently_painting_top)) { + currently_painting_top = true; + push_point_onto_queue(fill_queue, bci.max_queue_size, trace_t, bci.x, top_ty); + } + if ((!ok_to_paint) && currently_painting_top) { + currently_painting_top = false; + } + } + } + } + + if (can_paint_bottom) { + if (paint_directions & PAINT_DIRECTION_DOWN) { + unsigned char *trace_t = current_trace_t + bci.width; + if (!is_pixel_queued(trace_t)) { + bool ok_to_paint = check_if_pixel_is_paintable(px, trace_t, bci.x, bottom_ty, orig_color, bci); + + if (initial_paint) { currently_painting_bottom = !ok_to_paint; } + + if (ok_to_paint && (!currently_painting_bottom)) { + currently_painting_bottom = true; + push_point_onto_queue(fill_queue, bci.max_queue_size, trace_t, bci.x, bottom_ty); + } + if ((!ok_to_paint) && currently_painting_bottom) { + currently_painting_bottom = false; + } + } + } + } + + if (bci.is_left) { + if (paint_directions & PAINT_DIRECTION_LEFT) { + bci.x--; current_trace_t--; + ok = true; + } + } else { + if (paint_directions & PAINT_DIRECTION_RIGHT) { + bci.x++; current_trace_t++; + ok = true; + } + } + + initial_paint = false; + } + } else { + if (bci.bbox.min()[Geom::X] > bci.screen.min()[Geom::X]) { + aborted = true; break; + } else { + reached_screen_boundary = true; + } + } + } while (ok); + + if (aborted) { return SCANLINE_CHECK_ABORTED; } + if (reached_screen_boundary) { return SCANLINE_CHECK_BOUNDARY; } + return SCANLINE_CHECK_OK; +} + +/** + * Sort the rendered pixel buffer check queue vertically. + */ +static bool sort_fill_queue_vertical(Geom::Point a, Geom::Point b) { + return a[Geom::Y] > b[Geom::Y]; +} + +/** + * Sort the rendered pixel buffer check queue horizontally. + */ +static bool sort_fill_queue_horizontal(Geom::Point a, Geom::Point b) { + return a[Geom::X] > b[Geom::X]; +} + +/** + * Perform a flood fill operation. + * @param event_context The event context for this tool. + * @param event The details of this event. + * @param union_with_selection If true, union the new fill with the current selection. + * @param is_point_fill If false, use the Rubberband "touch selection" to get the initial points for the fill. + * @param is_touch_fill If true, use only the initial contact point in the Rubberband "touch selection" as the fill target color. + */ +static void sp_flood_do_flood_fill(ToolBase *event_context, GdkEvent *event, bool union_with_selection, bool is_point_fill, bool is_touch_fill) { + SPDesktop *desktop = event_context->desktop; + SPDocument *document = sp_desktop_document(desktop); + + document->ensureUpToDate(); + + Geom::OptRect bbox = document->getRoot()->visualBounds(); + + if (!bbox) { + desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill.")); + return; + } + + double zoom_scale = desktop->current_zoom(); + + // Render 160% of the physical display to the render pixel buffer, so that available + // fill areas off the screen can be included in the fill. + double padding = 1.6; + + Geom::Rect screen = desktop->get_display_area(); + + unsigned int width = (int)ceil(screen.width() * zoom_scale * padding); + unsigned int height = (int)ceil(screen.height() * zoom_scale * padding); + + Geom::Point origin(screen.min()[Geom::X], + document->getHeight().value("px") - screen.height() - screen.min()[Geom::Y]); + + origin[Geom::X] += (screen.width() * ((1 - padding) / 2)); + origin[Geom::Y] += (screen.height() * ((1 - padding) / 2)); + + Geom::Scale scale(zoom_scale, zoom_scale); + Geom::Affine affine = scale * Geom::Translate(-origin * scale); + + int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width); + guchar *px = g_new(guchar, stride * height); + guint32 bgcolor, dtc; + + // Draw image into data block px + { // this block limits the lifetime of Drawing and DrawingContext + /* Create DrawingItems and set transform */ + unsigned dkey = SPItem::display_key_new(1); + Inkscape::Drawing drawing; + Inkscape::DrawingItem *root = document->getRoot()->invoke_show( drawing, dkey, SP_ITEM_SHOW_DISPLAY); + root->setTransform(affine); + drawing.setRoot(root); + + Geom::IntRect final_bbox = Geom::IntRect::from_xywh(0, 0, width, height); + drawing.update(final_bbox); + + cairo_surface_t *s = cairo_image_surface_create_for_data( + px, CAIRO_FORMAT_ARGB32, width, height, stride); + Inkscape::DrawingContext dc(s, Geom::Point(0,0)); + // cairo_translate not necessary here - surface origin is at 0,0 + + SPNamedView *nv = sp_desktop_namedview(desktop); + bgcolor = nv->pagecolor; + // bgcolor is 0xrrggbbaa, we need 0xaarrggbb + dtc = (bgcolor >> 8) | (bgcolor << 24); + + dc.setSource(bgcolor); + dc.setOperator(CAIRO_OPERATOR_SOURCE); + dc.paint(); + dc.setOperator(CAIRO_OPERATOR_OVER); + + drawing.render(dc, final_bbox); + + //cairo_surface_write_to_png( s, "cairo.png" ); + + cairo_surface_flush(s); + cairo_surface_destroy(s); + + // Hide items + document->getRoot()->invoke_hide(dkey); + } + + // { + // // Dump data to png + // cairo_surface_t *s = cairo_image_surface_create_for_data( + // px, CAIRO_FORMAT_ARGB32, width, height, stride); + // cairo_surface_write_to_png( s, "cairo2.png" ); + // std::cout << " Wrote cairo2.png" << std::endl; + // } + + guchar *trace_px = g_new(guchar, width * height); + memset(trace_px, 0x00, width * height); + + std::deque<Geom::Point> fill_queue; + std::queue<Geom::Point> color_queue; + + std::vector<Geom::Point> fill_points; + + bool aborted = false; + int y_limit = height - 1; + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + PaintBucketChannels method = (PaintBucketChannels) prefs->getInt("/tools/paintbucket/channels", 0); + int threshold = prefs->getIntLimited("/tools/paintbucket/threshold", 1, 0, 100); + + switch(method) { + case FLOOD_CHANNELS_ALPHA: + case FLOOD_CHANNELS_RGB: + case FLOOD_CHANNELS_R: + case FLOOD_CHANNELS_G: + case FLOOD_CHANNELS_B: + threshold = (255 * threshold) / 100; + break; + case FLOOD_CHANNELS_H: + case FLOOD_CHANNELS_S: + case FLOOD_CHANNELS_L: + break; + } + + bitmap_coords_info bci; + + bci.y_limit = y_limit; + bci.width = width; + bci.height = height; + bci.stride = stride; + bci.threshold = threshold; + bci.method = method; + bci.bbox = *bbox; + bci.screen = screen; + bci.dtc = dtc; + bci.radius = prefs->getIntLimited("/tools/paintbucket/autogap", 0, 0, 3); + bci.max_queue_size = (width * height) / 4; + bci.current_step = 0; + + if (is_point_fill) { + fill_points.push_back(Geom::Point(event->button.x, event->button.y)); + } else { + Inkscape::Rubberband *r = Inkscape::Rubberband::get(desktop); + fill_points = r->getPoints(); + } + + for (unsigned int i = 0; i < fill_points.size(); i++) { + Geom::Point pw = Geom::Point(fill_points[i][Geom::X] / zoom_scale, document->getHeight().value("px") + (fill_points[i][Geom::Y] / zoom_scale)) * affine; + + pw[Geom::X] = (int)MIN(width - 1, MAX(0, pw[Geom::X])); + pw[Geom::Y] = (int)MIN(height - 1, MAX(0, pw[Geom::Y])); + + if (is_touch_fill) { + if (i == 0) { + color_queue.push(pw); + } else { + unsigned char *trace_t = get_trace_pixel(trace_px, (int)pw[Geom::X], (int)pw[Geom::Y], width); + push_point_onto_queue(&fill_queue, bci.max_queue_size, trace_t, (int)pw[Geom::X], (int)pw[Geom::Y]); + } + } else { + color_queue.push(pw); + } + } + + bool reached_screen_boundary = false; + + bool first_run = true; + + unsigned long sort_size_threshold = 5; + + unsigned int min_y = height; + unsigned int max_y = 0; + unsigned int min_x = width; + unsigned int max_x = 0; + + while (!color_queue.empty() && !aborted) { + Geom::Point color_point = color_queue.front(); + color_queue.pop(); + + int cx = (int)color_point[Geom::X]; + int cy = (int)color_point[Geom::Y]; + + guint32 orig_color = get_pixel(px, cx, cy, stride); + bci.merged_orig_pixel = compose_onto(orig_color, dtc); + + unsigned char *trace_t = get_trace_pixel(trace_px, cx, cy, width); + if (!is_pixel_checked(trace_t) && !is_pixel_colored(trace_t)) { + if (check_if_pixel_is_paintable(px, trace_px, cx, cy, orig_color, bci)) { + shift_point_onto_queue(&fill_queue, bci.max_queue_size, trace_t, cx, cy); + + if (!first_run) { + for (unsigned int y = 0; y < height; y++) { + trace_t = get_trace_pixel(trace_px, 0, y, width); + for (unsigned int x = 0; x < width; x++) { + clear_pixel_paintability(trace_t); + trace_t++; + } + } + } + first_run = false; + } + } + + unsigned long old_fill_queue_size = fill_queue.size(); + + while (!fill_queue.empty() && !aborted) { + Geom::Point cp = fill_queue.front(); + + if (bci.radius == 0) { + unsigned long new_fill_queue_size = fill_queue.size(); + + /* + * To reduce the number of points in the fill queue, periodically + * resort all of the points in the queue so that scanline checks + * can complete more quickly. A point cannot be checked twice + * in a normal scanline checks, so forcing scanline checks to start + * from one corner of the rendered area as often as possible + * will reduce the number of points that need to be checked and queued. + */ + if (new_fill_queue_size > sort_size_threshold) { + if (new_fill_queue_size > old_fill_queue_size) { + std::sort(fill_queue.begin(), fill_queue.end(), sort_fill_queue_vertical); + + std::deque<Geom::Point>::iterator start_sort = fill_queue.begin(); + std::deque<Geom::Point>::iterator end_sort = fill_queue.begin(); + unsigned int sort_y = (unsigned int)cp[Geom::Y]; + unsigned int current_y = sort_y; + + for (std::deque<Geom::Point>::iterator i = fill_queue.begin(); i != fill_queue.end(); ++i) { + Geom::Point current = *i; + current_y = (unsigned int)current[Geom::Y]; + if (current_y != sort_y) { + if (start_sort != end_sort) { + std::sort(start_sort, end_sort, sort_fill_queue_horizontal); + } + sort_y = current_y; + start_sort = i; + } + end_sort = i; + } + if (start_sort != end_sort) { + std::sort(start_sort, end_sort, sort_fill_queue_horizontal); + } + + cp = fill_queue.front(); + } + } + + old_fill_queue_size = new_fill_queue_size; + } + + fill_queue.pop_front(); + + int x = (int)cp[Geom::X]; + int y = (int)cp[Geom::Y]; + + min_y = MIN((unsigned int)y, min_y); + max_y = MAX((unsigned int)y, max_y); + + unsigned char *trace_t = get_trace_pixel(trace_px, x, y, width); + if (!is_pixel_checked(trace_t)) { + mark_pixel_checked(trace_t); + + if (y == 0) { + if (bbox->min()[Geom::Y] > screen.min()[Geom::Y]) { + aborted = true; break; + } else { + reached_screen_boundary = true; + } + } + + if (y == y_limit) { + if (bbox->max()[Geom::Y] < screen.max()[Geom::Y]) { + aborted = true; break; + } else { + reached_screen_boundary = true; + } + } + + bci.is_left = true; + bci.x = x; + bci.y = y; + + ScanlineCheckResult result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci, &min_x, &max_x); + + switch (result) { + case SCANLINE_CHECK_ABORTED: + aborted = true; + break; + case SCANLINE_CHECK_BOUNDARY: + reached_screen_boundary = true; + break; + default: + break; + } + + if (bci.x < width) { + trace_t++; + if (!is_pixel_checked(trace_t) && !is_pixel_queued(trace_t)) { + mark_pixel_checked(trace_t); + bci.is_left = false; + bci.x = x + 1; + + result = perform_bitmap_scanline_check(&fill_queue, px, trace_px, orig_color, bci, &min_x, &max_x); + + switch (result) { + case SCANLINE_CHECK_ABORTED: + aborted = true; + break; + case SCANLINE_CHECK_BOUNDARY: + reached_screen_boundary = true; + break; + default: + break; + } + } + } + } + + bci.current_step++; + + if (bci.current_step > bci.max_queue_size) { + aborted = true; + } + } + } + + g_free(px); + + if (aborted) { + g_free(trace_px); + desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Area is not bounded</b>, cannot fill.")); + return; + } + + if (reached_screen_boundary) { + desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Only the visible part of the bounded area was filled.</b> If you want to fill all of the area, undo, zoom out, and fill again.")); + } + + unsigned int trace_padding = bci.radius + 1; + if (min_y > trace_padding) { min_y -= trace_padding; } + if (max_y < (y_limit - trace_padding)) { max_y += trace_padding; } + if (min_x > trace_padding) { min_x -= trace_padding; } + if (max_x < (width - 1 - trace_padding)) { max_x += trace_padding; } + + Geom::Point min_start = Geom::Point(min_x, min_y); + + affine = scale * Geom::Translate(-origin * scale - min_start); + Geom::Affine inverted_affine = Geom::Affine(affine).inverse(); + + do_trace(bci, trace_px, desktop, inverted_affine, min_x, max_x, min_y, max_y, union_with_selection); + + g_free(trace_px); + + DocumentUndo::done(document, SP_VERB_CONTEXT_PAINTBUCKET, _("Fill bounded area")); +} + +bool FloodTool::item_handler(SPItem* item, GdkEvent* event) { + gint ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + if ((event->button.state & GDK_CONTROL_MASK) && event->button.button == 1 && !this->space_panning) { + Geom::Point const button_w(event->button.x, event->button.y); + + SPItem *item = sp_event_context_find_item (desktop, button_w, TRUE, TRUE); + + // Set style + desktop->applyCurrentOrToolStyle(item, "/tools/paintbucket", false); + + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET, _("Set style on object")); + + ret = TRUE; + } + break; + + default: + break; + } + +// if (((ToolBaseClass *) sp_flood_context_parent_class)->item_handler) { +// ret = ((ToolBaseClass *) sp_flood_context_parent_class)->item_handler(event_context, item, event); +// } + // CPPIFY: ret is overwritten... + ret = ToolBase::item_handler(item, event); + + return ret; +} + +bool FloodTool::root_handler(GdkEvent* event) { + static bool dragging; + + gint ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + if (!(event->button.state & GDK_CONTROL_MASK)) { + Geom::Point const button_w(event->button.x, event->button.y); + + if (Inkscape::have_viable_layer(desktop, this->defaultMessageContext())) { + // save drag origin + this->xp = (gint) button_w[Geom::X]; + this->yp = (gint) button_w[Geom::Y]; + this->within_tolerance = true; + + dragging = true; + + Geom::Point const p(desktop->w2d(button_w)); + Inkscape::Rubberband::get(desktop)->setMode(RUBBERBAND_MODE_TOUCHPATH); + Inkscape::Rubberband::get(desktop)->start(desktop, p); + } + } + } + + case GDK_MOTION_NOTIFY: + if ( dragging && ( event->motion.state & GDK_BUTTON1_MASK ) && !this->space_panning) { + if ( this->within_tolerance + && ( abs( (gint) event->motion.x - this->xp ) < this->tolerance ) + && ( abs( (gint) event->motion.y - this->yp ) < this->tolerance ) ) { + break; // do not drag if we're within tolerance from origin + } + + this->within_tolerance = false; + + Geom::Point const motion_pt(event->motion.x, event->motion.y); + Geom::Point const p(desktop->w2d(motion_pt)); + + if (Inkscape::Rubberband::get(desktop)->is_started()) { + Inkscape::Rubberband::get(desktop)->move(p); + this->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Draw over</b> areas to add to fill, hold <b>Alt</b> for touch fill")); + gobble_motion_events(GDK_BUTTON1_MASK); + } + } + break; + + case GDK_BUTTON_RELEASE: + if (event->button.button == 1 && !this->space_panning) { + Inkscape::Rubberband *r = Inkscape::Rubberband::get(desktop); + + if (r->is_started()) { + // set "busy" cursor + desktop->setWaitingCursor(); + + if (SP_IS_EVENT_CONTEXT(this)) { + // Since setWaitingCursor runs main loop iterations, we may have already left this tool! + // So check if the tool is valid before doing anything + dragging = false; + + bool is_point_fill = this->within_tolerance; + bool is_touch_fill = event->button.state & GDK_MOD1_MASK; + + sp_flood_do_flood_fill(this, event, event->button.state & GDK_SHIFT_MASK, is_point_fill, is_touch_fill); + + desktop->clearWaitingCursor(); + // restore cursor when done; note that it may already be different if e.g. user + // switched to another tool during interruptible tracing or drawing, in which case do nothing + + ret = TRUE; + } + + r->stop(); + + //if (SP_IS_EVENT_CONTEXT(this)) { + this->defaultMessageContext()->clear(); + //} + } + } + break; + case GDK_KEY_PRESS: + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Up: + case GDK_KEY_Down: + case GDK_KEY_KP_Up: + case GDK_KEY_KP_Down: + // prevent the zoom field from activation + if (!MOD__CTRL_ONLY(event)) + ret = TRUE; + break; + default: + break; + } + break; + + default: + break; + } + + if (!ret) { + ret = ToolBase::root_handler(event); + } + + return ret; +} + +void FloodTool::finishItem() { + this->message_context->clear(); + + if (this->item != NULL) { + this->item->updateRepr(); + + desktop->canvas->endForcedFullRedraws(); + + sp_desktop_selection(desktop)->set(this->item); + + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_PAINTBUCKET, _("Fill bounded area")); + + this->item = NULL; + } +} + +void FloodTool::set_channels(gint channels) { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + prefs->setInt("/tools/paintbucket/channels", channels); +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/flood-tool.h b/src/ui/tools/flood-tool.h new file mode 100644 index 000000000..3ed670e8b --- /dev/null +++ b/src/ui/tools/flood-tool.h @@ -0,0 +1,68 @@ +#ifndef __SP_FLOOD_CONTEXT_H__ +#define __SP_FLOOD_CONTEXT_H__ + +/* + * Flood fill drawing context + * + * Authors: + * Lauris Kaplinski <lauris@kaplinski.com> + * John Bintz <jcoswell@coswellproductions.org> + * + * Released under GNU GPL + */ + +#include <stddef.h> +#include <sigc++/sigc++.h> +#include <gtk/gtk.h> +#include "ui/tools/tool-base.h" + +#define SP_FLOOD_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::FloodTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_FLOOD_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::FloodTool*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +namespace Inkscape { +namespace UI { +namespace Tools { + +class FloodTool : public ToolBase { +public: + FloodTool(); + virtual ~FloodTool(); + + SPItem *item; + + sigc::connection sel_changed_connection; + + static const std::string prefsPath; + + virtual void setup(); + virtual bool root_handler(GdkEvent* event); + virtual bool item_handler(SPItem* item, GdkEvent* event); + + virtual const std::string& getPrefsPath(); + + static void set_channels(gint channels); + +private: + void selection_changed(Inkscape::Selection* selection); + void finishItem(); +}; + +GList* flood_channels_dropdown_items_list (void); +GList* flood_autogap_dropdown_items_list (void); + +enum PaintBucketChannels { + FLOOD_CHANNELS_RGB, + FLOOD_CHANNELS_R, + FLOOD_CHANNELS_G, + FLOOD_CHANNELS_B, + FLOOD_CHANNELS_H, + FLOOD_CHANNELS_S, + FLOOD_CHANNELS_L, + FLOOD_CHANNELS_ALPHA +}; + +} +} +} + +#endif diff --git a/src/ui/tools/freehand-base.cpp b/src/ui/tools/freehand-base.cpp new file mode 100644 index 000000000..288a200f4 --- /dev/null +++ b/src/ui/tools/freehand-base.cpp @@ -0,0 +1,781 @@ +/* + * Generic drawing context + * + * Author: + * Lauris Kaplinski <lauris@kaplinski.com> + * Abhishek Sharma + * Jon A. Cruz <jon@joncruz.org> + * + * Copyright (C) 2000 Lauris Kaplinski + * Copyright (C) 2000-2001 Ximian, Inc. + * Copyright (C) 2002 Lauris Kaplinski + * Copyright (C) 2012 Johan Engelen + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#define DRAW_VERBOSE + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include "live_effects/lpe-patternalongpath.h" +#include "display/canvas-bpath.h" +#include "xml/repr.h" +#include "svg/svg.h" +#include <glibmm/i18n.h> +#include "display/curve.h" +#include "desktop.h" +#include "desktop-handles.h" +#include "desktop-style.h" +#include "document.h" +#include "draw-anchor.h" +#include "macros.h" +#include "message-stack.h" +#include "ui/tools/pen-tool.h" +#include "ui/tools/lpe-tool.h" +#include "preferences.h" +#include "selection.h" +#include "selection-chemistry.h" +#include "snap.h" +#include "sp-path.h" +#include "sp-namedview.h" +#include "live_effects/lpe-powerstroke.h" +#include "style.h" +#include "ui/control-manager.h" +#include "ui/tools/freehand-base.h" + +#include <gdk/gdkkeysyms.h> + +using Inkscape::DocumentUndo; + +namespace Inkscape { +namespace UI { +namespace Tools { + +static void spdc_selection_changed(Inkscape::Selection *sel, FreehandBase *dc); +static void spdc_selection_modified(Inkscape::Selection *sel, guint flags, FreehandBase *dc); + +static void spdc_attach_selection(FreehandBase *dc, Inkscape::Selection *sel); + +/** + * Flushes white curve(s) and additional curve into object. + * + * No cleaning of colored curves - this has to be done by caller + * No rereading of white data, so if you cannot rely on ::modified, do it in caller + */ +static void spdc_flush_white(FreehandBase *dc, SPCurve *gc); + +static void spdc_reset_white(FreehandBase *dc); +static void spdc_free_colors(FreehandBase *dc); + +FreehandBase::FreehandBase(gchar const *const *cursor_shape, gint hot_x, gint hot_y) + : ToolBase(cursor_shape, hot_x, hot_y) + , selection(NULL) + , grab(NULL) + , attach(false) + , red_color(0xff00007f) + , blue_color(0x0000ff7f) + , green_color(0x00ff007f) + , red_bpath(NULL) + , red_curve(NULL) + , blue_bpath(NULL) + , blue_curve(NULL) + , green_bpaths(NULL) + , green_curve(NULL) + , green_anchor(NULL) + , green_closed(false) + , white_item(NULL) + , white_curves(NULL) + , white_anchors(NULL) + , sa(NULL) + , ea(NULL) + , waiting_LPE_type(Inkscape::LivePathEffect::INVALID_LPE) + , red_curve_is_valid(false) + , anchor_statusbar(false) +{ +} + +FreehandBase::~FreehandBase() { + if (this->grab) { + sp_canvas_item_ungrab(this->grab, GDK_CURRENT_TIME); + this->grab = NULL; + } + + if (this->selection) { + this->selection = NULL; + } + + spdc_free_colors(this); +} + +void FreehandBase::setup() { + ToolBase::setup(); + + this->selection = sp_desktop_selection(desktop); + + // Connect signals to track selection changes + this->sel_changed_connection = this->selection->connectChanged( + sigc::bind(sigc::ptr_fun(&spdc_selection_changed), this) + ); + this->sel_modified_connection = this->selection->connectModified( + sigc::bind(sigc::ptr_fun(&spdc_selection_modified), this) + ); + + // Create red bpath + this->red_bpath = sp_canvas_bpath_new(sp_desktop_sketch(this->desktop), NULL); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->red_bpath), this->red_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + + // Create red curve + this->red_curve = new SPCurve(); + + // Create blue bpath + this->blue_bpath = sp_canvas_bpath_new(sp_desktop_sketch(this->desktop), NULL); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->blue_bpath), this->blue_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + + // Create blue curve + this->blue_curve = new SPCurve(); + + // Create green curve + this->green_curve = new SPCurve(); + + // No green anchor by default + this->green_anchor = NULL; + this->green_closed = FALSE; + + this->attach = TRUE; + spdc_attach_selection(this, this->selection); +} + +void FreehandBase::finish() { + this->sel_changed_connection.disconnect(); + this->sel_modified_connection.disconnect(); + + if (this->grab) { + sp_canvas_item_ungrab(this->grab, GDK_CURRENT_TIME); + } + + if (this->selection) { + this->selection = NULL; + } + + spdc_free_colors(this); + + ToolBase::finish(); +} + +void FreehandBase::set(const Inkscape::Preferences::Entry& /*value*/) { +} + +bool FreehandBase::root_handler(GdkEvent* event) { + gint ret = FALSE; + + switch (event->type) { + case GDK_KEY_PRESS: + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Up: + case GDK_KEY_Down: + case GDK_KEY_KP_Up: + case GDK_KEY_KP_Down: + // prevent the zoom field from activation + if (!MOD__CTRL_ONLY(event)) { + ret = TRUE; + } + break; + default: + break; + } + break; + default: + break; + } + + if (!ret) { + ret = ToolBase::root_handler(event); + } + + return ret; +} + +static Glib::ustring const tool_name(FreehandBase *dc) +{ + return ( SP_IS_PEN_CONTEXT(dc) + ? "/tools/freehand/pen" + : "/tools/freehand/pencil" ); +} + +static void spdc_paste_curve_as_freehand_shape(const SPCurve *c, FreehandBase *dc, SPItem *item) +{ + using namespace Inkscape::LivePathEffect; + + // TODO: Don't paste path if nothing is on the clipboard + + Effect::createAndApply(PATTERN_ALONG_PATH, dc->desktop->doc(), item); + Effect* lpe = SP_LPE_ITEM(item)->getCurrentLPE(); + gchar *svgd = sp_svg_write_path(c->get_pathvector()); + static_cast<LPEPatternAlongPath*>(lpe)->pattern.paste_param_path(svgd); +} + +static void spdc_apply_powerstroke_shape(const std::vector<Geom::Point> & points, FreehandBase *dc, SPItem *item) +{ + using namespace Inkscape::LivePathEffect; + + Effect::createAndApply(POWERSTROKE, dc->desktop->doc(), item); + Effect* lpe = SP_LPE_ITEM(item)->getCurrentLPE(); + static_cast<LPEPowerStroke*>(lpe)->offset_points.param_set_and_write_new_value(points); + + // write powerstroke parameters: + lpe->getRepr()->setAttribute("start_linecap_type", "zerowidth"); + lpe->getRepr()->setAttribute("end_linecap_type", "zerowidth"); + lpe->getRepr()->setAttribute("cusp_linecap_type", "round"); + lpe->getRepr()->setAttribute("sort_points", "true"); + lpe->getRepr()->setAttribute("interpolator_type", "CubicBezierJohan"); + lpe->getRepr()->setAttribute("interpolator_beta", "0.2"); +} + +static void spdc_check_for_and_apply_waiting_LPE(FreehandBase *dc, SPItem *item, SPCurve *curve) +{ + using namespace Inkscape::LivePathEffect; + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + if (item && SP_IS_LPE_ITEM(item)) { + if (prefs->getInt(tool_name(dc) + "/freehand-mode", 0) == 1) { + Effect::createAndApply(SPIRO, dc->desktop->doc(), item); + } + + int shape = prefs->getInt(tool_name(dc) + "/shape", 0); + bool shape_applied = false; + SPCSSAttr *css_item = sp_css_attr_from_object(item, SP_STYLE_FLAG_ALWAYS); + const char *cstroke = sp_repr_css_property(css_item, "stroke", "none"); + +#define SHAPE_LENGTH 10 +#define SHAPE_HEIGHT 10 + + switch (shape) { + case 0: + // don't apply any shape + break; + case 1: + { + // "triangle in" + std::vector<Geom::Point> points(1); + points[0] = Geom::Point(0., SHAPE_HEIGHT/2); + spdc_apply_powerstroke_shape(points, dc, item); + + shape_applied = true; + break; + } + case 2: + { + // "triangle out" + guint curve_length = curve->get_segment_count(); + std::vector<Geom::Point> points(1); + points[0] = Geom::Point((double)curve_length, SHAPE_HEIGHT/2); + spdc_apply_powerstroke_shape(points, dc, item); + + shape_applied = true; + break; + } + case 3: + { + // "ellipse" + SPCurve *c = new SPCurve(); + const double C1 = 0.552; + c->moveto(0, SHAPE_HEIGHT/2); + c->curveto(0, (1 - C1) * SHAPE_HEIGHT/2, (1 - C1) * SHAPE_LENGTH/2, 0, SHAPE_LENGTH/2, 0); + c->curveto((1 + C1) * SHAPE_LENGTH/2, 0, SHAPE_LENGTH, (1 - C1) * SHAPE_HEIGHT/2, SHAPE_LENGTH, SHAPE_HEIGHT/2); + c->curveto(SHAPE_LENGTH, (1 + C1) * SHAPE_HEIGHT/2, (1 + C1) * SHAPE_LENGTH/2, SHAPE_HEIGHT, SHAPE_LENGTH/2, SHAPE_HEIGHT); + c->curveto((1 - C1) * SHAPE_LENGTH/2, SHAPE_HEIGHT, 0, (1 + C1) * SHAPE_HEIGHT/2, 0, SHAPE_HEIGHT/2); + c->closepath(); + spdc_paste_curve_as_freehand_shape(c, dc, item); + c->unref(); + shape_applied = true; + break; + } + case 4: + { + // take shape from clipboard; TODO: catch the case where clipboard is empty + Effect::createAndApply(PATTERN_ALONG_PATH, dc->desktop->doc(), item); + Effect* lpe = SP_LPE_ITEM(item)->getCurrentLPE(); + static_cast<LPEPatternAlongPath*>(lpe)->pattern.on_paste_button_click(); + + shape_applied = true; + break; + } + default: + break; + } + if (shape_applied) { + // apply original stroke color as fill and unset stroke; then return + SPCSSAttr *css = sp_repr_css_attr_new(); + + if (!strcmp(cstroke, "none")){ + sp_repr_css_set_property (css, "fill", "black"); + } else { + sp_repr_css_set_property (css, "fill", cstroke); + } + sp_repr_css_set_property (css, "stroke", "none"); + sp_desktop_apply_css_recursive(item, css, true); + sp_repr_css_attr_unref(css); + return; + } + + if (dc->waiting_LPE_type != INVALID_LPE) { + Effect::createAndApply(dc->waiting_LPE_type, dc->desktop->doc(), item); + dc->waiting_LPE_type = INVALID_LPE; + + if (SP_IS_LPETOOL_CONTEXT(dc)) { + // since a geometric LPE was applied, we switch back to "inactive" mode + lpetool_context_switch_mode(SP_LPETOOL_CONTEXT(dc), INVALID_LPE); + } + } + if (SP_IS_PEN_CONTEXT(dc)) { + SP_PEN_CONTEXT(dc)->setPolylineMode(); + } + } +} + +/* + * Selection handlers + */ + +static void spdc_selection_changed(Inkscape::Selection *sel, FreehandBase *dc) +{ + if (dc->attach) { + spdc_attach_selection(dc, sel); + } +} + +/* fixme: We have to ensure this is not delayed (Lauris) */ + +static void spdc_selection_modified(Inkscape::Selection *sel, guint /*flags*/, FreehandBase *dc) +{ + if (dc->attach) { + spdc_attach_selection(dc, sel); + } +} + +static void spdc_attach_selection(FreehandBase *dc, Inkscape::Selection */*sel*/) +{ + // We reset white and forget white/start/end anchors + spdc_reset_white(dc); + dc->sa = NULL; + dc->ea = NULL; + + SPItem *item = dc->selection ? dc->selection->singleItem() : NULL; + + if ( item && SP_IS_PATH(item) ) { + // Create new white data + // Item + dc->white_item = item; + + // Curve list + // We keep it in desktop coordinates to eliminate calculation errors + SPCurve *norm = SP_PATH(item)->get_curve_for_edit(); + norm->transform((dc->white_item)->i2dt_affine()); + g_return_if_fail( norm != NULL ); + dc->white_curves = g_slist_reverse(norm->split()); + norm->unref(); + + // Anchor list + for (GSList *l = dc->white_curves; l != NULL; l = l->next) { + SPCurve *c; + c = static_cast<SPCurve*>(l->data); + g_return_if_fail( c->get_segment_count() > 0 ); + if ( !c->is_closed() ) { + SPDrawAnchor *a; + a = sp_draw_anchor_new(dc, c, TRUE, *(c->first_point())); + if (a) + dc->white_anchors = g_slist_prepend(dc->white_anchors, a); + a = sp_draw_anchor_new(dc, c, FALSE, *(c->last_point())); + if (a) + dc->white_anchors = g_slist_prepend(dc->white_anchors, a); + } + } + // fixme: recalculate active anchor? + } +} + + +void spdc_endpoint_snap_rotation(ToolBase const *const ec, Geom::Point &p, Geom::Point const &o, + guint state) +{ + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + unsigned const snaps = abs(prefs->getInt("/options/rotationsnapsperpi/value", 12)); + + SnapManager &m = ec->desktop->namedview->snap_manager; + m.setup(ec->desktop); + + bool snap_enabled = m.snapprefs.getSnapEnabledGlobally(); + if (state & GDK_SHIFT_MASK) { + // SHIFT disables all snapping, except the angular snapping. After all, the user explicitly asked for angular + // snapping by pressing CTRL, otherwise we wouldn't have arrived here. But although we temporarily disable + // the snapping here, we must still call for a constrained snap in order to apply the constraints (i.e. round + // to the nearest angle increment) + m.snapprefs.setSnapEnabledGlobally(false); + } + + Inkscape::SnappedPoint dummy = m.constrainedAngularSnap(Inkscape::SnapCandidatePoint(p, Inkscape::SNAPSOURCE_NODE_HANDLE), boost::optional<Geom::Point>(), o, snaps); + p = dummy.getPoint(); + + if (state & GDK_SHIFT_MASK) { + m.snapprefs.setSnapEnabledGlobally(snap_enabled); // restore the original setting + } + + m.unSetup(); +} + + +void spdc_endpoint_snap_free(ToolBase const * const ec, Geom::Point& p, boost::optional<Geom::Point> &start_of_line, guint const /*state*/) +{ + SPDesktop *dt = ec->desktop; + SnapManager &m = dt->namedview->snap_manager; + Inkscape::Selection *selection = sp_desktop_selection (dt); + + // selection->singleItem() is the item that is currently being drawn. This item will not be snapped to (to avoid self-snapping) + // TODO: Allow snapping to the stationary parts of the item, and only ignore the last segment + + m.setup(dt, true, selection->singleItem()); + Inkscape::SnapCandidatePoint scp(p, Inkscape::SNAPSOURCE_NODE_HANDLE); + if (start_of_line) { + scp.addOrigin(*start_of_line); + } + + Inkscape::SnappedPoint sp = m.freeSnap(scp); + p = sp.getPoint(); + + m.unSetup(); +} + +static SPCurve *reverse_then_unref(SPCurve *orig) +{ + SPCurve *ret = orig->create_reverse(); + orig->unref(); + return ret; +} + +void spdc_concat_colors_and_flush(FreehandBase *dc, gboolean forceclosed) +{ + // Concat RBG + SPCurve *c = dc->green_curve; + + // Green + dc->green_curve = new SPCurve(); + while (dc->green_bpaths) { + sp_canvas_item_destroy(SP_CANVAS_ITEM(dc->green_bpaths->data)); + dc->green_bpaths = g_slist_remove(dc->green_bpaths, dc->green_bpaths->data); + } + + // Blue + c->append_continuous(dc->blue_curve, 0.0625); + dc->blue_curve->reset(); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->blue_bpath), NULL); + + // Red + if (dc->red_curve_is_valid) { + c->append_continuous(dc->red_curve, 0.0625); + } + dc->red_curve->reset(); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->red_bpath), NULL); + + if (c->is_empty()) { + c->unref(); + return; + } + + // Step A - test, whether we ended on green anchor + if ( forceclosed || ( dc->green_anchor && dc->green_anchor->active ) ) { + // We hit green anchor, closing Green-Blue-Red + dc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Path is closed.")); + c->closepath_current(); + // Closed path, just flush + spdc_flush_white(dc, c); + c->unref(); + return; + } + + // Step B - both start and end anchored to same curve + if ( dc->sa && dc->ea + && ( dc->sa->curve == dc->ea->curve ) + && ( ( dc->sa != dc->ea ) + || dc->sa->curve->is_closed() ) ) + { + // We hit bot start and end of single curve, closing paths + dc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Closing path.")); + if (dc->sa->start && !(dc->sa->curve->is_closed()) ) { + c = reverse_then_unref(c); + } + dc->sa->curve->append_continuous(c, 0.0625); + c->unref(); + dc->sa->curve->closepath_current(); + spdc_flush_white(dc, NULL); + return; + } + + // Step C - test start + if (dc->sa) { + SPCurve *s = dc->sa->curve; + dc->white_curves = g_slist_remove(dc->white_curves, s); + if (dc->sa->start) { + s = reverse_then_unref(s); + } + s->append_continuous(c, 0.0625); + c->unref(); + c = s; + } else /* Step D - test end */ if (dc->ea) { + SPCurve *e = dc->ea->curve; + dc->white_curves = g_slist_remove(dc->white_curves, e); + if (!dc->ea->start) { + e = reverse_then_unref(e); + } + c->append_continuous(e, 0.0625); + e->unref(); + } + + + spdc_flush_white(dc, c); + + c->unref(); +} + +static void spdc_flush_white(FreehandBase *dc, SPCurve *gc) +{ + SPCurve *c; + + if (dc->white_curves) { + g_assert(dc->white_item); + c = SPCurve::concat(dc->white_curves); + g_slist_free(dc->white_curves); + dc->white_curves = NULL; + if (gc) { + c->append(gc, FALSE); + } + } else if (gc) { + c = gc; + c->ref(); + } else { + return; + } + + // Now we have to go back to item coordinates at last + c->transform( dc->white_item + ? (dc->white_item)->dt2i_affine() + : dc->desktop->dt2doc() ); + + SPDesktop *desktop = dc->desktop; + SPDocument *doc = sp_desktop_document(desktop); + Inkscape::XML::Document *xml_doc = doc->getReprDoc(); + + if ( c && !c->is_empty() ) { + // We actually have something to write + + bool has_lpe = false; + Inkscape::XML::Node *repr; + if (dc->white_item) { + repr = dc->white_item->getRepr(); + has_lpe = SP_LPE_ITEM(dc->white_item)->hasPathEffectRecursive(); + } else { + repr = xml_doc->createElement("svg:path"); + // Set style + sp_desktop_apply_style_tool(desktop, repr, tool_name(dc).data(), false); + } + + gchar *str = sp_svg_write_path( c->get_pathvector() ); + g_assert( str != NULL ); + if (has_lpe) + repr->setAttribute("inkscape:original-d", str); + else + repr->setAttribute("d", str); + g_free(str); + + if (!dc->white_item) { + // Attach repr + SPItem *item = SP_ITEM(desktop->currentLayer()->appendChildRepr(repr)); + + // we finished the path; now apply any waiting LPEs or freehand shapes + spdc_check_for_and_apply_waiting_LPE(dc, item, c); + + dc->selection->set(repr); + Inkscape::GC::release(repr); + item->transform = SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); + item->doWriteTransform(item->getRepr(), item->transform, NULL, true); + item->updateRepr(); + } + + DocumentUndo::done(doc, SP_IS_PEN_CONTEXT(dc)? SP_VERB_CONTEXT_PEN : SP_VERB_CONTEXT_PENCIL, + _("Draw path")); + + // When quickly drawing several subpaths with Shift, the next subpath may be finished and + // flushed before the selection_modified signal is fired by the previous change, which + // results in the tool losing all of the selected path's curve except that last subpath. To + // fix this, we force the selection_modified callback now, to make sure the tool's curve is + // in sync immediately. + spdc_selection_modified(sp_desktop_selection(desktop), 0, dc); + } + + c->unref(); + + // Flush pending updates + doc->ensureUpToDate(); +} + +SPDrawAnchor *spdc_test_inside(FreehandBase *dc, Geom::Point p) +{ + SPDrawAnchor *active = NULL; + + // Test green anchor + if (dc->green_anchor) { + active = sp_draw_anchor_test(dc->green_anchor, p, TRUE); + } + + for (GSList *l = dc->white_anchors; l != NULL; l = l->next) { + SPDrawAnchor *na = sp_draw_anchor_test(static_cast<SPDrawAnchor*>(l->data), p, !active); + if ( !active && na ) { + active = na; + } + } + + return active; +} + +static void spdc_reset_white(FreehandBase *dc) +{ + if (dc->white_item) { + // We do not hold refcount + dc->white_item = NULL; + } + while (dc->white_curves) { + reinterpret_cast<SPCurve *>(dc->white_curves->data)->unref(); + dc->white_curves = g_slist_remove(dc->white_curves, dc->white_curves->data); + } + while (dc->white_anchors) { + sp_draw_anchor_destroy(static_cast<SPDrawAnchor*>(dc->white_anchors->data)); + dc->white_anchors = g_slist_remove(dc->white_anchors, dc->white_anchors->data); + } +} + +static void spdc_free_colors(FreehandBase *dc) +{ + // Red + if (dc->red_bpath) { + sp_canvas_item_destroy(SP_CANVAS_ITEM(dc->red_bpath)); + dc->red_bpath = NULL; + } + if (dc->red_curve) { + dc->red_curve = dc->red_curve->unref(); + } + + // Blue + if (dc->blue_bpath) { + sp_canvas_item_destroy(SP_CANVAS_ITEM(dc->blue_bpath)); + dc->blue_bpath = NULL; + } + if (dc->blue_curve) { + dc->blue_curve = dc->blue_curve->unref(); + } + + // Green + while (dc->green_bpaths) { + sp_canvas_item_destroy(SP_CANVAS_ITEM(dc->green_bpaths->data)); + dc->green_bpaths = g_slist_remove(dc->green_bpaths, dc->green_bpaths->data); + } + if (dc->green_curve) { + dc->green_curve = dc->green_curve->unref(); + } + if (dc->green_anchor) { + dc->green_anchor = sp_draw_anchor_destroy(dc->green_anchor); + } + + // White + if (dc->white_item) { + // We do not hold refcount + dc->white_item = NULL; + } + while (dc->white_curves) { + reinterpret_cast<SPCurve *>(dc->white_curves->data)->unref(); + dc->white_curves = g_slist_remove(dc->white_curves, dc->white_curves->data); + } + while (dc->white_anchors) { + sp_draw_anchor_destroy(static_cast<SPDrawAnchor *>(dc->white_anchors->data)); + dc->white_anchors = g_slist_remove(dc->white_anchors, dc->white_anchors->data); + } +} + +void spdc_create_single_dot(ToolBase *ec, Geom::Point const &pt, char const *tool, guint event_state) { + g_return_if_fail(!strcmp(tool, "/tools/freehand/pen") || !strcmp(tool, "/tools/freehand/pencil")); + Glib::ustring tool_path = tool; + + SPDesktop *desktop = ec->desktop; + Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc(); + Inkscape::XML::Node *repr = xml_doc->createElement("svg:path"); + repr->setAttribute("sodipodi:type", "arc"); + SPItem *item = SP_ITEM(desktop->currentLayer()->appendChildRepr(repr)); + Inkscape::GC::release(repr); + + // apply the tool's current style + sp_desktop_apply_style_tool(desktop, repr, tool, false); + + // find out stroke width (TODO: is there an easier way??) + double stroke_width = 3.0; + gchar const *style_str = NULL; + style_str = repr->attribute("style"); + if (style_str) { + SPStyle *style = sp_style_new(SP_ACTIVE_DOCUMENT); + sp_style_merge_from_style_string(style, style_str); + stroke_width = style->stroke_width.computed; + style->stroke_width.computed = 0; + sp_style_unref(style); + } + + // unset stroke and set fill color to former stroke color + gchar * str; + str = g_strdup_printf("fill:#%06x;stroke:none;", sp_desktop_get_color_tool(desktop, tool, false) >> 8); + repr->setAttribute("style", str); + g_free(str); + + // put the circle where the mouse click occurred and set the diameter to the + // current stroke width, multiplied by the amount specified in the preferences + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + Geom::Affine const i2d (item->i2dt_affine ()); + Geom::Point pp = pt * i2d.inverse(); + double rad = 0.5 * prefs->getDouble(tool_path + "/dot-size", 3.0); + if (event_state & GDK_MOD1_MASK) { + // TODO: We vary the dot size between 0.5*rad and 1.5*rad, where rad is the dot size + // as specified in prefs. Very simple, but it might be sufficient in practice. If not, + // we need to devise something more sophisticated. + double s = g_random_double_range(-0.5, 0.5); + rad *= (1 + s); + } + if (event_state & GDK_SHIFT_MASK) { + // double the point size + rad *= 2; + } + + sp_repr_set_svg_double (repr, "sodipodi:cx", pp[Geom::X]); + sp_repr_set_svg_double (repr, "sodipodi:cy", pp[Geom::Y]); + sp_repr_set_svg_double (repr, "sodipodi:rx", rad * stroke_width); + sp_repr_set_svg_double (repr, "sodipodi:ry", rad * stroke_width); + item->updateRepr(); + + sp_desktop_selection(desktop)->set(item); + + desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating single dot")); + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_NONE, _("Create single dot")); +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/freehand-base.h b/src/ui/tools/freehand-base.h new file mode 100644 index 000000000..c8da9faed --- /dev/null +++ b/src/ui/tools/freehand-base.h @@ -0,0 +1,144 @@ +#ifndef SEEN_SP_DRAW_CONTEXT_H +#define SEEN_SP_DRAW_CONTEXT_H + +/* + * Generic drawing context + * + * Author: + * Lauris Kaplinski <lauris@kaplinski.com> + * + * Copyright (C) 2000 Lauris Kaplinski + * Copyright (C) 2000-2001 Ximian, Inc. + * Copyright (C) 2002 Lauris Kaplinski + * + * Released under GNU GPL + */ + +#include <stddef.h> +#include <sigc++/sigc++.h> +#include <2geom/point.h> +#include "ui/tools/tool-base.h" +#include "live_effects/effect.h" + +/* Freehand context */ + +#define SP_DRAW_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::FreehandBase*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_DRAW_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::FreehandBase*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +struct SPDrawAnchor; +namespace Inkscape +{ + class Selection; +} + +namespace Inkscape { +namespace UI { +namespace Tools { + +class FreehandBase : public ToolBase { +public: + FreehandBase(gchar const *const *cursor_shape, gint hot_x, gint hot_y); + virtual ~FreehandBase(); + + Inkscape::Selection *selection; + SPCanvasItem *grab; + + bool attach; + + guint32 red_color; + guint32 blue_color; + guint32 green_color; + + // Red + SPCanvasItem *red_bpath; + SPCurve *red_curve; + + // Blue + SPCanvasItem *blue_bpath; + SPCurve *blue_curve; + + // Green + GSList *green_bpaths; + SPCurve *green_curve; + SPDrawAnchor *green_anchor; + gboolean green_closed; // a flag meaning we hit the green anchor, so close the path on itself + + // White + SPItem *white_item; + GSList *white_curves; + GSList *white_anchors; + + // Start anchor + SPDrawAnchor *sa; + + // End anchor + SPDrawAnchor *ea; + + /* type of the LPE that is to be applied automatically to a finished path (if any) */ + Inkscape::LivePathEffect::EffectType waiting_LPE_type; + + sigc::connection sel_changed_connection; + sigc::connection sel_modified_connection; + + bool red_curve_is_valid; + + bool anchor_statusbar; + +protected: + virtual void setup(); + virtual void finish(); + virtual void set(const Inkscape::Preferences::Entry& val); + virtual bool root_handler(GdkEvent* event); +}; + +/** + * Returns FIRST active anchor (the activated one). + */ +SPDrawAnchor *spdc_test_inside(FreehandBase *dc, Geom::Point p); + +/** + * Concats red, blue and green. + * If any anchors are defined, process these, optionally removing curves from white list + * Invoke _flush_white to write result back to object. + */ +void spdc_concat_colors_and_flush(FreehandBase *dc, gboolean forceclosed); + +/** + * Snaps node or handle to PI/rotationsnapsperpi degree increments. + * + * @param dc draw context. + * @param p cursor point (to be changed by snapping). + * @param o origin point. + * @param state keyboard state to check if ctrl or shift was pressed. + */ +void spdc_endpoint_snap_rotation(ToolBase const *const ec, Geom::Point &p, Geom::Point const &o, guint state); + +void spdc_endpoint_snap_free(ToolBase const *ec, Geom::Point &p, boost::optional<Geom::Point> &start_of_line, guint state); + +/** + * If we have an item and a waiting LPE, apply the effect to the item + * (spiro spline mode is treated separately). + */ +void spdc_check_for_and_apply_waiting_LPE(FreehandBase *dc, SPItem *item); + +/** + * Create a single dot represented by a circle. + */ +void spdc_create_single_dot(ToolBase *ec, Geom::Point const &pt, char const *tool, guint event_state); + +} +} +} + +#endif // SEEN_SP_DRAW_CONTEXT_H + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/gradient-tool.cpp b/src/ui/tools/gradient-tool.cpp new file mode 100644 index 000000000..a0bbfbaf1 --- /dev/null +++ b/src/ui/tools/gradient-tool.cpp @@ -0,0 +1,975 @@ +/* + * Gradient drawing and editing tool + * + * Authors: + * bulia byak <buliabyak@users.sf.net> + * Johan Engelen <j.b.c.engelen@ewi.utwente.nl> + * Abhishek Sharma + * + * Copyright (C) 2007 Johan Engelen + * Copyright (C) 2005 Authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + + +#include <gdk/gdkkeysyms.h> + +#include "macros.h" +#include "document.h" +#include "selection.h" +#include "desktop.h" +#include "desktop-handles.h" +#include "message-context.h" +#include "message-stack.h" +#include "pixmaps/cursor-gradient.xpm" +#include "pixmaps/cursor-gradient-add.xpm" +#include "ui/tools/gradient-tool.h" +#include "gradient-chemistry.h" +#include <glibmm/i18n.h> +#include "preferences.h" +#include "gradient-drag.h" +#include "gradient-chemistry.h" +#include "xml/repr.h" +#include "sp-item.h" +#include "display/sp-ctrlline.h" +#include "sp-linear-gradient.h" +#include "sp-radial-gradient.h" +#include "sp-stop.h" +#include "svg/css-ostringstream.h" +#include "svg/svg-color.h" +#include "snap.h" +#include "sp-namedview.h" +#include "rubberband.h" +#include "document-undo.h" +#include "verbs.h" +#include "selection-chemistry.h" + +using Inkscape::DocumentUndo; + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +static void sp_gradient_drag(GradientTool &rc, Geom::Point const pt, guint state, guint32 etime); + +namespace { + ToolBase* createGradientContext() { + return new GradientTool(); + } + + bool gradientContextRegistered = ToolFactory::instance().registerObject("/tools/gradient", createGradientContext); +} + +const std::string& GradientTool::getPrefsPath() { + return GradientTool::prefsPath; +} + +const std::string GradientTool::prefsPath = "/tools/gradient"; + + +GradientTool::GradientTool() + : ToolBase(cursor_gradient_xpm, 4, 4) + , cursor_addnode(false) + , node_added(false) +// TODO: Why are these connections stored as pointers? + , selcon(NULL) + , subselcon(NULL) +{ + // TODO: This value is overwritten in the root handler + this->tolerance = 6; +} + +GradientTool::~GradientTool() { + this->enableGrDrag(false); + + this->selcon->disconnect(); + delete this->selcon; + + this->subselcon->disconnect(); + delete this->subselcon; +} + +const gchar *gr_handle_descr [] = { + N_("Linear gradient <b>start</b>"), //POINT_LG_BEGIN + N_("Linear gradient <b>end</b>"), + N_("Linear gradient <b>mid stop</b>"), + N_("Radial gradient <b>center</b>"), + N_("Radial gradient <b>radius</b>"), + N_("Radial gradient <b>radius</b>"), + N_("Radial gradient <b>focus</b>"), // POINT_RG_FOCUS + N_("Radial gradient <b>mid stop</b>"), + N_("Radial gradient <b>mid stop</b>") +}; + +void GradientTool::selection_changed(Inkscape::Selection*) { + GradientTool *rc = (GradientTool *) this; + + GrDrag *drag = rc->_grdrag; + Inkscape::Selection *selection = sp_desktop_selection(SP_EVENT_CONTEXT(rc)->desktop); + if (selection == NULL) { + return; + } + guint n_obj = g_slist_length((GSList *) selection->itemList()); + + if (!drag->isNonEmpty() || selection->isEmpty()) + return; + guint n_tot = drag->numDraggers(); + guint n_sel = drag->numSelected(); + + //The use of ngettext in the following code is intentional even if the English singular form would never be used + if (n_sel == 1) { + if (drag->singleSelectedDraggerNumDraggables() == 1) { + gchar * message = g_strconcat( + //TRANSLATORS: %s will be substituted with the point name (see previous messages); This is part of a compound message + _("%s selected"), + //TRANSLATORS: Mind the space in front. This is part of a compound message + ngettext(" out of %d gradient handle"," out of %d gradient handles",n_tot), + ngettext(" on %d selected object"," on %d selected objects",n_obj),NULL); + rc->message_context->setF(Inkscape::NORMAL_MESSAGE, + message,_(gr_handle_descr[drag->singleSelectedDraggerSingleDraggableType()]), n_tot, n_obj); + } else { + gchar * message = g_strconcat( + //TRANSLATORS: This is a part of a compound message (out of two more indicating: grandint handle count & object count) + ngettext("One handle merging %d stop (drag with <b>Shift</b> to separate) selected", + "One handle merging %d stops (drag with <b>Shift</b> to separate) selected",drag->singleSelectedDraggerNumDraggables()), + ngettext(" out of %d gradient handle"," out of %d gradient handles",n_tot), + ngettext(" on %d selected object"," on %d selected objects",n_obj),NULL); + rc->message_context->setF(Inkscape::NORMAL_MESSAGE,message,drag->singleSelectedDraggerNumDraggables(), n_tot, n_obj); + } + } else if (n_sel > 1) { + //TRANSLATORS: The plural refers to number of selected gradient handles. This is part of a compound message (part two indicates selected object count) + gchar * message = g_strconcat(ngettext("<b>%d</b> gradient handle selected out of %d","<b>%d</b> gradient handles selected out of %d",n_sel), + //TRANSLATORS: Mind the space in front. (Refers to gradient handles selected). This is part of a compound message + ngettext(" on %d selected object"," on %d selected objects",n_obj),NULL); + rc->message_context->setF(Inkscape::NORMAL_MESSAGE,message, n_sel, n_tot, n_obj); + } else if (n_sel == 0) { + rc->message_context->setF(Inkscape::NORMAL_MESSAGE, + //TRANSLATORS: The plural refers to number of selected objects + ngettext("<b>No</b> gradient handles selected out of %d on %d selected object", + "<b>No</b> gradient handles selected out of %d on %d selected objects",n_obj), n_tot, n_obj); + } +} + +void GradientTool::setup() { + ToolBase::setup(); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + if (prefs->getBool("/tools/gradient/selcue", true)) { + this->enableSelectionCue(); + } + + this->enableGrDrag(); + Inkscape::Selection *selection = sp_desktop_selection(this->desktop); + + this->selcon = new sigc::connection(selection->connectChanged( + sigc::mem_fun(this, &GradientTool::selection_changed) + )); + + this->subselcon = new sigc::connection(this->desktop->connectToolSubselectionChanged( + sigc::hide(sigc::bind( + sigc::mem_fun(this, &GradientTool::selection_changed), + (Inkscape::Selection*)NULL + )) + )); + + this->selection_changed(selection); +} + +void +sp_gradient_context_select_next (ToolBase *event_context) +{ + GrDrag *drag = event_context->_grdrag; + g_assert (drag); + + GrDragger *d = drag->select_next(); + + event_context->desktop->scroll_to_point(d->point, 1.0); +} + +void +sp_gradient_context_select_prev (ToolBase *event_context) +{ + GrDrag *drag = event_context->_grdrag; + g_assert (drag); + + GrDragger *d = drag->select_prev(); + + event_context->desktop->scroll_to_point(d->point, 1.0); +} + +static bool +sp_gradient_context_is_over_line (GradientTool *rc, SPItem *item, Geom::Point event_p) +{ + SPDesktop *desktop = SP_EVENT_CONTEXT (rc)->desktop; + + //Translate mouse point into proper coord system + rc->mousepoint_doc = desktop->w2d(event_p); + + SPCtrlLine* line = SP_CTRLLINE(item); + + Geom::LineSegment ls(line->s, line->e); + Geom::Point nearest = ls.pointAt(ls.nearestPoint(rc->mousepoint_doc)); + double dist_screen = Geom::L2 (rc->mousepoint_doc - nearest) * desktop->current_zoom(); + + double tolerance = (double) SP_EVENT_CONTEXT(rc)->tolerance; + + bool close = (dist_screen < tolerance); + + return close; +} + +static std::vector<Geom::Point> +sp_gradient_context_get_stop_intervals (GrDrag *drag, GSList **these_stops, GSList **next_stops) +{ + std::vector<Geom::Point> coords; + + // for all selected draggers + for (GList *i = drag->selected; i != NULL; i = i->next) { + GrDragger *dragger = (GrDragger *) i->data; + // remember the coord of the dragger to reselect it later + coords.push_back(dragger->point); + // for all draggables of dragger + for (GSList const* j = dragger->draggables; j != NULL; j = j->next) { + GrDraggable *d = (GrDraggable *) j->data; + + // find the gradient + SPGradient *gradient = getGradient(d->item, d->fill_or_stroke); + SPGradient *vector = sp_gradient_get_forked_vector_if_necessary (gradient, false); + + // these draggable types cannot have a next draggabe to insert a stop between them + if (d->point_type == POINT_LG_END || + d->point_type == POINT_RG_FOCUS || + d->point_type == POINT_RG_R1 || + d->point_type == POINT_RG_R2) { + continue; + } + + // from draggables to stops + SPStop *this_stop = sp_get_stop_i (vector, d->point_i); + SPStop *next_stop = this_stop->getNextStop(); + SPStop *last_stop = sp_last_stop (vector); + + Inkscape::PaintTarget fs = d->fill_or_stroke; + SPItem *item = d->item; + gint type = d->point_type; + gint p_i = d->point_i; + + // if there's a next stop, + if (next_stop) { + GrDragger *dnext = NULL; + // find its dragger + // (complex because it may have different types, and because in radial, + // more than one dragger may correspond to a stop, so we must distinguish) + if (type == POINT_LG_BEGIN || type == POINT_LG_MID) { + if (next_stop == last_stop) { + dnext = drag->getDraggerFor(item, POINT_LG_END, p_i+1, fs); + } else { + dnext = drag->getDraggerFor(item, POINT_LG_MID, p_i+1, fs); + } + } else { // radial + if (type == POINT_RG_CENTER || type == POINT_RG_MID1) { + if (next_stop == last_stop) { + dnext = drag->getDraggerFor(item, POINT_RG_R1, p_i+1, fs); + } else { + dnext = drag->getDraggerFor(item, POINT_RG_MID1, p_i+1, fs); + } + } + if ((type == POINT_RG_MID2) || + (type == POINT_RG_CENTER && dnext && !dnext->isSelected())) { + if (next_stop == last_stop) { + dnext = drag->getDraggerFor(item, POINT_RG_R2, p_i+1, fs); + } else { + dnext = drag->getDraggerFor(item, POINT_RG_MID2, p_i+1, fs); + } + } + } + + // if both adjacent draggers selected, + if (!g_slist_find(*these_stops, this_stop) && dnext && dnext->isSelected()) { + + // remember the coords of the future dragger to select it + coords.push_back(0.5*(dragger->point + dnext->point)); + + // do not insert a stop now, it will confuse the loop; + // just remember the stops + *these_stops = g_slist_prepend (*these_stops, this_stop); + *next_stops = g_slist_prepend (*next_stops, next_stop); + } + } + } + } + return coords; +} + +void +sp_gradient_context_add_stops_between_selected_stops (GradientTool *rc) +{ + SPDocument *doc = NULL; + GrDrag *drag = rc->_grdrag; + + GSList *these_stops = NULL; + GSList *next_stops = NULL; + + std::vector<Geom::Point> coords = sp_gradient_context_get_stop_intervals (drag, &these_stops, &next_stops); + + if (g_slist_length(these_stops) == 0 && drag->numSelected() == 1) { + // if a single stop is selected, add between that stop and the next one + GrDragger *dragger = (GrDragger *) drag->selected->data; + for (GSList const* j = dragger->draggables; j != NULL; j = j->next) { + GrDraggable *d = (GrDraggable *) j->data; + if (d->point_type == POINT_RG_FOCUS) { + /* + * There are 2 draggables at the center (start) of a radial gradient + * To avoid creating 2 seperate stops, ignore this draggable point type + */ + continue; + } + SPGradient *gradient = getGradient(d->item, d->fill_or_stroke); + SPGradient *vector = sp_gradient_get_forked_vector_if_necessary (gradient, false); + SPStop *this_stop = sp_get_stop_i (vector, d->point_i); + if (this_stop) { + SPStop *next_stop = this_stop->getNextStop(); + if (next_stop) { + these_stops = g_slist_prepend (these_stops, this_stop); + next_stops = g_slist_prepend (next_stops, next_stop); + } + } + } + } + + // now actually create the new stops + GSList *i = these_stops; + GSList *j = next_stops; + GSList *new_stops = NULL; + + for (; i != NULL && j != NULL; i = i->next, j = j->next) { + SPStop *this_stop = (SPStop *) i->data; + SPStop *next_stop = (SPStop *) j->data; + gfloat offset = 0.5*(this_stop->offset + next_stop->offset); + SPObject *parent = this_stop->parent; + if (SP_IS_GRADIENT (parent)) { + doc = parent->document; + SPStop *new_stop = sp_vector_add_stop (SP_GRADIENT (parent), this_stop, next_stop, offset); + new_stops = g_slist_prepend (new_stops, new_stop); + SP_GRADIENT(parent)->ensureVector(); + } + } + + if (g_slist_length(these_stops) > 0 && doc) { + DocumentUndo::done(doc, SP_VERB_CONTEXT_GRADIENT, _("Add gradient stop")); + drag->updateDraggers(); + // so that it does not automatically update draggers in idle loop, as this would deselect + drag->local_change = true; + + // select the newly created stops + for (GSList *s = new_stops; s != NULL; s = s->next) { + drag->selectByStop((SPStop *)s->data); + } + + } + + g_slist_free (these_stops); + g_slist_free (next_stops); + g_slist_free (new_stops); +} + +static double sqr(double x) {return x*x;} + +static void +sp_gradient_simplify(GradientTool *rc, double tolerance) +{ + SPDocument *doc = NULL; + GrDrag *drag = rc->_grdrag; + + GSList *these_stops = NULL; + GSList *next_stops = NULL; + + std::vector<Geom::Point> coords = sp_gradient_context_get_stop_intervals (drag, &these_stops, &next_stops); + + GSList *todel = NULL; + + GSList *i = these_stops; + GSList *j = next_stops; + for (; i != NULL && j != NULL; i = i->next, j = j->next) { + SPStop *stop0 = (SPStop *) i->data; + SPStop *stop1 = (SPStop *) j->data; + + gint i1 = g_slist_index(these_stops, stop1); + if (i1 != -1) { + GSList *next_next = g_slist_nth (next_stops, i1); + if (next_next) { + SPStop *stop2 = (SPStop *) next_next->data; + + if (g_slist_find(todel, stop0) || g_slist_find(todel, stop2)) + continue; + + guint32 const c0 = stop0->get_rgba32(); + guint32 const c2 = stop2->get_rgba32(); + guint32 const c1r = stop1->get_rgba32(); + guint32 c1 = average_color (c0, c2, + (stop1->offset - stop0->offset) / (stop2->offset - stop0->offset)); + + double diff = + sqr(SP_RGBA32_R_F(c1) - SP_RGBA32_R_F(c1r)) + + sqr(SP_RGBA32_G_F(c1) - SP_RGBA32_G_F(c1r)) + + sqr(SP_RGBA32_B_F(c1) - SP_RGBA32_B_F(c1r)) + + sqr(SP_RGBA32_A_F(c1) - SP_RGBA32_A_F(c1r)); + + if (diff < tolerance) + todel = g_slist_prepend (todel, stop1); + } + } + } + + for (i = todel; i != NULL; i = i->next) { + SPStop *stop = (SPStop*) i->data; + doc = stop->document; + Inkscape::XML::Node * parent = stop->getRepr()->parent(); + parent->removeChild( stop->getRepr() ); + } + + if (g_slist_length(todel) > 0) { + DocumentUndo::done(doc, SP_VERB_CONTEXT_GRADIENT, _("Simplify gradient")); + drag->local_change = true; + drag->updateDraggers(); + drag->selectByCoords(coords); + } + + g_slist_free (todel); + g_slist_free (these_stops); + g_slist_free (next_stops); +} + + +static void +sp_gradient_context_add_stop_near_point (GradientTool *rc, SPItem *item, Geom::Point mouse_p, guint32 /*etime*/) +{ + // item is the selected item. mouse_p the location in doc coordinates of where to add the stop + + ToolBase *ec = SP_EVENT_CONTEXT(rc); + SPDesktop *desktop = SP_EVENT_CONTEXT (rc)->desktop; + + double tolerance = (double) ec->tolerance; + + SPStop *newstop = ec->get_drag()->addStopNearPoint (item, mouse_p, tolerance/desktop->current_zoom()); + + DocumentUndo::done(sp_desktop_document (desktop), SP_VERB_CONTEXT_GRADIENT, + _("Add gradient stop")); + + ec->get_drag()->updateDraggers(); + ec->get_drag()->local_change = true; + ec->get_drag()->selectByStop(newstop); +} + +bool GradientTool::root_handler(GdkEvent* event) { + static bool dragging; + + Inkscape::Selection *selection = sp_desktop_selection (desktop); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + this->tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + double const nudge = prefs->getDoubleLimited("/options/nudgedistance/value", 2, 0, 1000, "px"); // in px + + GrDrag *drag = this->_grdrag; + g_assert (drag); + + gint ret = FALSE; + + switch (event->type) { + case GDK_2BUTTON_PRESS: + if ( event->button.button == 1 ) { + bool over_line = false; + SPCtrlLine *line = NULL; + + if (drag->lines) { + for (GSList *l = drag->lines; (l != NULL) && (!over_line); l = l->next) { + line = (SPCtrlLine*) l->data; + over_line |= sp_gradient_context_is_over_line (this, (SPItem*) line, Geom::Point(event->motion.x, event->motion.y)); + } + } + + if (over_line) { + // we take the first item in selection, because with doubleclick, the first click + // always resets selection to the single object under cursor + sp_gradient_context_add_stop_near_point(this, SP_ITEM(selection->itemList()->data), this->mousepoint_doc, event->button.time); + } else { + for (GSList const* i = selection->itemList(); i != NULL; i = i->next) { + SPItem *item = SP_ITEM(i->data); + SPGradientType new_type = (SPGradientType) prefs->getInt("/tools/gradient/newgradient", SP_GRADIENT_TYPE_LINEAR); + Inkscape::PaintTarget fsmode = (prefs->getInt("/tools/gradient/newfillorstroke", 1) != 0) ? Inkscape::FOR_FILL : Inkscape::FOR_STROKE; + + SPGradient *vector = sp_gradient_vector_for_object(sp_desktop_document(desktop), desktop, item, fsmode); + + SPGradient *priv = sp_item_set_gradient(item, vector, new_type, fsmode); + sp_gradient_reset_to_userspace(priv, item); + } + + DocumentUndo::done(sp_desktop_document (desktop), SP_VERB_CONTEXT_GRADIENT, + _("Create default gradient")); + } + ret = TRUE; + } + break; + + case GDK_BUTTON_PRESS: + if ( event->button.button == 1 && !this->space_panning ) { + Geom::Point button_w(event->button.x, event->button.y); + + // save drag origin + this->xp = (gint) button_w[Geom::X]; + this->yp = (gint) button_w[Geom::Y]; + this->within_tolerance = true; + + dragging = true; + + Geom::Point button_dt = desktop->w2d(button_w); + if (event->button.state & GDK_SHIFT_MASK) { + Inkscape::Rubberband::get(desktop)->start(desktop, button_dt); + } else { + // remember clicked item, disregarding groups, honoring Alt; do nothing with Crtl to + // enable Ctrl+doubleclick of exactly the selected item(s) + if (!(event->button.state & GDK_CONTROL_MASK)) { + this->item_to_select = sp_event_context_find_item (desktop, button_w, event->button.state & GDK_MOD1_MASK, TRUE); + } + + if (!selection->isEmpty()) { + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + m.freeSnapReturnByRef(button_dt, Inkscape::SNAPSOURCE_NODE_HANDLE); + m.unSetup(); + } + + this->origin = button_dt; + } + + ret = TRUE; + } + break; + + case GDK_MOTION_NOTIFY: + if (dragging && ( event->motion.state & GDK_BUTTON1_MASK ) && !this->space_panning) { + if ( this->within_tolerance + && ( abs( (gint) event->motion.x - this->xp ) < this->tolerance ) + && ( abs( (gint) event->motion.y - this->yp ) < this->tolerance ) ) { + break; // do not drag if we're within tolerance from origin + } + // Once the user has moved farther than tolerance from the original location + // (indicating they intend to draw, not click), then always process the + // motion notify coordinates as given (no snapping back to origin) + this->within_tolerance = false; + + Geom::Point const motion_w(event->motion.x, + event->motion.y); + Geom::Point const motion_dt = this->desktop->w2d(motion_w); + + if (Inkscape::Rubberband::get(desktop)->is_started()) { + Inkscape::Rubberband::get(desktop)->move(motion_dt); + this->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Draw around</b> handles to select them")); + } else { + sp_gradient_drag(*this, motion_dt, event->motion.state, event->motion.time); + } + + gobble_motion_events(GDK_BUTTON1_MASK); + + ret = TRUE; + } else { + if (!drag->mouseOver() && !selection->isEmpty()) { + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point const motion_dt = this->desktop->w2d(motion_w); + + m.preSnap(Inkscape::SnapCandidatePoint(motion_dt, Inkscape::SNAPSOURCE_OTHER_HANDLE)); + m.unSetup(); + } + + bool over_line = false; + + if (drag->lines) { + for (GSList *l = drag->lines; l != NULL; l = l->next) { + over_line |= sp_gradient_context_is_over_line (this, (SPItem*) l->data, Geom::Point(event->motion.x, event->motion.y)); + } + } + + if (this->cursor_addnode && !over_line) { + this->cursor_shape = cursor_gradient_xpm; + this->sp_event_context_update_cursor(); + this->cursor_addnode = false; + } else if (!this->cursor_addnode && over_line) { + this->cursor_shape = cursor_gradient_add_xpm; + this->sp_event_context_update_cursor(); + this->cursor_addnode = true; + } + } + break; + + case GDK_BUTTON_RELEASE: + this->xp = this->yp = 0; + + if ( event->button.button == 1 && !this->space_panning ) { + bool over_line = false; + SPCtrlLine *line = NULL; + + if (drag->lines) { + for (GSList *l = drag->lines; (l != NULL) && (!over_line); l = l->next) { + line = (SPCtrlLine*) l->data; + over_line = sp_gradient_context_is_over_line (this, (SPItem*) line, Geom::Point(event->motion.x, event->motion.y)); + if (over_line) + break; + } + } + + if ( (event->button.state & GDK_CONTROL_MASK) && (event->button.state & GDK_MOD1_MASK ) ) { + if (over_line && line) { + sp_gradient_context_add_stop_near_point(this, line->item, this->mousepoint_doc, 0); + ret = TRUE; + } + } else { + dragging = false; + + // unless clicked with Ctrl (to enable Ctrl+doubleclick). + if (event->button.state & GDK_CONTROL_MASK) { + ret = TRUE; + break; + } + + if (!this->within_tolerance) { + // we've been dragging, either do nothing (grdrag handles that), + // or rubberband-select if we have rubberband + Inkscape::Rubberband *r = Inkscape::Rubberband::get(desktop); + + if (r->is_started() && !this->within_tolerance) { + // this was a rubberband drag + if (r->getMode() == RUBBERBAND_MODE_RECT) { + Geom::OptRect const b = r->getRectangle(); + drag->selectRect(*b); + } + } + } else if (this->item_to_select) { + if (over_line && line) { + // Clicked on an existing gradient line, dont change selection. This stops + // possible change in selection during a double click with overlapping objects + } else { + // no dragging, select clicked item if any + if (event->button.state & GDK_SHIFT_MASK) { + selection->toggle(this->item_to_select); + } else { + drag->deselectAll(); + selection->set(this->item_to_select); + } + } + } else { + // click in an empty space; do the same as Esc + if (drag->selected) { + drag->deselectAll(); + } else { + selection->clear(); + } + } + + this->item_to_select = NULL; + ret = TRUE; + } + + Inkscape::Rubberband::get(desktop)->stop(); + } + break; + + case GDK_KEY_PRESS: + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + case GDK_KEY_Meta_L: // Meta is when you press Shift+Alt (at least on my machine) + case GDK_KEY_Meta_R: + sp_event_show_modifier_tip (this->defaultMessageContext(), event, + _("<b>Ctrl</b>: snap gradient angle"), + _("<b>Shift</b>: draw gradient around the starting point"), + NULL); + break; + + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo ("altx-grad"); + ret = TRUE; + } + break; + + case GDK_KEY_A: + case GDK_KEY_a: + if (MOD__CTRL_ONLY(event) && drag->isNonEmpty()) { + drag->selectAll(); + ret = TRUE; + } + break; + + case GDK_KEY_L: + case GDK_KEY_l: + if (MOD__CTRL_ONLY(event) && drag->isNonEmpty() && drag->hasSelection()) { + sp_gradient_simplify(this, 1e-4); + ret = TRUE; + } + break; + + case GDK_KEY_Escape: + if (drag->selected) { + drag->deselectAll(); + } else { + Inkscape::SelectionHelper::selectNone(desktop); + } + ret = TRUE; + //TODO: make dragging escapable by Esc + break; + + case GDK_KEY_Left: // move handle left + case GDK_KEY_KP_Left: + case GDK_KEY_KP_4: + if (!MOD__CTRL(event)) { // not ctrl + gint mul = 1 + gobble_key_events( + get_group0_keyval(&event->key), 0); // with any mask + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) { + drag->selected_move_screen(mul*-10, 0); // shift + } else { + drag->selected_move_screen(mul*-1, 0); // no shift + } + } else { // no alt + if (MOD__SHIFT(event)) { + drag->selected_move(mul*-10*nudge, 0); // shift + } else { + drag->selected_move(mul*-nudge, 0); // no shift + } + } + ret = TRUE; + } + break; + + case GDK_KEY_Up: // move handle up + case GDK_KEY_KP_Up: + case GDK_KEY_KP_8: + if (!MOD__CTRL(event)) { // not ctrl + gint mul = 1 + gobble_key_events( + get_group0_keyval(&event->key), 0); // with any mask + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) { + drag->selected_move_screen(0, mul*10); // shift + } else { + drag->selected_move_screen(0, mul*1); // no shift + } + } else { // no alt + if (MOD__SHIFT(event)) { + drag->selected_move(0, mul*10*nudge); // shift + } else { + drag->selected_move(0, mul*nudge); // no shift + } + } + + ret = TRUE; + } + break; + + case GDK_KEY_Right: // move handle right + case GDK_KEY_KP_Right: + case GDK_KEY_KP_6: + if (!MOD__CTRL(event)) { // not ctrl + gint mul = 1 + gobble_key_events( + get_group0_keyval(&event->key), 0); // with any mask + + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) { + drag->selected_move_screen(mul*10, 0); // shift + } else { + drag->selected_move_screen(mul*1, 0); // no shift + } + } else { // no alt + if (MOD__SHIFT(event)) { + drag->selected_move(mul*10*nudge, 0); // shift + } else { + drag->selected_move(mul*nudge, 0); // no shift + } + } + + ret = TRUE; + } + break; + + case GDK_KEY_Down: // move handle down + case GDK_KEY_KP_Down: + case GDK_KEY_KP_2: + if (!MOD__CTRL(event)) { // not ctrl + gint mul = 1 + gobble_key_events( + get_group0_keyval(&event->key), 0); // with any mask + + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) { + drag->selected_move_screen(0, mul*-10); // shift + } else { + drag->selected_move_screen(0, mul*-1); // no shift + } + } else { // no alt + if (MOD__SHIFT(event)) { + drag->selected_move(0, mul*-10*nudge); // shift + } else { + drag->selected_move(0, mul*-nudge); // no shift + } + } + + ret = TRUE; + } + break; + + case GDK_KEY_r: + case GDK_KEY_R: + if (MOD__SHIFT_ONLY(event)) { + sp_gradient_reverse_selected_gradients(desktop); + ret = TRUE; + } + break; + + case GDK_KEY_Insert: + case GDK_KEY_KP_Insert: + // with any modifiers: + sp_gradient_context_add_stops_between_selected_stops (this); + ret = TRUE; + break; + + case GDK_KEY_Delete: + case GDK_KEY_KP_Delete: + case GDK_KEY_BackSpace: + ret = this->deleteSelectedDrag(MOD__CTRL_ONLY(event)); + break; + + default: + break; + } + break; + + case GDK_KEY_RELEASE: + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + case GDK_KEY_Meta_L: // Meta is when you press Shift+Alt + case GDK_KEY_Meta_R: + this->defaultMessageContext()->clear(); + break; + + default: + break; + } + break; + + default: + break; + } + + if (!ret) { + ret = ToolBase::root_handler(event); + } + + return ret; +} + +static void sp_gradient_drag(GradientTool &rc, Geom::Point const pt, guint /*state*/, guint32 etime) +{ + SPDesktop *desktop = SP_EVENT_CONTEXT(&rc)->desktop; + Inkscape::Selection *selection = sp_desktop_selection(desktop); + SPDocument *document = sp_desktop_document(desktop); + ToolBase *ec = SP_EVENT_CONTEXT(&rc); + + if (!selection->isEmpty()) { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int type = prefs->getInt("/tools/gradient/newgradient", 1); + Inkscape::PaintTarget fill_or_stroke = (prefs->getInt("/tools/gradient/newfillorstroke", 1) != 0) ? Inkscape::FOR_FILL : Inkscape::FOR_STROKE; + + SPGradient *vector; + if (ec->item_to_select) { + // pick color from the object where drag started + vector = sp_gradient_vector_for_object(document, desktop, ec->item_to_select, fill_or_stroke); + } else { + // Starting from empty space: + // Sort items so that the topmost comes last + GSList *items = g_slist_copy ((GSList *) selection->itemList()); + items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position); + // take topmost + vector = sp_gradient_vector_for_object(document, desktop, SP_ITEM(g_slist_last(items)->data), fill_or_stroke); + g_slist_free (items); + } + + // HACK: reset fill-opacity - that 0.75 is annoying; BUT remove this when we have an opacity slider for all tabs + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_set_property(css, "fill-opacity", "1.0"); + + for (GSList const *i = selection->itemList(); i != NULL; i = i->next) { + + //FIXME: see above + sp_repr_css_change_recursive(SP_OBJECT(i->data)->getRepr(), css, "style"); + + sp_item_set_gradient(SP_ITEM(i->data), vector, (SPGradientType) type, fill_or_stroke); + + if (type == SP_GRADIENT_TYPE_LINEAR) { + sp_item_gradient_set_coords (SP_ITEM(i->data), POINT_LG_BEGIN, 0, rc.origin, fill_or_stroke, true, false); + sp_item_gradient_set_coords (SP_ITEM(i->data), POINT_LG_END, 0, pt, fill_or_stroke, true, false); + } else if (type == SP_GRADIENT_TYPE_RADIAL) { + sp_item_gradient_set_coords (SP_ITEM(i->data), POINT_RG_CENTER, 0, rc.origin, fill_or_stroke, true, false); + sp_item_gradient_set_coords (SP_ITEM(i->data), POINT_RG_R1, 0, pt, fill_or_stroke, true, false); + } + SP_OBJECT(i->data)->requestModified(SP_OBJECT_MODIFIED_FLAG); + } + if (ec->_grdrag) { + ec->_grdrag->updateDraggers(); + // prevent regenerating draggers by selection modified signal, which sometimes + // comes too late and thus destroys the knot which we will now grab: + ec->_grdrag->local_change = true; + // give the grab out-of-bounds values of xp/yp because we're already dragging + // and therefore are already out of tolerance + ec->_grdrag->grabKnot (SP_ITEM(selection->itemList()->data), + type == SP_GRADIENT_TYPE_LINEAR? POINT_LG_END : POINT_RG_R1, + -1, // ignore number (though it is always 1) + fill_or_stroke, 99999, 99999, etime); + } + // We did an undoable action, but SPDocumentUndo::done will be called by the knot when released + + // status text; we do not track coords because this branch is run once, not all the time + // during drag + int n_objects = g_slist_length((GSList *) selection->itemList()); + rc.message_context->setF(Inkscape::NORMAL_MESSAGE, + ngettext("<b>Gradient</b> for %d object; with <b>Ctrl</b> to snap angle", + "<b>Gradient</b> for %d objects; with <b>Ctrl</b> to snap angle", n_objects), + n_objects); + } else { + sp_desktop_message_stack(desktop)->flash(Inkscape::WARNING_MESSAGE, _("Select <b>objects</b> on which to create gradient.")); + } +} + +} +} +} + + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/gradient-tool.h b/src/ui/tools/gradient-tool.h new file mode 100644 index 000000000..6fe3bca9f --- /dev/null +++ b/src/ui/tools/gradient-tool.h @@ -0,0 +1,76 @@ +#ifndef __SP_GRADIENT_CONTEXT_H__ +#define __SP_GRADIENT_CONTEXT_H__ + +/* + * Gradient drawing and editing tool + * + * Authors: + * bulia byak <buliabyak@users.sf.net> + * Johan Engelen <j.b.c.engelen@ewi.utwente.nl> + * Jon A. Cruz <jon@joncruz.org. + * + * Copyright (C) 2007 Johan Engelen + * Copyright (C) 2005,2010 Authors + * + * Released under GNU GPL + */ + +#include <stddef.h> +#include <sigc++/sigc++.h> +#include "ui/tools/tool-base.h" + +#define SP_GRADIENT_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::GradientTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_GRADIENT_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::GradientTool*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +namespace Inkscape { +namespace UI { +namespace Tools { + +class GradientTool : public ToolBase { +public: + GradientTool(); + virtual ~GradientTool(); + + Geom::Point origin; + + bool cursor_addnode; + + bool node_added; + + Geom::Point mousepoint_doc; // stores mousepoint when over_line in doc coords + + sigc::connection *selcon; + sigc::connection *subselcon; + + static const std::string prefsPath; + + virtual void setup(); + virtual bool root_handler(GdkEvent* event); + + virtual const std::string& getPrefsPath(); + +private: + void selection_changed(Inkscape::Selection*); +}; + +void sp_gradient_context_select_next (ToolBase *event_context); +void sp_gradient_context_select_prev (ToolBase *event_context); +void sp_gradient_context_add_stops_between_selected_stops (GradientTool *rc); + +} +} +} + +#endif + + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/lpe-tool.cpp b/src/ui/tools/lpe-tool.cpp new file mode 100644 index 000000000..9ab6d7814 --- /dev/null +++ b/src/ui/tools/lpe-tool.cpp @@ -0,0 +1,501 @@ +/* + * LPEToolContext: a context for a generic tool composed of subtools that are given by LPEs + * + * Authors: + * Maximilian Albert <maximilian.albert@gmail.com> + * Lauris Kaplinski <lauris@kaplinski.com> + * Abhishek Sharma + * + * Copyright (C) 1998 The Free Software Foundation + * Copyright (C) 1999-2005 authors + * Copyright (C) 2001-2002 Ximian, Inc. + * Copyright (C) 2008 Maximilian Albert + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include <2geom/sbasis-geometric.h> +#include <gdk/gdkkeysyms.h> + +#include <glibmm/i18n.h> +#include "macros.h" +#include "pixmaps/cursor-crosshairs.xpm" +#include <gtk/gtk.h> +#include "desktop.h" +#include "message-context.h" +#include "preferences.h" +#include "shape-editor.h" +#include "selection.h" +#include "desktop-handles.h" +#include "document.h" +#include "display/curve.h" +#include "display/canvas-bpath.h" +#include "display/canvas-text.h" +#include "message-stack.h" +#include "sp-path.h" +#include "util/units.h" + +#include "ui/tools/lpe-tool.h" + +using Inkscape::Util::unit_table; +using Inkscape::UI::Tools::PenTool; + +const int num_subtools = 8; + +SubtoolEntry lpesubtools[] = { + // this must be here to account for the "all inactive" action + {Inkscape::LivePathEffect::INVALID_LPE, "draw-geometry-inactive"}, + {Inkscape::LivePathEffect::LINE_SEGMENT, "draw-geometry-line-segment"}, + {Inkscape::LivePathEffect::CIRCLE_3PTS, "draw-geometry-circle-from-three-points"}, + {Inkscape::LivePathEffect::CIRCLE_WITH_RADIUS, "draw-geometry-circle-from-radius"}, + {Inkscape::LivePathEffect::PARALLEL, "draw-geometry-line-parallel"}, + {Inkscape::LivePathEffect::PERP_BISECTOR, "draw-geometry-line-perpendicular"}, + {Inkscape::LivePathEffect::ANGLE_BISECTOR, "draw-geometry-angle-bisector"}, + {Inkscape::LivePathEffect::MIRROR_SYMMETRY, "draw-geometry-mirror"} +}; + + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +void sp_lpetool_context_selection_changed(Inkscape::Selection *selection, gpointer data); + +namespace { + ToolBase* createLPEToolContext() { + return new LpeTool(); + } + + bool lpetoolContextRegistered = ToolFactory::instance().registerObject("/tools/lpetool", createLPEToolContext); +} + +const std::string& LpeTool::getPrefsPath() { + return LpeTool::prefsPath; +} + +const std::string LpeTool::prefsPath = "/tools/lpetool"; + +LpeTool::LpeTool() + : PenTool(cursor_crosshairs_xpm, 7, 7) + , shape_editor(NULL) + , canvas_bbox(NULL) + , mode(Inkscape::LivePathEffect::BEND_PATH) +// TODO: pointer? + , measuring_items(new std::map<SPPath *, SPCanvasItem*>) +{ +} + +LpeTool::~LpeTool() { + delete this->shape_editor; + this->shape_editor = NULL; + + if (this->canvas_bbox) { + sp_canvas_item_destroy(SP_CANVAS_ITEM(this->canvas_bbox)); + this->canvas_bbox = NULL; + } + + lpetool_delete_measuring_items(this); + delete this->measuring_items; + this->measuring_items = NULL; + + this->sel_changed_connection.disconnect(); +} + +void LpeTool::setup() { + PenTool::setup(); + + Inkscape::Selection *selection = sp_desktop_selection (this->desktop); + SPItem *item = selection->singleItem(); + + this->sel_changed_connection.disconnect(); + this->sel_changed_connection = + selection->connectChanged(sigc::bind(sigc::ptr_fun(&sp_lpetool_context_selection_changed), (gpointer)this)); + + this->shape_editor = new ShapeEditor(this->desktop); + + lpetool_context_switch_mode(this, Inkscape::LivePathEffect::INVALID_LPE); + lpetool_context_reset_limiting_bbox(this); + lpetool_create_measuring_items(this); + +// TODO temp force: + this->enableSelectionCue(); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + if (item) { + this->shape_editor->set_item(item, SH_NODEPATH); + this->shape_editor->set_item(item, SH_KNOTHOLDER); + } + + if (prefs->getBool("/tools/lpetool/selcue")) { + this->enableSelectionCue(); + } +} + +/** + * Callback that processes the "changed" signal on the selection; + * destroys old and creates new nodepath and reassigns listeners to the new selected item's repr. + */ +void sp_lpetool_context_selection_changed(Inkscape::Selection *selection, gpointer data) +{ + LpeTool *lc = SP_LPETOOL_CONTEXT(data); + + lc->shape_editor->unset_item(SH_KNOTHOLDER); + SPItem *item = selection->singleItem(); + lc->shape_editor->set_item(item, SH_KNOTHOLDER); +} + +void LpeTool::set(const Inkscape::Preferences::Entry& val) { + if (val.getEntryName() == "mode") { + Inkscape::Preferences::get()->setString("/tools/geometric/mode", "drag"); + SP_PEN_CONTEXT(this)->mode = PenTool::MODE_DRAG; + } +} + +bool LpeTool::item_handler(SPItem* item, GdkEvent* event) { + gint ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + { + // select the clicked item but do nothing else + Inkscape::Selection * const selection = sp_desktop_selection(this->desktop); + selection->clear(); + selection->add(item); + ret = TRUE; + break; + } + case GDK_BUTTON_RELEASE: + // TODO: do we need to catch this or can we pass it on to the parent handler? + ret = TRUE; + break; + default: + break; + } + + if (!ret) { + ret = PenTool::item_handler(item, event); + } + + return ret; +} + +bool LpeTool::root_handler(GdkEvent* event) { + Inkscape::Selection *selection = sp_desktop_selection (desktop); + + bool ret = false; + + if (this->hasWaitingLPE()) { + // quit when we are waiting for a LPE to be applied + //ret = ((ToolBaseClass *) sp_lpetool_context_parent_class)->root_handler(event_context, event); + return PenTool::root_handler(event); + } + + switch (event->type) { + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + if (this->mode == Inkscape::LivePathEffect::INVALID_LPE) { + // don't do anything for now if we are inactive (except clearing the selection + // since this was a click into empty space) + selection->clear(); + desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Choose a construction tool from the toolbar.")); + ret = true; + break; + } + + // save drag origin + this->xp = (gint) event->button.x; + this->yp = (gint) event->button.y; + this->within_tolerance = true; + + using namespace Inkscape::LivePathEffect; + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int mode = prefs->getInt("/tools/lpetool/mode"); + EffectType type = lpesubtools[mode].type; + + //bool over_stroke = lc->shape_editor->is_over_stroke(Geom::Point(event->button.x, event->button.y), true); + + this->waitForLPEMouseClicks(type, Inkscape::LivePathEffect::Effect::acceptsNumClicks(type)); + + // we pass the mouse click on to pen tool as the first click which it should collect + //ret = ((ToolBaseClass *) sp_lpetool_context_parent_class)->root_handler(event_context, event); + ret = PenTool::root_handler(event); + } + break; + + + case GDK_BUTTON_RELEASE: + { + /** + break; + **/ + } + + case GDK_KEY_PRESS: + /** + switch (get_group0_keyval (&event->key)) { + } + break; + **/ + + case GDK_KEY_RELEASE: + /** + switch (get_group0_keyval(&event->key)) { + case GDK_Control_L: + case GDK_Control_R: + dc->_message_context->clear(); + break; + default: + break; + } + **/ + + default: + break; + } + + if (!ret) { + ret = PenTool::root_handler(event); + } + + return ret; +} + +/* + * Finds the index in the list of geometric subtools corresponding to the given LPE type. + * Returns -1 if no subtool is found. + */ +int +lpetool_mode_to_index(Inkscape::LivePathEffect::EffectType const type) { + for (int i = 0; i < num_subtools; ++i) { + if (lpesubtools[i].type == type) { + return i; + } + } + return -1; +} + +/* + * Checks whether an item has a construction applied as LPE and if so returns the index in + * lpesubtools of this construction + */ +int lpetool_item_has_construction(LpeTool */*lc*/, SPItem *item) +{ + if (!SP_IS_LPE_ITEM(item)) { + return -1; + } + + Inkscape::LivePathEffect::Effect* lpe = SP_LPE_ITEM(item)->getCurrentLPE(); + if (!lpe) { + return -1; + } + return lpetool_mode_to_index(lpe->effectType()); +} + +/* + * Attempts to perform the construction of the given type (i.e., to apply the corresponding LPE) to + * a single selected item. Returns whether we succeeded. + */ +bool +lpetool_try_construction(LpeTool *lc, Inkscape::LivePathEffect::EffectType const type) +{ + Inkscape::Selection *selection = sp_desktop_selection(lc->desktop); + SPItem *item = selection->singleItem(); + + // TODO: should we check whether type represents a valid geometric construction? + if (item && SP_IS_LPE_ITEM(item) && Inkscape::LivePathEffect::Effect::acceptsNumClicks(type) == 0) { + Inkscape::LivePathEffect::Effect::createAndApply(type, sp_desktop_document(lc->desktop), item); + return true; + } + return false; +} + +void +lpetool_context_switch_mode(LpeTool *lc, Inkscape::LivePathEffect::EffectType const type) +{ + int index = lpetool_mode_to_index(type); + if (index != -1) { + lc->mode = type; + lc->desktop->setToolboxSelectOneValue ("lpetool_mode_action", index); + } else { + g_warning ("Invalid mode selected: %d", type); + return; + } +} + +void +lpetool_get_limiting_bbox_corners(SPDocument *document, Geom::Point &A, Geom::Point &B) { + Geom::Coord w = document->getWidth().value("px"); + Geom::Coord h = document->getHeight().value("px"); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + double ulx = prefs->getDouble("/tools/lpetool/bbox_upperleftx", 0); + double uly = prefs->getDouble("/tools/lpetool/bbox_upperlefty", 0); + double lrx = prefs->getDouble("/tools/lpetool/bbox_lowerrightx", w); + double lry = prefs->getDouble("/tools/lpetool/bbox_lowerrighty", h); + + A = Geom::Point(ulx, uly); + B = Geom::Point(lrx, lry); +} + +/* + * Reads the limiting bounding box from preferences and draws it on the screen + */ +// TODO: Note that currently the bbox is not user-settable; we simply use the page borders +void +lpetool_context_reset_limiting_bbox(LpeTool *lc) +{ + if (lc->canvas_bbox) { + sp_canvas_item_destroy(lc->canvas_bbox); + lc->canvas_bbox = NULL; + } + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (!prefs->getBool("/tools/lpetool/show_bbox", true)) + return; + + SPDocument *document = sp_desktop_document(lc->desktop); + + Geom::Point A, B; + lpetool_get_limiting_bbox_corners(document, A, B); + Geom::Affine doc2dt(lc->desktop->doc2dt()); + A *= doc2dt; + B *= doc2dt; + + Geom::Rect rect(A, B); + SPCurve *curve = SPCurve::new_from_rect(rect); + + lc->canvas_bbox = sp_canvas_bpath_new (sp_desktop_controls(lc->desktop), curve); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(lc->canvas_bbox), 0x0000ffff, 0.8, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 5); +} + +static void +set_pos_and_anchor(SPCanvasText *canvas_text, const Geom::Piecewise<Geom::D2<Geom::SBasis> > &pwd2, + const double t, const double length, bool /*use_curvature*/ = false) +{ + using namespace Geom; + + Piecewise<D2<SBasis> > pwd2_reparam = arc_length_parametrization(pwd2, 2 , 0.1); + double t_reparam = pwd2_reparam.cuts.back() * t; + Point pos = pwd2_reparam.valueAt(t_reparam); + Point dir = unit_vector(derivative(pwd2_reparam).valueAt(t_reparam)); + Point n = -rot90(dir); + double angle = Geom::angle_between(dir, Point(1,0)); + + sp_canvastext_set_coords(canvas_text, pos + n * length); + sp_canvastext_set_anchor_manually(canvas_text, std::sin(angle), -std::cos(angle)); +} + +void +lpetool_create_measuring_items(LpeTool *lc, Inkscape::Selection *selection) +{ + if (!selection) { + selection = sp_desktop_selection(lc->desktop); + } + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + bool show = prefs->getBool("/tools/lpetool/show_measuring_info", true); + + SPPath *path; + SPCurve *curve; + SPCanvasText *canvas_text; + SPCanvasGroup *tmpgrp = sp_desktop_tempgroup(lc->desktop); + gchar *arc_length; + double lengthval; + + for (GSList const *i = selection->itemList(); i != NULL; i = i->next) { + if (SP_IS_PATH(i->data)) { + path = SP_PATH(i->data); + curve = path->getCurve(); + Geom::Piecewise<Geom::D2<Geom::SBasis> > pwd2 = paths_to_pw(curve->get_pathvector()); + canvas_text = (SPCanvasText *) sp_canvastext_new(tmpgrp, lc->desktop, Geom::Point(0,0), ""); + if (!show) + sp_canvas_item_hide(SP_CANVAS_ITEM(canvas_text)); + + Inkscape::Util::Unit const * unit = NULL; + if (prefs->getString("/tools/lpetool/unit").compare("")) { + unit = unit_table.getUnit(prefs->getString("/tools/lpetool/unit")); + } else { + unit = unit_table.getUnit("px"); + } + + lengthval = Geom::length(pwd2); + lengthval = Inkscape::Util::Quantity::convert(lengthval, "px", unit); + arc_length = g_strdup_printf("%.2f %s", lengthval, unit->abbr.c_str()); + sp_canvastext_set_text (canvas_text, arc_length); + set_pos_and_anchor(canvas_text, pwd2, 0.5, 10); + // TODO: must we free arc_length? + (*lc->measuring_items)[path] = SP_CANVAS_ITEM(canvas_text); + } + } +} + +void +lpetool_delete_measuring_items(LpeTool *lc) +{ + std::map<SPPath *, SPCanvasItem*>::iterator i; + for (i = lc->measuring_items->begin(); i != lc->measuring_items->end(); ++i) { + sp_canvas_item_destroy(i->second); + } + lc->measuring_items->clear(); +} + +void +lpetool_update_measuring_items(LpeTool *lc) +{ + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + for ( std::map<SPPath *, SPCanvasItem*>::iterator i = lc->measuring_items->begin(); + i != lc->measuring_items->end(); + ++i ) + { + SPPath *path = i->first; + SPCurve *curve = path->getCurve(); + Geom::Piecewise<Geom::D2<Geom::SBasis> > pwd2 = Geom::paths_to_pw(curve->get_pathvector()); + Inkscape::Util::Unit const * unit = NULL; + if (prefs->getString("/tools/lpetool/unit").compare("")) { + unit = unit_table.getUnit(prefs->getString("/tools/lpetool/unit")); + } else { + unit = unit_table.getUnit("px"); + } + double lengthval = Geom::length(pwd2); + lengthval = Inkscape::Util::Quantity::convert(lengthval, "px", unit); + gchar *arc_length = g_strdup_printf("%.2f %s", lengthval, unit->abbr.c_str()); + sp_canvastext_set_text (SP_CANVASTEXT(i->second), arc_length); + set_pos_and_anchor(SP_CANVASTEXT(i->second), pwd2, 0.5, 10); + // TODO: must we free arc_length? + } +} + +void +lpetool_show_measuring_info(LpeTool *lc, bool show) +{ + std::map<SPPath *, SPCanvasItem*>::iterator i; + for (i = lc->measuring_items->begin(); i != lc->measuring_items->end(); ++i) { + if (show) { + sp_canvas_item_show(i->second); + } else { + sp_canvas_item_hide(i->second); + } + } +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/lpe-tool.h b/src/ui/tools/lpe-tool.h new file mode 100644 index 000000000..df78c205c --- /dev/null +++ b/src/ui/tools/lpe-tool.h @@ -0,0 +1,99 @@ +#ifndef SP_LPETOOL_CONTEXT_H_SEEN +#define SP_LPETOOL_CONTEXT_H_SEEN + +/* + * LPEToolContext: a context for a generic tool composed of subtools that are given by LPEs + * + * Authors: + * Maximilian Albert <maximilian.albert@gmail.com> + * + * Copyright (C) 1998 The Free Software Foundation + * Copyright (C) 1999-2002 authors + * Copyright (C) 2001-2002 Ximian, Inc. + * Copyright (C) 2008 Maximilian Albert + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "ui/tools/pen-tool.h" + +#define SP_LPETOOL_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::LpeTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_LPETOOL_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::LpeTool*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +/* This is the list of subtools from which the toolbar of the LPETool is built automatically */ +extern const int num_subtools; + +struct SubtoolEntry { + Inkscape::LivePathEffect::EffectType type; + gchar const *icon_name; +}; + +extern SubtoolEntry lpesubtools[]; + +enum LPEToolState { + LPETOOL_STATE_PEN, + LPETOOL_STATE_NODE +}; + +namespace Inkscape { +class Selection; +} + +class ShapeEditor; + +namespace Inkscape { +namespace UI { +namespace Tools { + +class LpeTool : public PenTool { +public: + LpeTool(); + virtual ~LpeTool(); + + ShapeEditor* shape_editor; + SPCanvasItem *canvas_bbox; + Inkscape::LivePathEffect::EffectType mode; + + std::map<SPPath *, SPCanvasItem*> *measuring_items; + + sigc::connection sel_changed_connection; + sigc::connection sel_modified_connection; + + static const std::string prefsPath; + + virtual const std::string& getPrefsPath(); + +protected: + virtual void setup(); + virtual void set(const Inkscape::Preferences::Entry& val); + virtual bool root_handler(GdkEvent* event); + virtual bool item_handler(SPItem* item, GdkEvent* event); +}; + +int lpetool_mode_to_index(Inkscape::LivePathEffect::EffectType const type); +int lpetool_item_has_construction(LpeTool *lc, SPItem *item); +bool lpetool_try_construction(LpeTool *lc, Inkscape::LivePathEffect::EffectType const type); +void lpetool_context_switch_mode(LpeTool *lc, Inkscape::LivePathEffect::EffectType const type); +void lpetool_get_limiting_bbox_corners(SPDocument *document, Geom::Point &A, Geom::Point &B); +void lpetool_context_reset_limiting_bbox(LpeTool *lc); +void lpetool_create_measuring_items(LpeTool *lc, Inkscape::Selection *selection = NULL); +void lpetool_delete_measuring_items(LpeTool *lc); +void lpetool_update_measuring_items(LpeTool *lc); +void lpetool_show_measuring_info(LpeTool *lc, bool show = true); + +} +} +} + +#endif // SP_LPETOOL_CONTEXT_H_SEEN + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/measure-tool.cpp b/src/ui/tools/measure-tool.cpp new file mode 100644 index 000000000..380aa79e3 --- /dev/null +++ b/src/ui/tools/measure-tool.cpp @@ -0,0 +1,777 @@ +/* + * Our nice measuring tool + * + * Authors: + * Felipe Correa da Silva Sanches <juca@members.fsf.org> + * Jon A. Cruz <jon@joncruz.org> + * + * Copyright (C) 2011 Authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + + +#include <gdk/gdkkeysyms.h> +#include <boost/none_t.hpp> +#include "util/units.h" +#include "macros.h" +#include "display/curve.h" +#include "sp-shape.h" +#include "sp-text.h" +#include "sp-flowtext.h" +#include "text-editing.h" +#include "display/sp-ctrlline.h" +#include "display/sodipodi-ctrl.h" +#include "display/sp-canvas-item.h" +#include "display/sp-canvas-util.h" +#include "desktop.h" +#include "document.h" +#include "pixmaps/cursor-measure.xpm" +#include "preferences.h" +#include "inkscape.h" +#include "desktop-handles.h" +#include "ui/tools/measure-tool.h" +#include "ui/tools/freehand-base.h" +#include "display/canvas-text.h" +#include "path-chemistry.h" +#include "2geom/line.h" +#include <2geom/path-intersection.h> +#include <2geom/pathvector.h> +#include <2geom/crossing.h> +#include <2geom/angle.h> +#include "snap.h" +#include "sp-namedview.h" +#include "enums.h" +#include "ui/control-manager.h" + +using Inkscape::ControlManager; +using Inkscape::CTLINE_SECONDARY; +using Inkscape::Util::unit_table; + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +std::vector<Inkscape::Display::TemporaryItem*> measure_tmp_items; + +namespace { + ToolBase* createMeasureContext() { + return new MeasureTool(); + } + + bool measureContextRegistered = ToolFactory::instance().registerObject("/tools/measure", createMeasureContext); +} + +const std::string& MeasureTool::getPrefsPath() { + return MeasureTool::prefsPath; +} + +const std::string MeasureTool::prefsPath = "/tools/measure"; + +namespace +{ + +gint const DIMENSION_OFFSET = 35; + +/** + * Simple class to use for removing label overlap. + */ +class LabelPlacement { +public: + + double lengthVal; + double offset; + Geom::Point start; + Geom::Point end; +}; + +bool SortLabelPlacement(LabelPlacement const &first, LabelPlacement const &second) +{ + if (first.end[Geom::Y] == second.end[Geom::Y]) { + return first.end[Geom::X] < second.end[Geom::X]; + } else { + return first.end[Geom::Y] < second.end[Geom::Y]; + } +} + +void repositionOverlappingLabels(std::vector<LabelPlacement> &placements, SPDesktop *desktop, Geom::Point const &normal, double fontsize) +{ + std::sort(placements.begin(), placements.end(), SortLabelPlacement); + + double border = 3; + Geom::Rect box; + { + Geom::Point tmp(fontsize * 8 + (border * 2), fontsize + (border * 2)); + tmp = desktop->w2d(tmp); + box = Geom::Rect(-tmp[Geom::X] / 2, -tmp[Geom::Y] / 2, tmp[Geom::X] / 2, tmp[Geom::Y] / 2); + } + + // Using index since vector may be re-ordered as we go. + // Starting at one, since the first item can't overlap itself + for (size_t i = 1; i < placements.size(); i++) { + LabelPlacement &place = placements[i]; + + bool changed = false; + do { + Geom::Rect current(box + place.end); + + changed = false; + bool overlaps = false; + for (size_t j = i; (j > 0) && !overlaps; --j) { + LabelPlacement &otherPlace = placements[j - 1]; + Geom::Rect target(box + otherPlace.end); + if (current.intersects(target)) { + overlaps = true; + } + } + if (overlaps) { + place.offset += (fontsize + border); + place.end = place.start - desktop->w2d(normal * place.offset); + changed = true; + } + } while (changed); + + std::sort(placements.begin(), placements.begin() + i + 1, SortLabelPlacement); + } +} + +/** + * Calculates where to place the anchor for the display text and arc. + * + * @param desktop the desktop that is being used. + * @param angle the angle to be displaying. + * @param baseAngle the angle of the initial baseline. + * @param startPoint the point that is the vertex of the selected angle. + * @param endPoint the point that is the end the user is manipulating for measurement. + * @param fontsize the size to display the text label at. + */ +Geom::Point calcAngleDisplayAnchor(SPDesktop *desktop, double angle, double baseAngle, + Geom::Point const &startPoint, Geom::Point const &endPoint, + double fontsize) +{ + // Time for the trick work of figuring out where things should go, and how. + double lengthVal = (endPoint - startPoint).length(); + double effective = baseAngle + (angle / 2); + Geom::Point where(lengthVal, 0); + where *= Geom::Affine(Geom::Rotate(effective)) * Geom::Affine(Geom::Translate(startPoint)); + + // When the angle is tight, the label would end up under the cursor and/or lines. Bump it + double scaledFontsize = std::abs(fontsize * desktop->w2d(Geom::Point(0, 1.0))[Geom::Y]); + if (std::abs((where - endPoint).length()) < scaledFontsize) { + where[Geom::Y] += scaledFontsize * 2; + } + + // We now have the ideal position, but need to see if it will fit/work. + + Geom::Rect visibleArea = desktop->get_display_area(); + // Bring it in to "title safe" for the anchor point + Geom::Point textBox = desktop->w2d(Geom::Point(fontsize * 3, fontsize / 2)); + textBox[Geom::Y] = std::abs(textBox[Geom::Y]); + + visibleArea = Geom::Rect(visibleArea.min()[Geom::X] + textBox[Geom::X], + visibleArea.min()[Geom::Y] + textBox[Geom::Y], + visibleArea.max()[Geom::X] - textBox[Geom::X], + visibleArea.max()[Geom::Y] - textBox[Geom::Y]); + + where[Geom::X] = std::min(where[Geom::X], visibleArea.max()[Geom::X]); + where[Geom::X] = std::max(where[Geom::X], visibleArea.min()[Geom::X]); + where[Geom::Y] = std::min(where[Geom::Y], visibleArea.max()[Geom::Y]); + where[Geom::Y] = std::max(where[Geom::Y], visibleArea.min()[Geom::Y]); + + return where; +} + +/** + * Given an angle, the arc center and edge point, draw an arc segment centered around that edge point. + * + * @param desktop the desktop that is being used. + * @param center the center point for the arc. + * @param end the point that ends at the edge of the arc segment. + * @param anchor the anchor point for displaying the text label. + * @param angle the angle of the arc segment to draw. + */ +void createAngleDisplayCurve(SPDesktop *desktop, Geom::Point const ¢er, Geom::Point const &end, Geom::Point const &anchor, double angle) +{ + // Given that we have a point on the arc's edge and the angle of the arc, we need to get the two endpoints. + + double textLen = std::abs((anchor - center).length()); + double sideLen = std::abs((end - center).length()); + if (sideLen > 0.0) { + double factor = std::min(1.0, textLen / sideLen); + + // arc start + Geom::Point p1 = end * (Geom::Affine(Geom::Translate(-center)) + * Geom::Affine(Geom::Scale(factor)) + * Geom::Affine(Geom::Translate(center))); + + // arc end + Geom::Point p4 = p1 * (Geom::Affine(Geom::Translate(-center)) + * Geom::Affine(Geom::Rotate(-angle)) + * Geom::Affine(Geom::Translate(center))); + + // from Riskus + double xc = center[Geom::X]; + double yc = center[Geom::Y]; + double ax = p1[Geom::X] - xc; + double ay = p1[Geom::Y] - yc; + double bx = p4[Geom::X] - xc; + double by = p4[Geom::Y] - yc; + double q1 = (ax * ax) + (ay * ay); + double q2 = q1 + (ax * bx) + (ay * by); + + double k2 = (4.0 / 3.0) * (std::sqrt(2 * q1 * q2) - q2) / ((ax * by) - (ay * bx)); + + Geom::Point p2(xc + ax - (k2 * ay), + yc + ay + (k2 * ax)); + Geom::Point p3(xc + bx + (k2 * by), + yc + by - (k2 * bx)); + SPCtrlCurve *curve = ControlManager::getManager().createControlCurve(sp_desktop_tempgroup(desktop), p1, p2, p3, p4, CTLINE_SECONDARY); + + measure_tmp_items.push_back(desktop->add_temporary_canvasitem(SP_CANVAS_ITEM(curve), 0, true)); + } +} + +} // namespace + + +MeasureTool::MeasureTool() + : ToolBase(cursor_measure_xpm, 4, 4) + , grabbed(NULL) +{ +} + +MeasureTool::~MeasureTool() { +} + +void MeasureTool::finish() { + this->enableGrDrag(false); + + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed, GDK_CURRENT_TIME); + this->grabbed = NULL; + } + + ToolBase::finish(); +} + +//void MeasureTool::setup() { +// ToolBase* ec = this; +// +//// if (SP_EVENT_CONTEXT_CLASS(sp_measure_context_parent_class)->setup) { +//// SP_EVENT_CONTEXT_CLASS(sp_measure_context_parent_class)->setup(ec); +//// } +// ToolBase::setup(); +//} + +//gint MeasureTool::item_handler(SPItem* item, GdkEvent* event) { +// gint ret = FALSE; +// +//// if (SP_EVENT_CONTEXT_CLASS(sp_measure_context_parent_class)->item_handler) { +//// ret = SP_EVENT_CONTEXT_CLASS(sp_measure_context_parent_class)->item_handler(event_context, item, event); +//// } +// ret = ToolBase::item_handler(item, event); +// +// return ret; +//} + +static bool GeomPointSortPredicate(const Geom::Point& p1, const Geom::Point& p2) +{ + if (p1[Geom::Y] == p2[Geom::Y]) { + return p1[Geom::X] < p2[Geom::X]; + } else { + return p1[Geom::Y] < p2[Geom::Y]; + } +} + +static void calculate_intersections(SPDesktop * /*desktop*/, SPItem* item, Geom::PathVector const &lineseg, SPCurve *curve, std::vector<Geom::Point> &intersections) +{ + curve->transform(item->i2doc_affine()); + + // Find all intersections of the control-line with this shape + Geom::CrossingSet cs = Geom::crossings(lineseg, curve->get_pathvector()); + + // Reconstruct and store the points of intersection + for (Geom::Crossings::const_iterator m = cs[0].begin(); m != cs[0].end(); ++m) { +#if 0 +//TODO: consider only visible intersections + Geom::Point intersection = lineseg[0].pointAt((*m).ta); + double eps = 0.0001; + SPDocument* doc = sp_desktop_document(desktop); + if (((*m).ta > eps && + item == doc->getItemAtPoint(desktop->dkey, lineseg[0].pointAt((*m).ta - eps), false, NULL)) || + ((*m).ta + eps < 1 && + item == doc->getItemAtPoint(desktop->dkey, lineseg[0].pointAt((*m).ta + eps), false, NULL)) ) { + intersections.push_back(intersection); + } +#else + intersections.push_back(lineseg[0].pointAt((*m).ta)); +#endif + } +} + +bool MeasureTool::root_handler(GdkEvent* event) { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + + gint ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: { + Geom::Point const button_w(event->button.x, event->button.y); + explicitBase = boost::none; + lastEnd = boost::none; + start_point = desktop->w2d(button_w); + + if (event->button.button == 1 && !this->space_panning) { + // save drag origin + xp = static_cast<gint>(event->button.x); + yp = static_cast<gint>(event->button.y); + within_tolerance = true; + + ret = TRUE; + } + + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + m.freeSnapReturnByRef(start_point, Inkscape::SNAPSOURCE_OTHER_HANDLE); + m.unSetup(); + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK, + NULL, event->button.time); + this->grabbed = SP_CANVAS_ITEM(desktop->acetate); + break; + } + case GDK_KEY_PRESS: { + if ((event->key.keyval == GDK_KEY_Shift_L) || (event->key.keyval == GDK_KEY_Shift_R)) { + if (lastEnd) { + explicitBase = lastEnd; + } + } + break; + } + case GDK_MOTION_NOTIFY: { + if (!((event->motion.state & GDK_BUTTON1_MASK) && !this->space_panning)) { + if (!(event->motion.state & GDK_SHIFT_MASK)) { + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point const motion_dt(desktop->w2d(motion_w)); + + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + + Inkscape::SnapCandidatePoint scp(motion_dt, Inkscape::SNAPSOURCE_OTHER_HANDLE); + scp.addOrigin(start_point); + + m.preSnap(scp); + m.unSetup(); + } + } else { + ret = TRUE; + + if ( within_tolerance + && ( abs( static_cast<gint>(event->motion.x) - xp ) < tolerance ) + && ( abs( static_cast<gint>(event->motion.y) - yp ) < tolerance ) ) { + break; // do not drag if we're within tolerance from origin + } + // Once the user has moved farther than tolerance from the original location + // (indicating they intend to move the object, not click), then always process the + // motion notify coordinates as given (no snapping back to origin) + within_tolerance = false; + + //clear previous temporary canvas items, we'll draw new ones + for (size_t idx = 0; idx < measure_tmp_items.size(); ++idx) { + desktop->remove_temporary_canvasitem(measure_tmp_items[idx]); + } + + measure_tmp_items.clear(); + + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point const motion_dt(desktop->w2d(motion_w)); + Geom::Point end_point = motion_dt; + + if (event->motion.state & GDK_CONTROL_MASK) { + spdc_endpoint_snap_rotation(this, end_point, start_point, event->motion.state); + } else { + if (!(event->motion.state & GDK_SHIFT_MASK)) { + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + Inkscape::SnapCandidatePoint scp(end_point, Inkscape::SNAPSOURCE_OTHER_HANDLE); + scp.addOrigin(start_point); + Inkscape::SnappedPoint sp = m.freeSnap(scp); + end_point = sp.getPoint(); + m.unSetup(); + } + } + + Geom::PathVector lineseg; + Geom::Path p; + p.start(desktop->dt2doc(start_point)); + p.appendNew<Geom::LineSegment>(desktop->dt2doc(end_point)); + lineseg.push_back(p); + + double deltax = end_point[Geom::X] - start_point[Geom::X]; + double deltay = end_point[Geom::Y] - start_point[Geom::Y]; + double angle = atan2(deltay, deltax); + double baseAngle = 0; + + if (explicitBase) { + double deltax2 = explicitBase.get()[Geom::X] - start_point[Geom::X]; + double deltay2 = explicitBase.get()[Geom::Y] - start_point[Geom::Y]; + + baseAngle = atan2(deltay2, deltax2); + angle -= baseAngle; + + if (angle < -M_PI) { + angle += 2 * M_PI; + } else if (angle > M_PI) { + angle -= 2 * M_PI; + } + } + +//TODO: calculate NPOINTS +//800 seems to be a good value for 800x600 resolution +#define NPOINTS 800 + + std::vector<Geom::Point> points; + + for (double i = 0; i < NPOINTS; i++) { + points.push_back(desktop->d2w(start_point + (i / NPOINTS) * (end_point - start_point))); + } + +// TODO: Felipe, why don't you simply iterate over all items, and test whether their bounding boxes intersect +// with the measurement line, instead of interpolating? E.g. bbox_of_measurement_line.intersects(*bbox_of_item). +// That's also how the object-snapper works, see _findCandidates() in object-snapper.cpp. + + //select elements crossed by line segment: + GSList *items = sp_desktop_document(desktop)->getItemsAtPoints(desktop->dkey, points); + std::vector<Geom::Point> intersections; + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + bool ignore_1st_and_last = prefs->getBool("/tools/measure/ignore_1st_and_last", true); + + if (!ignore_1st_and_last) { + intersections.push_back(desktop->dt2doc(start_point)); + } + + std::vector<LabelPlacement> placements; + + // TODO switch to a different variable name. The single letter 'l' is easy to misread. + for (GSList *l = items; l != NULL; l = l->next) { + SPItem *item = static_cast<SPItem*>(l->data); + + if (SP_IS_SHAPE(item)) { + calculate_intersections(desktop, item, lineseg, SP_SHAPE(item)->getCurve(), intersections); + } else { + if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item)) { + Inkscape::Text::Layout::iterator iter = te_get_layout(item)->begin(); + do { + Inkscape::Text::Layout::iterator iter_next = iter; + iter_next.nextGlyph(); // iter_next is one glyph ahead from iter + if (iter == iter_next) { + break; + } + + // get path from iter to iter_next: + SPCurve *curve = te_get_layout(item)->convertToCurves(iter, iter_next); + iter = iter_next; // shift to next glyph + if (!curve) { + continue; // error converting this glyph + } + if (curve->is_empty()) { // whitespace glyph? + curve->unref(); + continue; + } + + curve->transform(item->i2doc_affine()); + + calculate_intersections(desktop, item, lineseg, curve, intersections); + + if (iter == te_get_layout(item)->end()) { + break; + } + } while (true); + } + } + } + + if (!ignore_1st_and_last) { + intersections.push_back(desktop->dt2doc(end_point)); + } + + //sort intersections + if (intersections.size() > 2) { + std::sort(intersections.begin(), intersections.end(), GeomPointSortPredicate); + } + + Glib::ustring unit_name = prefs->getString("/tools/measure/unit"); + if (!unit_name.compare("")) { + unit_name = "px"; + } + + double fontsize = prefs->getInt("/tools/measure/fontsize"); + + // Normal will be used for lines and text + Geom::Point windowNormal = Geom::unit_vector(Geom::rot90(desktop->d2w(end_point - start_point))); + Geom::Point normal = desktop->w2d(windowNormal); + + for (size_t idx = 1; idx < intersections.size(); ++idx) { + LabelPlacement placement; + placement.lengthVal = (intersections[idx] - intersections[idx - 1]).length(); + placement.lengthVal = Inkscape::Util::Quantity::convert(placement.lengthVal, "px", unit_name); + placement.offset = DIMENSION_OFFSET; + placement.start = desktop->doc2dt( (intersections[idx - 1] + intersections[idx]) / 2 ); + placement.end = placement.start - (normal * placement.offset); + + placements.push_back(placement); + } + + // Adjust positions + repositionOverlappingLabels(placements, desktop, windowNormal, fontsize); + + for (std::vector<LabelPlacement>::iterator it = placements.begin(); it != placements.end(); ++it) + { + LabelPlacement &place = *it; + + // TODO cleanup memory, Glib::ustring, etc.: + gchar *measure_str = g_strdup_printf("%.2f %s", place.lengthVal, unit_name.c_str()); + SPCanvasText *canvas_tooltip = sp_canvastext_new(sp_desktop_tempgroup(desktop), + desktop, + place.end, + measure_str); + sp_canvastext_set_fontsize(canvas_tooltip, fontsize); + canvas_tooltip->rgba = 0xffffffff; + canvas_tooltip->rgba_background = 0x0000007f; + canvas_tooltip->outline = false; + canvas_tooltip->background = true; + canvas_tooltip->anchor_position = TEXT_ANCHOR_CENTER; + + measure_tmp_items.push_back(desktop->add_temporary_canvasitem(canvas_tooltip, 0)); + g_free(measure_str); + } + + Geom::Point angleDisplayPt = calcAngleDisplayAnchor(desktop, angle, baseAngle, + start_point, end_point, + fontsize); + + { + // TODO cleanup memory, Glib::ustring, etc.: + gchar *angle_str = g_strdup_printf("%.2f °", angle * 180/M_PI); + + SPCanvasText *canvas_tooltip = sp_canvastext_new(sp_desktop_tempgroup(desktop), + desktop, + angleDisplayPt, + angle_str); + sp_canvastext_set_fontsize(canvas_tooltip, fontsize); + canvas_tooltip->rgba = 0xffffffff; + canvas_tooltip->rgba_background = 0x337f337f; + canvas_tooltip->outline = false; + canvas_tooltip->background = true; + canvas_tooltip->anchor_position = TEXT_ANCHOR_CENTER; + + measure_tmp_items.push_back(desktop->add_temporary_canvasitem(canvas_tooltip, 0)); + g_free(angle_str); + } + + { + double totallengthval = (end_point - start_point).length(); + totallengthval = Inkscape::Util::Quantity::convert(totallengthval, "px", unit_name); + + // TODO cleanup memory, Glib::ustring, etc.: + gchar *totallength_str = g_strdup_printf("%.2f %s", totallengthval, unit_name.c_str()); + SPCanvasText *canvas_tooltip = sp_canvastext_new(sp_desktop_tempgroup(desktop), + desktop, + end_point + desktop->w2d(Geom::Point(3*fontsize, -fontsize)), + totallength_str); + sp_canvastext_set_fontsize(canvas_tooltip, fontsize); + canvas_tooltip->rgba = 0xffffffff; + canvas_tooltip->rgba_background = 0x3333337f; + canvas_tooltip->outline = false; + canvas_tooltip->background = true; + canvas_tooltip->anchor_position = TEXT_ANCHOR_LEFT; + + measure_tmp_items.push_back(desktop->add_temporary_canvasitem(canvas_tooltip, 0)); + g_free(totallength_str); + } + + if (intersections.size() > 2) { + double totallengthval = (intersections[intersections.size()-1] - intersections[0]).length(); + totallengthval = Inkscape::Util::Quantity::convert(totallengthval, "px", unit_name); + + // TODO cleanup memory, Glib::ustring, etc.: + gchar *total_str = g_strdup_printf("%.2f %s", totallengthval, unit_name.c_str()); + SPCanvasText *canvas_tooltip = sp_canvastext_new(sp_desktop_tempgroup(desktop), + desktop, + desktop->doc2dt((intersections[0] + intersections[intersections.size()-1])/2) + normal * 60, + total_str); + sp_canvastext_set_fontsize(canvas_tooltip, fontsize); + canvas_tooltip->rgba = 0xffffffff; + canvas_tooltip->rgba_background = 0x33337f7f; + canvas_tooltip->outline = false; + canvas_tooltip->background = true; + canvas_tooltip->anchor_position = TEXT_ANCHOR_CENTER; + + measure_tmp_items.push_back(desktop->add_temporary_canvasitem(canvas_tooltip, 0)); + g_free(total_str); + } + + // Now that text has been added, we can add lines and controls so that they go underneath + + for (size_t idx = 0; idx < intersections.size(); ++idx) { + // Display the intersection indicator (i.e. the cross) + SPCanvasItem * canvasitem = sp_canvas_item_new(sp_desktop_tempgroup(desktop), + SP_TYPE_CTRL, + "anchor", SP_ANCHOR_CENTER, + "size", 8.0, + "stroked", TRUE, + "stroke_color", 0xff0000ff, + "mode", SP_KNOT_MODE_XOR, + "shape", SP_KNOT_SHAPE_CROSS, + NULL ); + + SP_CTRL(canvasitem)->moveto(desktop->doc2dt(intersections[idx])); + measure_tmp_items.push_back(desktop->add_temporary_canvasitem(canvasitem, 0)); + } + + // Since adding goes to the bottom, do all lines last. + + // draw main control line + { + SPCtrlLine *control_line = ControlManager::getManager().createControlLine(sp_desktop_tempgroup(desktop), + start_point, + end_point); + measure_tmp_items.push_back(desktop->add_temporary_canvasitem(control_line, 0)); + + if ((end_point[Geom::X] != start_point[Geom::X]) && (end_point[Geom::Y] != start_point[Geom::Y])) { + double length = std::abs((end_point - start_point).length()); + Geom::Point anchorEnd = start_point; + anchorEnd[Geom::X] += length; + if (explicitBase) { + anchorEnd *= (Geom::Affine(Geom::Translate(-start_point)) + * Geom::Affine(Geom::Rotate(baseAngle)) + * Geom::Affine(Geom::Translate(start_point))); + } + + SPCtrlLine *control_line = ControlManager::getManager().createControlLine(sp_desktop_tempgroup(desktop), + start_point, + anchorEnd, + CTLINE_SECONDARY); + measure_tmp_items.push_back(desktop->add_temporary_canvasitem(control_line, 0)); + + createAngleDisplayCurve(desktop, start_point, end_point, angleDisplayPt, angle); + } + } + + if (intersections.size() > 2) { + ControlManager &mgr = ControlManager::getManager(); + SPCtrlLine *control_line = 0; + control_line = mgr.createControlLine(sp_desktop_tempgroup(desktop), + desktop->doc2dt(intersections[0]) + normal * 60, + desktop->doc2dt(intersections[intersections.size() - 1]) + normal * 60); + measure_tmp_items.push_back(desktop->add_temporary_canvasitem(control_line, 0)); + + control_line = mgr.createControlLine(sp_desktop_tempgroup(desktop), + desktop->doc2dt(intersections[0]), + desktop->doc2dt(intersections[0]) + normal * 65); + measure_tmp_items.push_back(desktop->add_temporary_canvasitem(control_line, 0)); + + control_line = mgr.createControlLine(sp_desktop_tempgroup(desktop), + desktop->doc2dt(intersections[intersections.size() - 1]), + desktop->doc2dt(intersections[intersections.size() - 1]) + normal * 65); + measure_tmp_items.push_back(desktop->add_temporary_canvasitem(control_line, 0)); + } + + // call-out lines + for (std::vector<LabelPlacement>::iterator it = placements.begin(); it != placements.end(); ++it) + { + LabelPlacement &place = *it; + + ControlManager &mgr = ControlManager::getManager(); + SPCtrlLine *control_line = mgr.createControlLine(sp_desktop_tempgroup(desktop), + place.start, + place.end, + CTLINE_SECONDARY); + measure_tmp_items.push_back(desktop->add_temporary_canvasitem(control_line, 0)); + } + + { + for (size_t idx = 1; idx < intersections.size(); ++idx) { + Geom::Point measure_text_pos = (intersections[idx - 1] + intersections[idx]) / 2; + + ControlManager &mgr = ControlManager::getManager(); + SPCtrlLine *control_line = mgr.createControlLine(sp_desktop_tempgroup(desktop), + desktop->doc2dt(measure_text_pos), + desktop->doc2dt(measure_text_pos) - (normal * DIMENSION_OFFSET), + CTLINE_SECONDARY); + measure_tmp_items.push_back(desktop->add_temporary_canvasitem(control_line, 0)); + } + } + + // Initial point + { + SPCanvasItem * canvasitem = sp_canvas_item_new(sp_desktop_tempgroup(desktop), + SP_TYPE_CTRL, + "anchor", SP_ANCHOR_CENTER, + "size", 8.0, + "stroked", TRUE, + "stroke_color", 0xff0000ff, + "mode", SP_KNOT_MODE_XOR, + "shape", SP_KNOT_SHAPE_CROSS, + NULL ); + + SP_CTRL(canvasitem)->moveto(start_point); + measure_tmp_items.push_back(desktop->add_temporary_canvasitem(canvasitem, 0)); + } + + lastEnd = end_point; // track in case we get a anchoring key-press later + + gobble_motion_events(GDK_BUTTON1_MASK); + } + break; + } + case GDK_BUTTON_RELEASE: { + sp_event_context_discard_delayed_snap_event(this); + explicitBase = boost::none; + lastEnd = boost::none; + + //clear all temporary canvas items related to the measurement tool. + for (size_t idx = 0; idx < measure_tmp_items.size(); ++idx) { + desktop->remove_temporary_canvasitem(measure_tmp_items[idx]); + } + + measure_tmp_items.clear(); + + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed, event->button.time); + this->grabbed = NULL; + } + + xp = 0; + yp = 0; + break; + } + default: + break; + } + + if (!ret) { + ret = ToolBase::root_handler(event); + } + + return ret; +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/tools/measure-tool.h b/src/ui/tools/measure-tool.h new file mode 100644 index 000000000..9701ba6ea --- /dev/null +++ b/src/ui/tools/measure-tool.h @@ -0,0 +1,50 @@ +#ifndef SEEN_SP_MEASURING_CONTEXT_H +#define SEEN_SP_MEASURING_CONTEXT_H + +/* + * Our fine measuring tool + * + * Authors: + * Felipe Correa da Silva Sanches <juca@members.fsf.org> + * + * Copyright (C) 2011 Authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "ui/tools/tool-base.h" +#include <2geom/point.h> +#include <boost/optional.hpp> + +#define SP_MEASURE_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::MeasureTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_MEASURE_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::MeasureTool*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +namespace Inkscape { +namespace UI { +namespace Tools { + +class MeasureTool : public ToolBase { +public: + MeasureTool(); + virtual ~MeasureTool(); + + static const std::string prefsPath; + + virtual void finish(); + virtual bool root_handler(GdkEvent* event); + + virtual const std::string& getPrefsPath(); + +private: + SPCanvasItem* grabbed; + + Geom::Point start_point; + boost::optional<Geom::Point> explicitBase; + boost::optional<Geom::Point> lastEnd; +}; + +} +} +} + +#endif // SEEN_SP_MEASURING_CONTEXT_H diff --git a/src/ui/tools/mesh-tool.cpp b/src/ui/tools/mesh-tool.cpp new file mode 100644 index 000000000..7d6d3bc23 --- /dev/null +++ b/src/ui/tools/mesh-tool.cpp @@ -0,0 +1,1015 @@ +/* + * Mesh drawing and editing tool + * + * Authors: + * bulia byak <buliabyak@users.sf.net> + * Johan Engelen <j.b.c.engelen@ewi.utwente.nl> + * Abhishek Sharma + * Tavmjong Bah <tavmjong@free.fr> + * + * Copyright (C) 2012 Tavmjong Bah + * Copyright (C) 2007 Johan Engelen + * Copyright (C) 2005 Authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +//#define DEBUG_MESH + + +// Libraries +#include <gdk/gdkkeysyms.h> +#include <glibmm/i18n.h> + +// General +#include "desktop.h" +#include "desktop-handles.h" +#include "document.h" +#include "document-undo.h" +#include "macros.h" +#include "message-context.h" +#include "message-stack.h" +#include "preferences.h" +#include "rubberband.h" +#include "selection.h" +#include "snap.h" +#include "sp-namedview.h" +#include "verbs.h" + +// Gradient specific +#include "gradient-drag.h" +#include "gradient-chemistry.h" +#include "pixmaps/cursor-gradient.xpm" +#include "pixmaps/cursor-gradient-add.xpm" + +// Mesh specific +#include "ui/tools/mesh-tool.h" +#include "sp-mesh-gradient.h" +#include "display/sp-ctrlcurve.h" + +using Inkscape::DocumentUndo; + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +static void sp_mesh_drag(MeshTool &rc, Geom::Point const pt, guint state, guint32 etime); + +namespace { + ToolBase* createMeshContext() { + return new MeshTool(); + } + + bool meshContextRegistered = ToolFactory::instance().registerObject("/tools/mesh", createMeshContext); +} + +const std::string& MeshTool::getPrefsPath() { + return MeshTool::prefsPath; +} + +const std::string MeshTool::prefsPath = "/tools/mesh"; + +// TODO: The gradient tool class looks like a 1:1 copy. + +MeshTool::MeshTool() + : ToolBase(cursor_gradient_xpm, 4, 4) + , cursor_addnode(false) + , node_added(false) +// TODO: Why are these connections stored as pointers? + , selcon(NULL) + , subselcon(NULL) +{ + // TODO: This value is overwritten in the root handler + this->tolerance = 6; +} + +MeshTool::~MeshTool() { + this->enableGrDrag(false); + + this->selcon->disconnect(); + delete this->selcon; + + this->subselcon->disconnect(); + delete this->subselcon; +} + +const gchar *ms_handle_descr [] = { + N_("Mesh gradient <b>corner</b>"), + N_("Mesh gradient <b>handle</b>"), + N_("Mesh gradient <b>tensor</b>") +}; + +void MeshTool::selection_changed(Inkscape::Selection* /*sel*/) { + GrDrag *drag = this->_grdrag; + Inkscape::Selection *selection = sp_desktop_selection(this->desktop); + + if (selection == NULL) { + return; + } + + guint n_obj = g_slist_length((GSList *) selection->itemList()); + + if (!drag->isNonEmpty() || selection->isEmpty()) { + return; + } + + guint n_tot = drag->numDraggers(); + guint n_sel = drag->numSelected(); + + //The use of ngettext in the following code is intentional even if the English singular form would never be used + if (n_sel == 1) { + if (drag->singleSelectedDraggerNumDraggables() == 1) { + gchar * message = g_strconcat( + //TRANSLATORS: %s will be substituted with the point name (see previous messages); This is part of a compound message + _("%s selected"), + //TRANSLATORS: Mind the space in front. This is part of a compound message + ngettext(" out of %d mesh handle"," out of %d mesh handles",n_tot), + ngettext(" on %d selected object"," on %d selected objects",n_obj),NULL); + this->message_context->setF(Inkscape::NORMAL_MESSAGE, + message,_(ms_handle_descr[drag->singleSelectedDraggerSingleDraggableType()]), n_tot, n_obj); + } else { + gchar * message = + g_strconcat( + //TRANSLATORS: This is a part of a compound message (out of two more indicating: grandint handle count & object count) + ngettext("One handle merging %d stop (drag with <b>Shift</b> to separate) selected", + "One handle merging %d stops (drag with <b>Shift</b> to separate) selected", + drag->singleSelectedDraggerNumDraggables()), + ngettext(" out of %d mesh handle"," out of %d mesh handles",n_tot), + ngettext(" on %d selected object"," on %d selected objects",n_obj),NULL); + this->message_context->setF(Inkscape::NORMAL_MESSAGE,message,drag->singleSelectedDraggerNumDraggables(), n_tot, n_obj); + } + } else if (n_sel > 1) { + //TRANSLATORS: The plural refers to number of selected mesh handles. This is part of a compound message (part two indicates selected object count) + gchar * message = + g_strconcat(ngettext("<b>%d</b> mesh handle selected out of %d","<b>%d</b> mesh handles selected out of %d",n_sel), + //TRANSLATORS: Mind the space in front. (Refers to gradient handles selected). This is part of a compound message + ngettext(" on %d selected object"," on %d selected objects",n_obj),NULL); + this->message_context->setF(Inkscape::NORMAL_MESSAGE,message, n_sel, n_tot, n_obj); + } else if (n_sel == 0) { + this->message_context->setF(Inkscape::NORMAL_MESSAGE, + //TRANSLATORS: The plural refers to number of selected objects + ngettext("<b>No</b> mesh handles selected out of %d on %d selected object", + "<b>No</b> mesh handles selected out of %d on %d selected objects",n_obj), n_tot, n_obj); + } + + // FIXME + // We need to update mesh gradient handles. + // Get gradient this drag belongs too.. + // std::cout << "mesh_selection_changed: selection: objects: " << n_obj << std::endl; + // GSList *itemList = (GSList *) selection->itemList(); + // while( itemList ) { + + // SPItem *item = SP_ITEM( itemList->data ); + // // std::cout << " item: " << SP_OBJECT(item)->getId() << std::endl; + + // SPStyle *style = item->style; + // if (style && (style->fill.isPaintserver())) { + + // SPPaintServer *server = item->style->getFillPaintServer(); + // if ( SP_IS_MESHGRADIENT(server) ) { + + // SPMeshGradient *mg = SP_MESHGRADIENT(server); + + // guint rows = 0;//mg->array.patches.size(); + // for ( guint i = 0; i < rows; ++i ) { + // guint columns = 0;//mg->array.patches[0].size(); + // for ( guint j = 0; j < columns; ++j ) { + // } + // } + // } + // } + // itemList = itemList->next; + // } + + // GList* dragger_ptr = drag->draggers; // Points to GrDragger class (group of GrDraggable) + // guint count = 0; + // while( dragger_ptr ) { + + // std::cout << "mesh_selection_changed: dragger: " << ++count << std::endl; + // GSList* draggable_ptr = ((GrDragger *) dragger_ptr->data)->draggables; + + // while( draggable_ptr ) { + + // std::cout << "mesh_selection_changed: draggable: " << draggable_ptr << std::endl; + // GrDraggable *draggable = (GrDraggable *) draggable_ptr->data; + + // gint point_type = draggable->point_type; + // gint point_i = draggable->point_i; + // bool fill_or_stroke = draggable->fill_or_stroke; + + // if( point_type == POINT_MG_CORNER ) { + + // //std::cout << "mesh_selection_changed: POINT_MG_CORNER: " << point_i << std::endl; + // // Now we must create or destroy corresponding handles. + + // if( g_list_find( drag->selected, dragger_ptr->data ) ) { + // //std::cout << "gradient_selection_changed: Selected: " << point_i << std::endl; + // // Which meshes does this point belong to? + + // } else { + // //std::cout << "mesh_selection_changed: Not Selected: " << point_i << std::endl; + // } + // } + + // draggable_ptr = draggable_ptr->next; + + // } + + // dragger_ptr = dragger_ptr->next; + // } +} + +void MeshTool::setup() { + ToolBase::setup(); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/tools/mesh/selcue", true)) { + this->enableSelectionCue(); + } + + this->enableGrDrag(); + Inkscape::Selection *selection = sp_desktop_selection(this->desktop); + + this->selcon = new sigc::connection(selection->connectChanged( + sigc::mem_fun(this, &MeshTool::selection_changed) + )); + + this->subselcon = new sigc::connection(this->desktop->connectToolSubselectionChanged( + sigc::hide(sigc::bind( + sigc::mem_fun(*this, &MeshTool::selection_changed), + (Inkscape::Selection*)NULL) + ) + )); + + this->selection_changed(selection); +} + +void +sp_mesh_context_select_next (ToolBase *event_context) +{ + GrDrag *drag = event_context->_grdrag; + g_assert (drag); + + GrDragger *d = drag->select_next(); + + event_context->desktop->scroll_to_point(d->point, 1.0); +} + +void +sp_mesh_context_select_prev (ToolBase *event_context) +{ + GrDrag *drag = event_context->_grdrag; + g_assert (drag); + + GrDragger *d = drag->select_prev(); + + event_context->desktop->scroll_to_point(d->point, 1.0); +} + +/** +Returns true if mouse cursor over mesh edge. +*/ +static bool +sp_mesh_context_is_over_line (MeshTool *rc, SPItem *item, Geom::Point event_p) +{ + SPDesktop *desktop = SP_EVENT_CONTEXT (rc)->desktop; + + //Translate mouse point into proper coord system + rc->mousepoint_doc = desktop->w2d(event_p); + + SPCtrlCurve *curve = SP_CTRLCURVE(item); + Geom::BezierCurveN<3> b( curve->p0, curve->p1, curve->p2, curve->p3 ); + Geom::Coord coord = b.nearestPoint( rc->mousepoint_doc ); // Coord == double + Geom::Point nearest = b( coord ); + + double dist_screen = Geom::L2 (rc->mousepoint_doc - nearest) * desktop->current_zoom(); + + double tolerance = (double) SP_EVENT_CONTEXT(rc)->tolerance; + + bool close = (dist_screen < tolerance); + + return close; +} + + +/** +Split row/column near the mouse point. +*/ +static void sp_mesh_context_split_near_point(MeshTool *rc, SPItem *item, Geom::Point mouse_p, guint32 /*etime*/) +{ + +#ifdef DEBUG_MESH + std::cout << "sp_mesh_context_split_near_point: entrance: " << mouse_p << std::endl; +#endif + + // item is the selected item. mouse_p the location in doc coordinates of where to add the stop + + ToolBase *ec = SP_EVENT_CONTEXT(rc); + SPDesktop *desktop = SP_EVENT_CONTEXT (rc)->desktop; + + double tolerance = (double) ec->tolerance; + + ec->get_drag()->addStopNearPoint (item, mouse_p, tolerance/desktop->current_zoom()); + + DocumentUndo::done(sp_desktop_document (desktop), SP_VERB_CONTEXT_MESH, + _("Split mesh row/column")); + + ec->get_drag()->updateDraggers(); +} + +/** +Wrapper for various mesh operations that require a list of selected corner nodes. + */ +static void +sp_mesh_context_corner_operation (MeshTool *rc, MeshCornerOperation operation ) +{ + +#ifdef DEBUG_MESH + std::cout << "sp_mesh_corner_operation: entrance: " << operation << std::endl; +#endif + + SPDocument *doc = NULL; + GrDrag *drag = rc->_grdrag; + + std::map<SPMeshGradient*, std::vector<guint> > points; + std::map<SPMeshGradient*, SPItem*> items; + + // Get list of selected draggers for each mesh. + // For all selected draggers + for (GList *i = drag->selected; i != NULL; i = i->next) { + GrDragger *dragger = (GrDragger *) i->data; + // For all draggables of dragger + for (GSList const* j = dragger->draggables; j != NULL; j = j->next) { + GrDraggable *d = (GrDraggable *) j->data; + + // Only mesh corners + if( d->point_type != POINT_MG_CORNER ) continue; + + // Find the gradient + SPMeshGradient *gradient = SP_MESHGRADIENT( getGradient (d->item, d->fill_or_stroke) ); + + // Collect points together for same gradient + points[gradient].push_back( d->point_i ); + items[gradient] = d->item; + } + } + + // Loop over meshes. + for( std::map<SPMeshGradient*, std::vector<guint> >::const_iterator iter = points.begin(); iter != points.end(); ++iter) { + SPMeshGradient *mg = SP_MESHGRADIENT( iter->first ); + if( iter->second.size() > 0 ) { + guint noperation = 0; + switch (operation) { + + case MG_CORNER_SIDE_TOGGLE: + // std::cout << "SIDE_TOGGLE" << std::endl; + noperation += mg->array.side_toggle( iter->second ); + break; + + case MG_CORNER_SIDE_ARC: + // std::cout << "SIDE_ARC" << std::endl; + noperation += mg->array.side_arc( iter->second ); + break; + + case MG_CORNER_TENSOR_TOGGLE: + // std::cout << "TENSOR_TOGGLE" << std::endl; + noperation += mg->array.tensor_toggle( iter->second ); + break; + + case MG_CORNER_COLOR_SMOOTH: + // std::cout << "COLOR_SMOOTH" << std::endl; + noperation += mg->array.color_smooth( iter->second ); + break; + + case MG_CORNER_COLOR_PICK: + // std::cout << "COLOR_PICK" << std::endl; + noperation += mg->array.color_pick( iter->second, items[iter->first] ); + break; + + default: + std::cout << "sp_mesh_corner_operation: unknown operation" << std::endl; + } + + if( noperation > 0 ) { + mg->array.write( mg ); + mg->requestModified(SP_OBJECT_MODIFIED_FLAG); + doc = mg->document; + + switch (operation) { + + case MG_CORNER_SIDE_TOGGLE: + DocumentUndo::done(doc, SP_VERB_CONTEXT_MESH, _("Toggled mesh path type.")); + break; + + case MG_CORNER_SIDE_ARC: + DocumentUndo::done(doc, SP_VERB_CONTEXT_MESH, _("Approximated arc for mesh side.")); + break; + + case MG_CORNER_TENSOR_TOGGLE: + DocumentUndo::done(doc, SP_VERB_CONTEXT_MESH, _("Toggled mesh tensors.")); + break; + + case MG_CORNER_COLOR_SMOOTH: + DocumentUndo::done(doc, SP_VERB_CONTEXT_MESH, _("Smoothed mesh corner color.")); + break; + + case MG_CORNER_COLOR_PICK: + DocumentUndo::done(doc, SP_VERB_CONTEXT_MESH, _("Picked mesh corner color.")); + break; + + default: + std::cout << "sp_mesh_corner_operation: unknown operation" << std::endl; + } + } + } + } + drag->updateDraggers(); + +} + + +/** +Handles all keyboard and mouse input for meshs. +*/ +bool MeshTool::root_handler(GdkEvent* event) { + static bool dragging; + + Inkscape::Selection *selection = sp_desktop_selection (desktop); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + this->tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + double const nudge = prefs->getDoubleLimited("/options/nudgedistance/value", 2, 0, 1000, "px"); // in px + + GrDrag *drag = this->_grdrag; + g_assert (drag); + + gint ret = FALSE; + + switch (event->type) { + case GDK_2BUTTON_PRESS: + +#ifdef DEBUG_MESH + std::cout << "sp_mesh_context_root_handler: GDK_2BUTTON_PRESS" << std::endl; +#endif + + // Double click: + // If over a mesh line, divide mesh row/column + // If not over a line, create new gradients for selected objects. + + if ( event->button.button == 1 ) { + // Are we over a mesh line? + bool over_line = false; + SPCtrlCurve *line = NULL; + + if (drag->lines) { + for (GSList *l = drag->lines; (l != NULL) && (!over_line); l = l->next) { + line = (SPCtrlCurve*) l->data; + over_line |= sp_mesh_context_is_over_line (this, (SPItem*) line, Geom::Point(event->motion.x, event->motion.y)); + } + } + + if (over_line) { + // We take the first item in selection, because with doubleclick, the first click + // always resets selection to the single object under cursor + sp_mesh_context_split_near_point(this, SP_ITEM(selection->itemList()->data), this->mousepoint_doc, event->button.time); + } else { + // Create a new gradient with default coordinates. + for (GSList const* i = selection->itemList(); i != NULL; i = i->next) { + SPItem *item = SP_ITEM(i->data); + SPGradientType new_type = SP_GRADIENT_TYPE_MESH; + Inkscape::PaintTarget fsmode = (prefs->getInt("/tools/gradient/newfillorstroke", 1) != 0) ? Inkscape::FOR_FILL : Inkscape::FOR_STROKE; + +#ifdef DEBUG_MESH + std::cout << "sp_mesh_context_root_handler: creating new mesh on: " << (fsmode == Inkscape::FOR_FILL ? "Fill" : "Stroke") << std::endl; +#endif + SPGradient *vector = sp_gradient_vector_for_object(sp_desktop_document(desktop), desktop, item, fsmode); + + SPGradient *priv = sp_item_set_gradient(item, vector, new_type, fsmode); + sp_gradient_reset_to_userspace(priv, item); + } + + DocumentUndo::done(sp_desktop_document (desktop), SP_VERB_CONTEXT_MESH, + _("Create default mesh")); + } + + ret = TRUE; + } + break; + + case GDK_BUTTON_PRESS: + +#ifdef DEBUG_MESH + std::cout << "sp_mesh_context_root_handler: GDK_BUTTON_PRESS" << std::endl; +#endif + // Button down + // If Shift key down: do rubber band selection + // Else set origin for drag. A drag creates a new gradient if one does not exist + if ( event->button.button == 1 && !this->space_panning ) { + Geom::Point button_w(event->button.x, event->button.y); + + // save drag origin + this->xp = (gint) button_w[Geom::X]; + this->yp = (gint) button_w[Geom::Y]; + this->within_tolerance = true; + + dragging = true; + + Geom::Point button_dt = desktop->w2d(button_w); + if (event->button.state & GDK_SHIFT_MASK) { + Inkscape::Rubberband::get(desktop)->start(desktop, button_dt); + } else { + // remember clicked item, disregarding groups, honoring Alt; do nothing with Crtl to + // enable Ctrl+doubleclick of exactly the selected item(s) + if (!(event->button.state & GDK_CONTROL_MASK)) { + this->item_to_select = sp_event_context_find_item (desktop, button_w, event->button.state & GDK_MOD1_MASK, TRUE); + } + + if (!selection->isEmpty()) { + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + m.freeSnapReturnByRef(button_dt, Inkscape::SNAPSOURCE_NODE_HANDLE); + m.unSetup(); + } + + this->origin = button_dt; + } + + ret = TRUE; + } + break; + + case GDK_MOTION_NOTIFY: + // Mouse move + if ( dragging && ( event->motion.state & GDK_BUTTON1_MASK ) && !this->space_panning ) { + +#ifdef DEBUG_MESH + std::cout << "sp_mesh_context_root_handler: GDK_MOTION_NOTIFY: Dragging" << std::endl; +#endif + if ( this->within_tolerance + && ( abs( (gint) event->motion.x - this->xp ) < this->tolerance ) + && ( abs( (gint) event->motion.y - this->yp ) < this->tolerance ) ) { + break; // do not drag if we're within tolerance from origin + } + // Once the user has moved farther than tolerance from the original location + // (indicating they intend to draw, not click), then always process the + // motion notify coordinates as given (no snapping back to origin) + this->within_tolerance = false; + + Geom::Point const motion_w(event->motion.x, + event->motion.y); + Geom::Point const motion_dt = this->desktop->w2d(motion_w); + + if (Inkscape::Rubberband::get(desktop)->is_started()) { + Inkscape::Rubberband::get(desktop)->move(motion_dt); + this->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Draw around</b> handles to select them")); + } else { + // Create new gradient with coordinates determined by drag. + sp_mesh_drag(*this, motion_dt, event->motion.state, event->motion.time); + } + + gobble_motion_events(GDK_BUTTON1_MASK); + + ret = TRUE; + } else { + // Not dragging + + // Do snapping + if (!drag->mouseOver() && !selection->isEmpty()) { + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point const motion_dt = this->desktop->w2d(motion_w); + + m.preSnap(Inkscape::SnapCandidatePoint(motion_dt, Inkscape::SNAPSOURCE_OTHER_HANDLE)); + m.unSetup(); + } + + // Highlight corner node corresponding to side or tensor node + if( drag->mouseOver() ) { + // MESH FIXME: Light up corresponding corner node corresponding to node we are over. + // See "pathflash" in ui/tools/node-tool.cpp for ideas. + // Use desktop->add_temporary_canvasitem( SPCanvasItem, milliseconds ); + } + + // Change cursor shape if over line + bool over_line = false; + + if (drag->lines) { + for (GSList *l = drag->lines; l != NULL; l = l->next) { + over_line |= sp_mesh_context_is_over_line (this, (SPItem*) l->data, Geom::Point(event->motion.x, event->motion.y)); + } + } + + if (this->cursor_addnode && !over_line) { + this->cursor_shape = cursor_gradient_xpm; + this->sp_event_context_update_cursor(); + this->cursor_addnode = false; + } else if (!this->cursor_addnode && over_line) { + this->cursor_shape = cursor_gradient_add_xpm; + this->sp_event_context_update_cursor(); + this->cursor_addnode = true; + } + } + break; + + case GDK_BUTTON_RELEASE: + +#ifdef DEBUG_MESH + std::cout << "sp_mesh_context_root_handler: GDK_BUTTON_RELEASE" << std::endl; +#endif + + this->xp = this->yp = 0; + + if ( event->button.button == 1 && !this->space_panning ) { + // Check if over line + bool over_line = false; + SPCtrlLine *line = NULL; + + if (drag->lines) { + for (GSList *l = drag->lines; (l != NULL) && (!over_line); l = l->next) { + line = (SPCtrlLine*) l->data; + over_line = sp_mesh_context_is_over_line (this, (SPItem*) line, Geom::Point(event->motion.x, event->motion.y)); + + if (over_line) { + break; + } + } + } + + if ( (event->button.state & GDK_CONTROL_MASK) && (event->button.state & GDK_MOD1_MASK ) ) { + if (over_line && line) { + sp_mesh_context_split_near_point(this, line->item, this->mousepoint_doc, 0); + ret = TRUE; + } + } else { + dragging = false; + + // unless clicked with Ctrl (to enable Ctrl+doubleclick). + if (event->button.state & GDK_CONTROL_MASK) { + ret = TRUE; + break; + } + + if (!this->within_tolerance) { + // we've been dragging, either do nothing (grdrag handles that), + // or rubberband-select if we have rubberband + Inkscape::Rubberband *r = Inkscape::Rubberband::get(desktop); + + if (r->is_started() && !this->within_tolerance) { + // this was a rubberband drag + if (r->getMode() == RUBBERBAND_MODE_RECT) { + Geom::OptRect const b = r->getRectangle(); + drag->selectRect(*b); + } + } + } else if (this->item_to_select) { + if (over_line && line) { + // Clicked on an existing mesh line, don't change selection. This stops + // possible change in selection during a double click with overlapping objects + } else { + // no dragging, select clicked item if any + if (event->button.state & GDK_SHIFT_MASK) { + selection->toggle(this->item_to_select); + } else { + selection->set(this->item_to_select); + } + } + } else { + // click in an empty space; do the same as Esc + if (drag->selected) { + drag->deselectAll(); + } else { + selection->clear(); + } + } + + this->item_to_select = NULL; + ret = TRUE; + } + + Inkscape::Rubberband::get(desktop)->stop(); + } + break; + + case GDK_KEY_PRESS: + +#ifdef DEBUG_MESH + std::cout << "sp_mesh_context_root_handler: GDK_KEY_PRESS" << std::endl; +#endif + + // FIXME: tip + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + case GDK_KEY_Meta_L: // Meta is when you press Shift+Alt (at least on my machine) + case GDK_KEY_Meta_R: + sp_event_show_modifier_tip (this->defaultMessageContext(), event, + _("FIXME<b>Ctrl</b>: snap mesh angle"), + _("FIXME<b>Shift</b>: draw mesh around the starting point"), + NULL); + break; + + case GDK_KEY_A: + case GDK_KEY_a: + if (MOD__CTRL_ONLY(event) && drag->isNonEmpty()) { + drag->selectAll(); + ret = TRUE; + } + break; + + case GDK_KEY_Escape: + if (drag->selected) { + drag->deselectAll(); + } else { + selection->clear(); + } + + ret = TRUE; + //TODO: make dragging escapable by Esc + break; + + case GDK_KEY_Left: // move handle left + case GDK_KEY_KP_Left: + case GDK_KEY_KP_4: + if (!MOD__CTRL(event)) { // not ctrl + gint mul = 1 + gobble_key_events(get_group0_keyval(&event->key), 0); // with any mask + + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) { + drag->selected_move_screen(mul*-10, 0); // shift + } else { + drag->selected_move_screen(mul*-1, 0); // no shift + } + } else { // no alt + if (MOD__SHIFT(event)) { + drag->selected_move(mul*-10*nudge, 0); // shift + } else { + drag->selected_move(mul*-nudge, 0); // no shift + } + } + + ret = TRUE; + } + break; + + case GDK_KEY_Up: // move handle up + case GDK_KEY_KP_Up: + case GDK_KEY_KP_8: + if (!MOD__CTRL(event)) { // not ctrl + gint mul = 1 + gobble_key_events(get_group0_keyval(&event->key), 0); // with any mask + + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) { + drag->selected_move_screen(0, mul*10); // shift + } else { + drag->selected_move_screen(0, mul*1); // no shift + } + } else { // no alt + if (MOD__SHIFT(event)) { + drag->selected_move(0, mul*10*nudge); // shift + } else { + drag->selected_move(0, mul*nudge); // no shift + } + } + + ret = TRUE; + } + break; + + case GDK_KEY_Right: // move handle right + case GDK_KEY_KP_Right: + case GDK_KEY_KP_6: + if (!MOD__CTRL(event)) { // not ctrl + gint mul = 1 + gobble_key_events(get_group0_keyval(&event->key), 0); // with any mask + + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) { + drag->selected_move_screen(mul*10, 0); // shift + } else { + drag->selected_move_screen(mul*1, 0); // no shift + } + } else { // no alt + if (MOD__SHIFT(event)) { + drag->selected_move(mul*10*nudge, 0); // shift + } else { + drag->selected_move(mul*nudge, 0); // no shift + } + } + + ret = TRUE; + } + break; + + case GDK_KEY_Down: // move handle down + case GDK_KEY_KP_Down: + case GDK_KEY_KP_2: + if (!MOD__CTRL(event)) { // not ctrl + gint mul = 1 + gobble_key_events(get_group0_keyval(&event->key), 0); // with any mask + + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) { + drag->selected_move_screen(0, mul*-10); // shift + } else { + drag->selected_move_screen(0, mul*-1); // no shift + } + } else { // no alt + if (MOD__SHIFT(event)) { + drag->selected_move(0, mul*-10*nudge); // shift + } else { + drag->selected_move(0, mul*-nudge); // no shift + } + } + + ret = TRUE; + } + break; + + case GDK_KEY_Insert: + case GDK_KEY_KP_Insert: + // with any modifiers: + //sp_gradient_context_add_stops_between_selected_stops (rc); + std::cout << "Inserting stops between selected stops not implemented yet" << std::endl; + ret = TRUE; + break; + + case GDK_KEY_Delete: + case GDK_KEY_KP_Delete: + case GDK_KEY_BackSpace: + if ( drag->selected ) { + std::cout << "Deleting mesh stops not implemented yet" << std::endl; + ret = TRUE; + } + break; + + // Mesh Operations -------------------------------------------- + + case GDK_KEY_b: // Toggle mesh side between lineto and curveto. + case GDK_KEY_B: + if (MOD__ALT(event) && drag->isNonEmpty() && drag->hasSelection()) { + sp_mesh_context_corner_operation ( this, MG_CORNER_SIDE_TOGGLE ); + ret = TRUE; + } + break; + + case GDK_KEY_c: // Convert mesh side from generic Bezier to Bezier approximating arc, + case GDK_KEY_C: // preserving handle direction. + if (MOD__ALT(event) && drag->isNonEmpty() && drag->hasSelection()) { + sp_mesh_context_corner_operation ( this, MG_CORNER_SIDE_ARC ); + ret = TRUE; + } + break; + + case GDK_KEY_g: // Toggle mesh tensor points on/off + case GDK_KEY_G: + if (MOD__ALT(event) && drag->isNonEmpty() && drag->hasSelection()) { + sp_mesh_context_corner_operation ( this, MG_CORNER_TENSOR_TOGGLE ); + ret = TRUE; + } + break; + + case GDK_KEY_j: // Smooth corner color + case GDK_KEY_J: + if (MOD__ALT(event) && drag->isNonEmpty() && drag->hasSelection()) { + sp_mesh_context_corner_operation ( this, MG_CORNER_COLOR_SMOOTH ); + ret = TRUE; + } + break; + + case GDK_KEY_k: // Pick corner color + case GDK_KEY_K: + if (MOD__ALT(event) && drag->isNonEmpty() && drag->hasSelection()) { + sp_mesh_context_corner_operation ( this, MG_CORNER_COLOR_PICK ); + ret = TRUE; + } + break; + + default: + break; + } + + break; + + case GDK_KEY_RELEASE: + +#ifdef DEBUG_MESH + std::cout << "sp_mesh_context_root_handler: GDK_KEY_RELEASE" << std::endl; +#endif + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + case GDK_KEY_Meta_L: // Meta is when you press Shift+Alt + case GDK_KEY_Meta_R: + this->defaultMessageContext()->clear(); + break; + default: + break; + } + break; + default: + break; + } + + if (!ret) { + ret = ToolBase::root_handler(event); + } + + return ret; +} + +static void sp_mesh_drag(MeshTool &rc, Geom::Point const /*pt*/, guint /*state*/, guint32 /*etime*/) { + SPDesktop *desktop = SP_EVENT_CONTEXT(&rc)->desktop; + Inkscape::Selection *selection = sp_desktop_selection(desktop); + SPDocument *document = sp_desktop_document(desktop); + ToolBase *ec = SP_EVENT_CONTEXT(&rc); + + if (!selection->isEmpty()) { + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int type = SP_GRADIENT_TYPE_MESH; + Inkscape::PaintTarget fill_or_stroke = (prefs->getInt("/tools/gradient/newfillorstroke", 1) != 0) ? Inkscape::FOR_FILL : Inkscape::FOR_STROKE; + + SPGradient *vector; + if (ec->item_to_select) { + // pick color from the object where drag started + vector = sp_gradient_vector_for_object(document, desktop, ec->item_to_select, fill_or_stroke); + } else { + // Starting from empty space: + // Sort items so that the topmost comes last + GSList *items = g_slist_copy ((GSList *) selection->itemList()); + items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position); + // take topmost + vector = sp_gradient_vector_for_object(document, desktop, SP_ITEM(g_slist_last(items)->data), fill_or_stroke); + g_slist_free (items); + } + + // HACK: reset fill-opacity - that 0.75 is annoying; BUT remove this when we have an opacity slider for all tabs + SPCSSAttr *css = sp_repr_css_attr_new(); + sp_repr_css_set_property(css, "fill-opacity", "1.0"); + + for (GSList const *i = selection->itemList(); i != NULL; i = i->next) { + + //FIXME: see above + sp_repr_css_change_recursive(SP_OBJECT(i->data)->getRepr(), css, "style"); + + sp_item_set_gradient(SP_ITEM(i->data), vector, (SPGradientType) type, fill_or_stroke); + + // We don't need to do anything. Mesh is already sized appropriately. + + SP_OBJECT(i->data)->requestModified(SP_OBJECT_MODIFIED_FLAG); + } + // if (ec->_grdrag) { + // ec->_grdrag->updateDraggers(); + // // prevent regenerating draggers by selection modified signal, which sometimes + // // comes too late and thus destroys the knot which we will now grab: + // ec->_grdrag->local_change = true; + // // give the grab out-of-bounds values of xp/yp because we're already dragging + // // and therefore are already out of tolerance + // ec->_grdrag->grabKnot (SP_ITEM(selection->itemList()->data), + // type == SP_GRADIENT_TYPE_LINEAR? POINT_LG_END : POINT_RG_R1, + // -1, // ignore number (though it is always 1) + // fill_or_stroke, 99999, 99999, etime); + // } + // We did an undoable action, but SPDocumentUndo::done will be called by the knot when released + + // status text; we do not track coords because this branch is run once, not all the time + // during drag + int n_objects = g_slist_length((GSList *) selection->itemList()); + rc.message_context->setF(Inkscape::NORMAL_MESSAGE, + ngettext("<b>Gradient</b> for %d object; with <b>Ctrl</b> to snap angle", + "<b>Gradient</b> for %d objects; with <b>Ctrl</b> to snap angle", n_objects), + n_objects); + } else { + sp_desktop_message_stack(desktop)->flash(Inkscape::WARNING_MESSAGE, _("Select <b>objects</b> on which to create gradient.")); + } + +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/mesh-tool.h b/src/ui/tools/mesh-tool.h new file mode 100644 index 000000000..d952c9010 --- /dev/null +++ b/src/ui/tools/mesh-tool.h @@ -0,0 +1,77 @@ +#ifndef SEEN_SP_MESH_CONTEXT_H +#define SEEN_SP_MESH_CONTEXT_H + +/* + * Mesh drawing and editing tool + * + * Authors: + * bulia byak <buliabyak@users.sf.net> + * Johan Engelen <j.b.c.engelen@ewi.utwente.nl> + * Jon A. Cruz <jon@joncruz.org. + * Tavmjong Bah <tavmjong@free.fr> + * + * Copyright (C) 2012 Tavmjong Bah + * Copyright (C) 2007 Johan Engelen + * Copyright (C) 2005,2010 Authors + * + * Released under GNU GPL + */ + +#include <stddef.h> +#include <sigc++/sigc++.h> +#include "ui/tools/tool-base.h" + +#define SP_MESH_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::MeshTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_MESH_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::MeshTool*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +namespace Inkscape { +namespace UI { +namespace Tools { + +class MeshTool : public ToolBase { +public: + MeshTool(); + virtual ~MeshTool(); + + Geom::Point origin; + + bool cursor_addnode; + + bool node_added; + + Geom::Point mousepoint_doc; // stores mousepoint when over_line in doc coords + + sigc::connection *selcon; + sigc::connection *subselcon; + + static const std::string prefsPath; + + virtual void setup(); + virtual bool root_handler(GdkEvent* event); + + virtual const std::string& getPrefsPath(); + +private: + void selection_changed(Inkscape::Selection* sel); +}; + +void sp_mesh_context_select_next(ToolBase *event_context); +void sp_mesh_context_select_prev(ToolBase *event_context); + +} +} +} + +#endif // SEEN_SP_MESH_CONTEXT_H + + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/node-tool.cpp b/src/ui/tools/node-tool.cpp new file mode 100644 index 000000000..b1e11bd66 --- /dev/null +++ b/src/ui/tools/node-tool.cpp @@ -0,0 +1,702 @@ +/** + * @file + * New node tool - implementation. + */ +/* Authors: + * Krzysztof Kosiński <tweenk@gmail.com> + * Abhishek Sharma + * + * Copyright (C) 2009 Authors + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "ui/tool/curve-drag-point.h" +#include <glib/gi18n.h> +#include "desktop.h" +#include "desktop-handles.h" +#include "display/sp-canvas-group.h" +#include "display/canvas-bpath.h" +#include "display/curve.h" +#include "display/sp-canvas.h" +#include "document.h" +#include "live_effects/lpeobject.h" +#include "message-context.h" +#include "selection.h" +#include "shape-editor.h" // temporary! +#include "sp-clippath.h" +#include "sp-item-group.h" +#include "sp-mask.h" +#include "sp-object-group.h" +#include "sp-path.h" +#include "sp-text.h" +#include "ui/control-manager.h" +#include "ui/tools/node-tool.h" +#include "ui/tool/control-point-selection.h" +#include "ui/tool/event-utils.h" +#include "ui/tool/manipulator.h" +#include "ui/tool/multi-path-manipulator.h" +#include "ui/tool/path-manipulator.h" +#include "ui/tool/selector.h" +#include "ui/tool/shape-record.h" + +#include "pixmaps/cursor-node.xpm" +#include "pixmaps/cursor-node-d.xpm" +#include "selection-chemistry.h" + +#include <gdk/gdkkeysyms.h> + +/** @struct NodeTool + * + * Node tool event context. + * + * @par Architectural overview of the tool + * @par + * Here's a breakdown of what each object does. + * - Handle: shows a handle and keeps the node type constraint (smooth / symmetric) by updating + * the other handle's position when dragged. Its move() method cannot violate the constraints. + * - Node: keeps node type constraints for auto nodes and smooth nodes at ends of linear segments. + * Its move() method cannot violate constraints. Handles linear grow and dispatches spatial grow + * to MultiPathManipulator. Keeps a reference to its NodeList. + * - NodeList: exposes an iterator-based interface to nodes. It is possible to obtain an iterator + * to a node from the node. Keeps a reference to its SubpathList. + * - SubpathList: list of NodeLists that represents an editable pathvector. Keeps a reference + * to its PathManipulator. + * - PathManipulator: performs most of the single-path actions like reverse subpaths, + * delete segment, shift selection, etc. Keeps a reference to MultiPathManipulator. + * - MultiPathManipulator: performs additional operations for actions that are not per-path, + * for example node joins and segment joins. Tracks the control transforms for PMs that edit + * clipping paths and masks. It is more or less equivalent to ShapeEditor and in the future + * it might handle all shapes. Handles XML commit of actions that affect all paths or + * the node selection and removes PathManipulators that have no nodes left after e.g. node + * deletes. + * - ControlPointSelection: keeps track of node selection and a set of nodes that can potentially + * be selected. There can be more than one selection. Performs actions that require no + * knowledge about the path, only about the nodes, like dragging and transforms. It is not + * specific to nodes and can accomodate any control point derived from SelectableControlPoint. + * Transforms nodes in response to transform handle events. + * - TransformHandleSet: displays nodeset transform handles and emits transform events. The aim + * is to eventually use a common class for object and control point transforms. + * - SelectableControlPoint: base for any type of selectable point. It can belong to only one + * selection. + * + * @par Functionality that resides in weird places + * @par + * + * This list is probably incomplete. + * - Curve dragging: CurveDragPoint, controlled by PathManipulator + * - Single handle shortcuts: MultiPathManipulator::event(), ModifierTracker + * - Linear and spatial grow: Node, spatial grow routed to ControlPointSelection + * - Committing handle actions performed with the mouse: PathManipulator + * - Sculpting: ControlPointSelection + * + * @par Plans for the future + * @par + * - MultiPathManipulator should become a generic shape editor that manages all active manipulator, + * more or less like the old ShapeEditor. + * - Knotholder should be rewritten into one manipulator class per shape, using the control point + * classes. Interesting features like dragging rectangle sides could be added along the way. + * - Better handling of clip and mask editing, particularly in response to undo. + * - High level refactoring of the event context hierarchy. All aspects of tools, like toolbox + * controls, icons, event handling should be collected in one class, though each aspect + * of a tool might be in an separate class for better modularity. The long term goal is to allow + * tools to be defined in extensions or shared library plugins. + */ + +using Inkscape::ControlManager; + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +namespace { + ToolBase* createNodesContext() { + return new NodeTool(); + } + + bool nodesContextRegistered = ToolFactory::instance().registerObject("/tools/nodes", createNodesContext); +} + +const std::string& NodeTool::getPrefsPath() { + return NodeTool::prefsPath; +} + +const std::string NodeTool::prefsPath = "/tools/nodes"; + +SPCanvasGroup *create_control_group(SPDesktop *d); + +NodeTool::NodeTool() + : ToolBase(cursor_node_xpm, 1, 1) + , _selected_nodes(NULL) + , _multipath(NULL) + , edit_clipping_paths(false) + , edit_masks(false) + , flashed_item(NULL) + , flash_tempitem(NULL) + , _selector(NULL) + , _path_data(NULL) + , _transform_handle_group(NULL) + , _last_over(NULL) + , cursor_drag(false) + , show_handles(false) + , show_outline(false) + , live_outline(false) + , live_objects(false) + , show_path_direction(false) + , show_transform_handles(false) + , single_node_transform_handles(false) +{ +} + +SPCanvasGroup *create_control_group(SPDesktop *d) +{ + return reinterpret_cast<SPCanvasGroup*>(sp_canvas_item_new( + sp_desktop_controls(d), SP_TYPE_CANVAS_GROUP, NULL)); +} + +void destroy_group(SPCanvasGroup *g) +{ + sp_canvas_item_destroy(SP_CANVAS_ITEM(g)); +} + +NodeTool::~NodeTool() { + this->enableGrDrag(false); + + if (this->flash_tempitem) { + this->desktop->remove_temporary_canvasitem(this->flash_tempitem); + } + + this->_selection_changed_connection.disconnect(); + //this->_selection_modified_connection.disconnect(); + this->_mouseover_changed_connection.disconnect(); + this->_sizeUpdatedConn.disconnect(); + + delete this->_multipath; + delete this->_selected_nodes; + delete this->_selector; + + Inkscape::UI::PathSharedData &data = *this->_path_data; + destroy_group(data.node_data.node_group); + destroy_group(data.node_data.handle_group); + destroy_group(data.node_data.handle_line_group); + destroy_group(data.outline_group); + destroy_group(data.dragpoint_group); + destroy_group(this->_transform_handle_group); +} + +void NodeTool::setup() { + ToolBase::setup(); + + this->_path_data = new Inkscape::UI::PathSharedData(); + + Inkscape::UI::PathSharedData &data = *this->_path_data; + data.node_data.desktop = this->desktop; + + // selector has to be created here, so that its hidden control point is on the bottom + this->_selector = new Inkscape::UI::Selector(this->desktop); + + // Prepare canvas groups for controls. This guarantees correct z-order, so that + // for example a dragpoint won't obscure a node + data.outline_group = create_control_group(this->desktop); + data.node_data.handle_line_group = create_control_group(this->desktop); + data.dragpoint_group = create_control_group(this->desktop); + this->_transform_handle_group = create_control_group(this->desktop); + data.node_data.node_group = create_control_group(this->desktop); + data.node_data.handle_group = create_control_group(this->desktop); + + Inkscape::Selection *selection = sp_desktop_selection (this->desktop); + + this->_selection_changed_connection.disconnect(); + this->_selection_changed_connection = + selection->connectChanged(sigc::mem_fun(this, &NodeTool::selection_changed)); + + this->_mouseover_changed_connection.disconnect(); + this->_mouseover_changed_connection = + Inkscape::UI::ControlPoint::signal_mouseover_change.connect(sigc::mem_fun(this, &NodeTool::mouseover_changed)); + + this->_sizeUpdatedConn = ControlManager::getManager().connectCtrlSizeChanged( + sigc::mem_fun(this, &NodeTool::handleControlUiStyleChange) + ); + + this->_selected_nodes = new Inkscape::UI::ControlPointSelection(this->desktop, this->_transform_handle_group); + + data.node_data.selection = this->_selected_nodes; + + this->_multipath = new Inkscape::UI::MultiPathManipulator(data, this->_selection_changed_connection); + + this->_selector->signal_point.connect(sigc::mem_fun(this, &NodeTool::select_point)); + this->_selector->signal_area.connect(sigc::mem_fun(this, &NodeTool::select_area)); + + this->_multipath->signal_coords_changed.connect( + sigc::bind( + sigc::mem_fun(*this->desktop, &SPDesktop::emitToolSubselectionChanged), + (void*)NULL + ) + ); + + this->_selected_nodes->signal_point_changed.connect( + // Hide both signal parameters and bind the function parameter to 0 + // sigc::signal<void, SelectableControlPoint *, bool> + // <=> + // void update_tip(GdkEvent *event) + sigc::hide(sigc::hide(sigc::bind( + sigc::mem_fun(this, &NodeTool::update_tip), + (GdkEvent*)NULL + ))) + ); + + this->cursor_drag = false; + this->show_transform_handles = true; + this->single_node_transform_handles = false; + this->flash_tempitem = NULL; + this->flashed_item = NULL; + this->_last_over = NULL; + + // read prefs before adding items to selection to prevent momentarily showing the outline + sp_event_context_read(this, "show_handles"); + sp_event_context_read(this, "show_outline"); + sp_event_context_read(this, "live_outline"); + sp_event_context_read(this, "live_objects"); + sp_event_context_read(this, "show_path_direction"); + sp_event_context_read(this, "show_transform_handles"); + sp_event_context_read(this, "single_node_transform_handles"); + sp_event_context_read(this, "edit_clipping_paths"); + sp_event_context_read(this, "edit_masks"); + + this->selection_changed(selection); + this->update_tip(NULL); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + if (prefs->getBool("/tools/nodes/selcue")) { + this->enableSelectionCue(); + } + + if (prefs->getBool("/tools/nodes/gradientdrag")) { + this->enableGrDrag(); + } + + this->desktop->emitToolSubselectionChanged(NULL); // sets the coord entry fields to inactive +} + +void NodeTool::set(const Inkscape::Preferences::Entry& value) { + Glib::ustring entry_name = value.getEntryName(); + + if (entry_name == "show_handles") { + this->show_handles = value.getBool(true); + this->_multipath->showHandles(this->show_handles); + } else if (entry_name == "show_outline") { + this->show_outline = value.getBool(); + this->_multipath->showOutline(this->show_outline); + } else if (entry_name == "live_outline") { + this->live_outline = value.getBool(); + this->_multipath->setLiveOutline(this->live_outline); + } else if (entry_name == "live_objects") { + this->live_objects = value.getBool(); + this->_multipath->setLiveObjects(this->live_objects); + } else if (entry_name == "show_path_direction") { + this->show_path_direction = value.getBool(); + this->_multipath->showPathDirection(this->show_path_direction); + } else if (entry_name == "show_transform_handles") { + this->show_transform_handles = value.getBool(true); + this->_selected_nodes->showTransformHandles( + this->show_transform_handles, this->single_node_transform_handles); + } else if (entry_name == "single_node_transform_handles") { + this->single_node_transform_handles = value.getBool(); + this->_selected_nodes->showTransformHandles( + this->show_transform_handles, this->single_node_transform_handles); + } else if (entry_name == "edit_clipping_paths") { + this->edit_clipping_paths = value.getBool(); + this->selection_changed(this->desktop->selection); + } else if (entry_name == "edit_masks") { + this->edit_masks = value.getBool(); + this->selection_changed(this->desktop->selection); + } else { + ToolBase::set(value); + } +} + +/** Recursively collect ShapeRecords */ +void gather_items(NodeTool *nt, SPItem *base, SPObject *obj, Inkscape::UI::ShapeRole role, + std::set<Inkscape::UI::ShapeRecord> &s) +{ + using namespace Inkscape::UI; + + if (!obj) { + return; + } + + //XML Tree being used directly here while it shouldn't be. + if (SP_IS_PATH(obj) && obj->getRepr()->attribute("inkscape:original-d") != NULL) { + ShapeRecord r; + r.item = static_cast<SPItem*>(obj); + r.edit_transform = Geom::identity(); // TODO wrong? + r.role = role; + s.insert(r); + } else if (role != SHAPE_ROLE_NORMAL && (SP_IS_GROUP(obj) || SP_IS_OBJECTGROUP(obj))) { + for (SPObject *c = obj->children; c; c = c->next) { + gather_items(nt, base, c, role, s); + } + } else if (SP_IS_ITEM(obj)) { + SPItem *item = static_cast<SPItem*>(obj); + ShapeRecord r; + r.item = item; + // TODO add support for objectBoundingBox + r.edit_transform = base ? base->i2doc_affine() : Geom::identity(); + r.role = role; + + if (s.insert(r).second) { + // this item was encountered the first time + if (nt->edit_clipping_paths && item->clip_ref) { + gather_items(nt, item, item->clip_ref->getObject(), SHAPE_ROLE_CLIPPING_PATH, s); + } + + if (nt->edit_masks && item->mask_ref) { + gather_items(nt, item, item->mask_ref->getObject(), SHAPE_ROLE_MASK, s); + } + } + } +} + +void NodeTool::selection_changed(Inkscape::Selection *sel) { + using namespace Inkscape::UI; + + std::set<ShapeRecord> shapes; + + GSList const *ilist = sel->itemList(); + + for (GSList *i = const_cast<GSList*>(ilist); i; i = i->next) { + SPObject *obj = static_cast<SPObject*>(i->data); + + if (SP_IS_ITEM(obj)) { + gather_items(this, NULL, static_cast<SPItem*>(obj), SHAPE_ROLE_NORMAL, shapes); + } + } + + // use multiple ShapeEditors for now, to allow editing many shapes at once + // needs to be rethought + for (boost::ptr_map<SPItem*, ShapeEditor>::iterator i = this->_shape_editors.begin(); + i != this->_shape_editors.end(); ) + { + ShapeRecord s; + s.item = i->first; + + if (shapes.find(s) == shapes.end()) { + this->_shape_editors.erase(i++); + } else { + ++i; + } + } + + for (std::set<ShapeRecord>::iterator i = shapes.begin(); i != shapes.end(); ++i) { + ShapeRecord const &r = *i; + + if ((SP_IS_SHAPE(r.item) || SP_IS_TEXT(r.item)) && + this->_shape_editors.find(r.item) == this->_shape_editors.end()) + { + ShapeEditor *si = new ShapeEditor(this->desktop); + si->set_item(r.item, SH_KNOTHOLDER); + this->_shape_editors.insert(const_cast<SPItem*&>(r.item), si); + } + } + + this->_multipath->setItems(shapes); + this->update_tip(NULL); + this->desktop->updateNow(); +} + +bool NodeTool::root_handler(GdkEvent* event) { + /* things to handle here: + * 1. selection of items + * 2. passing events to manipulators + * 3. some keybindings + */ + using namespace Inkscape::UI; // pull in event helpers + + Inkscape::Selection *selection = desktop->selection; + static Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + if (this->_multipath->event(this, event)) { + return true; + } + + if (this->_selector->event(this, event)) { + return true; + } + + if (this->_selected_nodes->event(this, event)) { + return true; + } + + switch (event->type) + { + case GDK_MOTION_NOTIFY: { + combine_motion_events(desktop->canvas, event->motion, 0); + SPItem *over_item = sp_event_context_find_item (desktop, event_point(event->button), + FALSE, TRUE); + + if (over_item != this->_last_over) { + this->_last_over = over_item; + //ink_node_tool_update_tip(nt, event); + this->update_tip(event); + } + + // create pathflash outline + if (prefs->getBool("/tools/nodes/pathflash_enabled")) { + if (over_item == this->flashed_item) { + break; + } + + if (!prefs->getBool("/tools/nodes/pathflash_selected") && selection->includes(over_item)) { + break; + } + + if (this->flash_tempitem) { + desktop->remove_temporary_canvasitem(this->flash_tempitem); + this->flash_tempitem = NULL; + this->flashed_item = NULL; + } + + if (!SP_IS_SHAPE(over_item)) { + break; // for now, handle only shapes + } + + this->flashed_item = over_item; + SPCurve *c = SP_SHAPE(over_item)->getCurveBeforeLPE(); + + if (!c) { + break; // break out when curve doesn't exist + } + + c->transform(over_item->i2dt_affine()); + SPCanvasItem *flash = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), c); + + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(flash), + prefs->getInt("/tools/nodes/highlight_color", 0xff0000ff), 1.0, + SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + + sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(flash), 0, SP_WIND_RULE_NONZERO); + + this->flash_tempitem = desktop->add_temporary_canvasitem(flash, + prefs->getInt("/tools/nodes/pathflash_timeout", 500)); + + c->unref(); + } + } break; // do not return true, because we need to pass this event to the parent context + // otherwise some features cease to work + + case GDK_KEY_PRESS: + switch (get_group0_keyval(&event->key)) + { + case GDK_KEY_Escape: // deselect everything + if (this->_selected_nodes->empty()) { + Inkscape::SelectionHelper::selectNone(desktop); + } else { + this->_selected_nodes->clear(); + } + //ink_node_tool_update_tip(nt, event); + this->update_tip(event); + return TRUE; + + case GDK_KEY_a: + case GDK_KEY_A: + if (held_control(event->key) && held_alt(event->key)) { + this->_selected_nodes->selectAll(); + // Ctrl+A is handled in selection-chemistry.cpp via verb + //ink_node_tool_update_tip(nt, event); + this->update_tip(event); + return TRUE; + } + break; + + case GDK_KEY_h: + case GDK_KEY_H: + if (held_only_control(event->key)) { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + prefs->setBool("/tools/nodes/show_handles", !this->show_handles); + return TRUE; + } + break; + + default: + break; + } + //ink_node_tool_update_tip(nt, event); + this->update_tip(event); + break; + + case GDK_KEY_RELEASE: + //ink_node_tool_update_tip(nt, event); + this->update_tip(event); + break; + + default: + break; + } + + return ToolBase::root_handler(event); +} + +void NodeTool::update_tip(GdkEvent *event) { + using namespace Inkscape::UI; + + if (event && (event->type == GDK_KEY_PRESS || event->type == GDK_KEY_RELEASE)) { + unsigned new_state = state_after_event(event); + + if (new_state == event->key.state) { + return; + } + + if (state_held_shift(new_state)) { + if (this->_last_over) { + this->message_context->set(Inkscape::NORMAL_MESSAGE, + C_("Node tool tip", "<b>Shift</b>: drag to add nodes to the selection, " + "click to toggle object selection")); + } else { + this->message_context->set(Inkscape::NORMAL_MESSAGE, + C_("Node tool tip", "<b>Shift</b>: drag to add nodes to the selection")); + } + + return; + } + } + + unsigned sz = this->_selected_nodes->size(); + unsigned total = this->_selected_nodes->allPoints().size(); + + if (sz != 0) { + char *nodestring = g_strdup_printf( + ngettext("<b>%u of %u</b> node selected.", "<b>%u of %u</b> nodes selected.", total), + sz, total); + + if (this->_last_over) { + // TRANSLATORS: The %s below is where the "%u of %u nodes selected" sentence gets put + char *dyntip = g_strdup_printf(C_("Node tool tip", + "%s Drag to select nodes, click to edit only this object (more: Shift)"), + nodestring); + this->message_context->set(Inkscape::NORMAL_MESSAGE, dyntip); + g_free(dyntip); + } else { + char *dyntip = g_strdup_printf(C_("Node tool tip", + "%s Drag to select nodes, click clear the selection"), + nodestring); + this->message_context->set(Inkscape::NORMAL_MESSAGE, dyntip); + g_free(dyntip); + } + g_free(nodestring); + } else if (!this->_multipath->empty()) { + if (this->_last_over) { + this->message_context->set(Inkscape::NORMAL_MESSAGE, C_("Node tool tip", + "Drag to select nodes, click to edit only this object")); + } else { + this->message_context->set(Inkscape::NORMAL_MESSAGE, C_("Node tool tip", + "Drag to select nodes, click to clear the selection")); + } + } else { + if (this->_last_over) { + this->message_context->set(Inkscape::NORMAL_MESSAGE, C_("Node tool tip", + "Drag to select objects to edit, click to edit this object (more: Shift)")); + } else { + this->message_context->set(Inkscape::NORMAL_MESSAGE, C_("Node tool tip", + "Drag to select objects to edit")); + } + } +} + +void NodeTool::select_area(Geom::Rect const &sel, GdkEventButton *event) { + using namespace Inkscape::UI; + + if (this->_multipath->empty()) { + // if multipath is empty, select rubberbanded items rather than nodes + Inkscape::Selection *selection = this->desktop->selection; + GSList *items = sp_desktop_document(this->desktop)->getItemsInBox(this->desktop->dkey, sel); + selection->setList(items); + g_slist_free(items); + } else { + if (!held_shift(*event)) { + this->_selected_nodes->clear(); + } + + this->_selected_nodes->selectArea(sel); + } +} + +void NodeTool::select_point(Geom::Point const &/*sel*/, GdkEventButton *event) { + using namespace Inkscape::UI; // pull in event helpers + + if (!event) { + return; + } + + if (event->button != 1) { + return; + } + + Inkscape::Selection *selection = this->desktop->selection; + + SPItem *item_clicked = sp_event_context_find_item (this->desktop, event_point(*event), + (event->state & GDK_MOD1_MASK) && !(event->state & GDK_CONTROL_MASK), TRUE); + + if (item_clicked == NULL) { // nothing under cursor + // if no Shift, deselect + // if there are nodes selected, the first click should deselect the nodes + // and the second should deselect the items + if (!state_held_shift(event->state)) { + if (this->_selected_nodes->empty()) { + selection->clear(); + } else { + this->_selected_nodes->clear(); + } + } + } else { + if (held_shift(*event)) { + selection->toggle(item_clicked); + } else { + selection->set(item_clicked); + } + + this->desktop->updateNow(); + } +} + +void NodeTool::mouseover_changed(Inkscape::UI::ControlPoint *p) { + using Inkscape::UI::CurveDragPoint; + + CurveDragPoint *cdp = dynamic_cast<CurveDragPoint*>(p); + + if (cdp && !this->cursor_drag) { + this->cursor_shape = cursor_node_d_xpm; + this->hot_x = 1; + this->hot_y = 1; + this->sp_event_context_update_cursor(); + this->cursor_drag = true; + } else if (!cdp && this->cursor_drag) { + this->cursor_shape = cursor_node_xpm; + this->hot_x = 1; + this->hot_y = 1; + this->sp_event_context_update_cursor(); + this->cursor_drag = false; + } +} + +void NodeTool::handleControlUiStyleChange() { + this->_multipath->updateHandles(); +} + +} +} +} + +//} // anonymous namespace + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/node-tool.h b/src/ui/tools/node-tool.h new file mode 100644 index 000000000..4d15ab70e --- /dev/null +++ b/src/ui/tools/node-tool.h @@ -0,0 +1,105 @@ +/** @file + * @brief New node tool with support for multiple path editing + */ +/* Authors: + * Krzysztof Kosiński <tweenk@gmail.com> + * + * Copyright (C) 2009 Authors + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifndef SEEN_UI_TOOL_NODE_TOOL_H +#define SEEN_UI_TOOL_NODE_TOOL_H + +#include <boost/ptr_container/ptr_map.hpp> +#include <glib.h> +#include "ui/tools/tool-base.h" + +namespace Inkscape { + namespace Display { + class TemporaryItem; + } + + namespace UI { + class MultiPathManipulator; + class ControlPointSelection; + class Selector; + class ControlPoint; + + struct PathSharedData; + } +} + +#define INK_NODE_TOOL(obj) (dynamic_cast<Inkscape::UI::Tools::NodeTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define INK_IS_NODE_TOOL(obj) (dynamic_cast<const Inkscape::UI::Tools::NodeTool*>((const Inkscape::UI::Tools::ToolBase*)obj)) + +namespace Inkscape { +namespace UI { +namespace Tools { + +class NodeTool : public ToolBase { +public: + NodeTool(); + virtual ~NodeTool(); + + Inkscape::UI::ControlPointSelection* _selected_nodes; + Inkscape::UI::MultiPathManipulator* _multipath; + + bool edit_clipping_paths; + bool edit_masks; + + static const std::string prefsPath; + + virtual void setup(); + virtual void set(const Inkscape::Preferences::Entry& val); + virtual bool root_handler(GdkEvent* event); + + virtual const std::string& getPrefsPath(); + +private: + sigc::connection _selection_changed_connection; + sigc::connection _mouseover_changed_connection; + sigc::connection _sizeUpdatedConn; + + SPItem *flashed_item; + Inkscape::Display::TemporaryItem *flash_tempitem; + Inkscape::UI::Selector* _selector; + Inkscape::UI::PathSharedData* _path_data; + SPCanvasGroup *_transform_handle_group; + SPItem *_last_over; + boost::ptr_map<SPItem*, ShapeEditor> _shape_editors; + + bool cursor_drag; + bool show_handles; + bool show_outline; + bool live_outline; + bool live_objects; + bool show_path_direction; + bool show_transform_handles; + bool single_node_transform_handles; + + void selection_changed(Inkscape::Selection *sel); + + void select_area(Geom::Rect const &sel, GdkEventButton *event); + void select_point(Geom::Point const &sel, GdkEventButton *event); + void mouseover_changed(Inkscape::UI::ControlPoint *p); + void update_tip(GdkEvent *event); + void handleControlUiStyleChange(); +}; + +} +} +} + +#endif + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/pen-tool.cpp b/src/ui/tools/pen-tool.cpp new file mode 100644 index 000000000..7228690b1 --- /dev/null +++ b/src/ui/tools/pen-tool.cpp @@ -0,0 +1,1373 @@ +/** \file + * Pen event context implementation. + */ + +/* + * Authors: + * Lauris Kaplinski <lauris@kaplinski.com> + * bulia byak <buliabyak@users.sf.net> + * Jon A. Cruz <jon@joncruz.org> + * + * Copyright (C) 2000 Lauris Kaplinski + * Copyright (C) 2000-2001 Ximian, Inc. + * Copyright (C) 2002 Lauris Kaplinski + * Copyright (C) 2004 Monash University + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include <gdk/gdkkeysyms.h> +#include <cstring> +#include <string> + +#include "ui/tools/pen-tool.h" +#include "sp-namedview.h" +#include "desktop.h" +#include "desktop-handles.h" +#include "selection.h" +#include "selection-chemistry.h" +#include "draw-anchor.h" +#include "message-stack.h" +#include "message-context.h" +#include "preferences.h" +#include "sp-path.h" +#include "display/sp-canvas.h" +#include "display/curve.h" +#include "pixmaps/cursor-pen.xpm" +#include "display/canvas-bpath.h" +#include "display/sp-ctrlline.h" +#include "display/sodipodi-ctrl.h" +#include <glibmm/i18n.h> +#include "macros.h" +#include "context-fns.h" +#include "tools-switch.h" +#include "ui/control-manager.h" +#include "tool-factory.h" + +using Inkscape::ControlManager; + +namespace Inkscape { +namespace UI { +namespace Tools { + +static Geom::Point pen_drag_origin_w(0, 0); +static bool pen_within_tolerance = false; +static int pen_last_paraxial_dir = 0; // last used direction in horizontal/vertical mode; 0 = horizontal, 1 = vertical + +namespace { + ToolBase* createPenContext() { + return new PenTool(); + } + + bool penContextRegistered = ToolFactory::instance().registerObject("/tools/freehand/pen", createPenContext); +} + +const std::string& PenTool::getPrefsPath() { + return PenTool::prefsPath; +} + +const std::string PenTool::prefsPath = "/tools/freehand/pen"; + +PenTool::PenTool() + : FreehandBase(cursor_pen_xpm, 4, 4) + , p() + , npoints(0) + , mode(MODE_CLICK) + , state(POINT) + , polylines_only(false) + , polylines_paraxial(false) + , num_clicks(0) + , expecting_clicks_for_LPE(0) + , waiting_LPE(NULL) + , waiting_item(NULL) + , c0(NULL) + , c1(NULL) + , cl0(NULL) + , cl1(NULL) + , events_disabled(false) +{ +} + +PenTool::PenTool(gchar const *const *cursor_shape, gint hot_x, gint hot_y) + : FreehandBase(cursor_shape, hot_x, hot_y) + , p() + , npoints(0) + , mode(MODE_CLICK) + , state(POINT) + , polylines_only(false) + , polylines_paraxial(false) + , num_clicks(0) + , expecting_clicks_for_LPE(0) + , waiting_LPE(NULL) + , waiting_item(NULL) + , c0(NULL) + , c1(NULL) + , cl0(NULL) + , cl1(NULL) + , events_disabled(false) +{ +} + +PenTool::~PenTool() { + if (this->c0) { + sp_canvas_item_destroy(this->c0); + this->c0 = NULL; + } + if (this->c1) { + sp_canvas_item_destroy(this->c1); + this->c1 = NULL; + } + if (this->cl0) { + sp_canvas_item_destroy(this->cl0); + this->cl0 = NULL; + } + if (this->cl1) { + sp_canvas_item_destroy(this->cl1); + this->cl1 = NULL; + } + + if (this->expecting_clicks_for_LPE > 0) { + // we received too few clicks to sanely set the parameter path so we remove the LPE from the item + this->waiting_item->removeCurrentPathEffect(false); + } +} + +void PenTool::setPolylineMode() { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + guint mode = prefs->getInt("/tools/freehand/pen/freehand-mode", 0); + this->polylines_only = (mode == 2 || mode == 3); + this->polylines_paraxial = (mode == 3); +} + +/** + * Callback to initialize PenTool object. + */ +void PenTool::setup() { + FreehandBase::setup(); + + ControlManager &mgr = ControlManager::getManager(); + + // Pen indicators + this->c0 = mgr.createControl(sp_desktop_controls(this->desktop), Inkscape::CTRL_TYPE_ADJ_HANDLE); + mgr.track(this->c0); + + this->c1 = mgr.createControl(sp_desktop_controls(this->desktop), Inkscape::CTRL_TYPE_ADJ_HANDLE); + mgr.track(this->c1); + + this->cl0 = mgr.createControlLine(sp_desktop_controls(this->desktop)); + this->cl1 = mgr.createControlLine(sp_desktop_controls(this->desktop)); + + sp_canvas_item_hide(this->c0); + sp_canvas_item_hide(this->c1); + sp_canvas_item_hide(this->cl0); + sp_canvas_item_hide(this->cl1); + + sp_event_context_read(this, "mode"); + + this->anchor_statusbar = false; + + this->setPolylineMode(); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/tools/freehand/pen/selcue")) { + this->enableSelectionCue(); + } +} + +void PenTool::_cancel() { + this->num_clicks = 0; + this->state = PenTool::STOP; + this->_resetColors(); + sp_canvas_item_hide(this->c0); + sp_canvas_item_hide(this->c1); + sp_canvas_item_hide(this->cl0); + sp_canvas_item_hide(this->cl1); + this->message_context->clear(); + this->message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled")); + + this->desktop->canvas->endForcedFullRedraws(); +} + +/** + * Finalization callback. + */ +void PenTool::finish() { + sp_event_context_discard_delayed_snap_event(this); + + if (this->npoints != 0) { + this->_cancel(); + } + + FreehandBase::finish(); +} + +/** + * Callback that sets key to value in pen context. + */ +void PenTool::set(const Inkscape::Preferences::Entry& val) { + Glib::ustring name = val.getEntryName(); + + if (name == "mode") { + if ( val.getString() == "drag" ) { + this->mode = MODE_DRAG; + } else { + this->mode = MODE_CLICK; + } + } +} + +bool PenTool::hasWaitingLPE() { + // note: waiting_LPE_type is defined in SPDrawContext + return (this->waiting_LPE != NULL || + this->waiting_LPE_type != Inkscape::LivePathEffect::INVALID_LPE); +} + +/** + * Snaps new node relative to the previous node. + */ +void PenTool::_endpointSnap(Geom::Point &p, guint const state) const { + if ((state & GDK_CONTROL_MASK) && !this->polylines_paraxial) { //CTRL enables angular snapping + if (this->npoints > 0) { + spdc_endpoint_snap_rotation(this, p, this->p[0], state); + } + } else { + // We cannot use shift here to disable snapping because the shift-key is already used + // to toggle the paraxial direction; if the user wants to disable snapping (s)he will + // have to use the %-key, the menu, or the snap toolbar + if ((this->npoints > 0) && this->polylines_paraxial) { + // snap constrained + this->_setToNearestHorizVert(p, state, true); + } else { + // snap freely + boost::optional<Geom::Point> origin = this->npoints > 0 ? this->p[0] : boost::optional<Geom::Point>(); + spdc_endpoint_snap_free(this, p, origin, state); // pass the origin, to allow for perpendicular / tangential snapping + } + } +} + +/** + * Snaps new node's handle relative to the new node. + */ +void PenTool::_endpointSnapHandle(Geom::Point &p, guint const state) const { + g_return_if_fail(( this->npoints == 2 || + this->npoints == 5 )); + + if ((state & GDK_CONTROL_MASK)) { //CTRL enables angular snapping + spdc_endpoint_snap_rotation(this, p, this->p[this->npoints - 2], state); + } else { + if (!(state & GDK_SHIFT_MASK)) { //SHIFT disables all snapping, except the angular snapping above + boost::optional<Geom::Point> origin = this->p[this->npoints - 2]; + spdc_endpoint_snap_free(this, p, origin, state); + } + } +} + +bool PenTool::item_handler(SPItem* item, GdkEvent* event) { + gint ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + ret = this->_handleButtonPress(event->button); + break; + case GDK_BUTTON_RELEASE: + ret = this->_handleButtonRelease(event->button); + break; + default: + break; + } + + if (!ret) { + ret = FreehandBase::item_handler(item, event); + } + + return ret; +} + +/** + * Callback to handle all pen events. + */ +bool PenTool::root_handler(GdkEvent* event) { + gint ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + ret = this->_handleButtonPress(event->button); + break; + + case GDK_MOTION_NOTIFY: + ret = this->_handleMotionNotify(event->motion); + break; + + case GDK_BUTTON_RELEASE: + ret = this->_handleButtonRelease(event->button); + break; + + case GDK_2BUTTON_PRESS: + ret = this->_handle2ButtonPress(event->button); + break; + + case GDK_KEY_PRESS: + ret = this->_handleKeyPress(event); + break; + + default: + break; + } + + if (!ret) { + ret = FreehandBase::root_handler(event); + } + + return ret; +} + +/** + * Handle mouse button press event. + */ +gint PenTool::_handleButtonPress(GdkEventButton const &bevent) { + if (this->events_disabled) { + // skip event processing if events are disabled + return FALSE; + } + + FreehandBase * const dc = SP_DRAW_CONTEXT(this); + SPDesktop * const desktop = dc->desktop; + Geom::Point const event_w(bevent.x, bevent.y); + Geom::Point event_dt(desktop->w2d(event_w)); + ToolBase *event_context = SP_EVENT_CONTEXT(this); + + gint ret = FALSE; + if (bevent.button == 1 && !event_context->space_panning + // make sure this is not the last click for a waiting LPE (otherwise we want to finish the path) + && this->expecting_clicks_for_LPE != 1) { + + if (Inkscape::have_viable_layer(desktop, dc->message_context) == false) { + return TRUE; + } + + if (!this->grab ) { + // Grab mouse, so release will not pass unnoticed + this->grab = SP_CANVAS_ITEM(desktop->acetate); + sp_canvas_item_grab(this->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK | + GDK_BUTTON_RELEASE_MASK | + GDK_POINTER_MOTION_MASK ), + NULL, bevent.time); + } + + pen_drag_origin_w = event_w; + pen_within_tolerance = true; + + // Test whether we hit any anchor. + SPDrawAnchor * const anchor = spdc_test_inside(this, event_w); + + switch (this->mode) { + case PenTool::MODE_CLICK: + // In click mode we add point on release + switch (this->state) { + case PenTool::POINT: + case PenTool::CONTROL: + case PenTool::CLOSE: + break; + case PenTool::STOP: + // This is allowed, if we just canceled curve + this->state = PenTool::POINT; + break; + default: + break; + } + break; + case PenTool::MODE_DRAG: + switch (this->state) { + case PenTool::STOP: + // This is allowed, if we just canceled curve + case PenTool::POINT: + if (this->npoints == 0) { + + Geom::Point p; + if ((bevent.state & GDK_CONTROL_MASK) && (this->polylines_only || this->polylines_paraxial)) { + p = event_dt; + if (!(bevent.state & GDK_SHIFT_MASK)) { + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE); + m.unSetup(); + } + spdc_create_single_dot(event_context, p, "/tools/freehand/pen", bevent.state); + ret = TRUE; + break; + } + + // TODO: Perhaps it would be nicer to rearrange the following case + // distinction so that the case of a waiting LPE is treated separately + + // Set start anchor + this->sa = anchor; + if (anchor && !this->hasWaitingLPE()) { + // Adjust point to anchor if needed; if we have a waiting LPE, we need + // a fresh path to be created so don't continue an existing one + p = anchor->dp; + desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path")); + } else { + // This is the first click of a new curve; deselect item so that + // this curve is not combined with it (unless it is drawn from its + // anchor, which is handled by the sibling branch above) + Inkscape::Selection * const selection = sp_desktop_selection(desktop); + if (!(bevent.state & GDK_SHIFT_MASK) || this->hasWaitingLPE()) { + // if we have a waiting LPE, we need a fresh path to be created + // so don't append to an existing one + selection->clear(); + desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path")); + } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) { + desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path")); + } + + // Create green anchor + p = event_dt; + this->_endpointSnap(p, bevent.state); + this->green_anchor = sp_draw_anchor_new(this, this->green_curve, TRUE, p); + } + this->_setInitialPoint(p); + } else { + + // Set end anchor + this->ea = anchor; + Geom::Point p; + if (anchor) { + p = anchor->dp; + // we hit an anchor, will finish the curve (either with or without closing) + // in release handler + this->state = PenTool::CLOSE; + + if (this->green_anchor && this->green_anchor->active) { + // we clicked on the current curve start, so close it even if + // we drag a handle away from it + dc->green_closed = TRUE; + } + ret = TRUE; + break; + + } else { + p = event_dt; + this->_endpointSnap(p, bevent.state); // Snap node only if not hitting anchor. + this->_setSubsequentPoint(p, true); + } + } + + this->state = this->polylines_only ? PenTool::POINT : PenTool::CONTROL; + ret = TRUE; + break; + case PenTool::CONTROL: + g_warning("Button down in CONTROL state"); + break; + case PenTool::CLOSE: + g_warning("Button down in CLOSE state"); + break; + default: + break; + } + break; + default: + break; + } + } else if (this->expecting_clicks_for_LPE == 1 && this->npoints != 0) { + // when the last click for a waiting LPE occurs we want to finish the path + this->_finishSegment(event_dt, bevent.state); + if (this->green_closed) { + // finishing at the start anchor, close curve + this->_finish(TRUE); + } else { + // finishing at some other anchor, finish curve but not close + this->_finish(FALSE); + } + + ret = TRUE; + } else if (bevent.button == 3 && this->npoints != 0) { + // right click - finish path + this->_finish(FALSE); + ret = TRUE; + } + + if (this->expecting_clicks_for_LPE > 0) { + --this->expecting_clicks_for_LPE; + } + + return ret; +} + +/** + * Handle motion_notify event. + */ +gint PenTool::_handleMotionNotify(GdkEventMotion const &mevent) { + gint ret = FALSE; + + ToolBase *event_context = SP_EVENT_CONTEXT(this); + SPDesktop * const dt = event_context->desktop; + + if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) { + // allow scrolling + return FALSE; + } + + if (this->events_disabled) { + // skip motion events if pen events are disabled + return FALSE; + } + + Geom::Point const event_w(mevent.x, + mevent.y); + if (pen_within_tolerance) { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + if ( Geom::LInfty( event_w - pen_drag_origin_w ) < tolerance ) { + return FALSE; // Do not drag if we're within tolerance from origin. + } + } + // Once the user has moved farther than tolerance from the original location + // (indicating they intend to move the object, not click), then always process the + // motion notify coordinates as given (no snapping back to origin) + pen_within_tolerance = false; + + // Find desktop coordinates + Geom::Point p = dt->w2d(event_w); + + // Test, whether we hit any anchor + SPDrawAnchor *anchor = spdc_test_inside(this, event_w); + + switch (this->mode) { + case PenTool::MODE_CLICK: + switch (this->state) { + case PenTool::POINT: + if ( this->npoints != 0 ) { + // Only set point, if we are already appending + this->_endpointSnap(p, mevent.state); + this->_setSubsequentPoint(p, true); + ret = TRUE; + } else if (!this->sp_event_context_knot_mouseover()) { + SnapManager &m = dt->namedview->snap_manager; + m.setup(dt); + m.preSnap(Inkscape::SnapCandidatePoint(p, Inkscape::SNAPSOURCE_NODE_HANDLE)); + m.unSetup(); + } + break; + case PenTool::CONTROL: + case PenTool::CLOSE: + // Placing controls is last operation in CLOSE state + this->_endpointSnap(p, mevent.state); + this->_setCtrl(p, mevent.state); + ret = TRUE; + break; + case PenTool::STOP: + // This is perfectly valid + break; + default: + break; + } + break; + case PenTool::MODE_DRAG: + switch (this->state) { + case PenTool::POINT: + if ( this->npoints > 0 ) { + // Only set point, if we are already appending + + if (!anchor) { // Snap node only if not hitting anchor + this->_endpointSnap(p, mevent.state); + this->_setSubsequentPoint(p, true, mevent.state); + } else { + this->_setSubsequentPoint(anchor->dp, false, mevent.state); + } + + if (anchor && !this->anchor_statusbar) { + this->message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Click</b> or <b>click and drag</b> to close and finish the path.")); + this->anchor_statusbar = true; + } else if (!anchor && this->anchor_statusbar) { + this->message_context->clear(); + this->anchor_statusbar = false; + } + + ret = TRUE; + } else { + if (anchor && !this->anchor_statusbar) { + this->message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Click</b> or <b>click and drag</b> to continue the path from this point.")); + this->anchor_statusbar = true; + } else if (!anchor && this->anchor_statusbar) { + this->message_context->clear(); + this->anchor_statusbar = false; + } + if (!this->sp_event_context_knot_mouseover()) { + SnapManager &m = dt->namedview->snap_manager; + m.setup(dt); + m.preSnap(Inkscape::SnapCandidatePoint(p, Inkscape::SNAPSOURCE_NODE_HANDLE)); + m.unSetup(); + } + } + break; + case PenTool::CONTROL: + case PenTool::CLOSE: + // Placing controls is last operation in CLOSE state + + // snap the handle + this->_endpointSnapHandle(p, mevent.state); + + if (!this->polylines_only) { + this->_setCtrl(p, mevent.state); + } else { + this->_setCtrl(this->p[1], mevent.state); + } + gobble_motion_events(GDK_BUTTON1_MASK); + ret = TRUE; + break; + case PenTool::STOP: + // This is perfectly valid + break; + default: + if (!this->sp_event_context_knot_mouseover()) { + SnapManager &m = dt->namedview->snap_manager; + m.setup(dt); + m.preSnap(Inkscape::SnapCandidatePoint(p, Inkscape::SNAPSOURCE_NODE_HANDLE)); + m.unSetup(); + } + break; + } + break; + default: + break; + } + return ret; +} + +/** + * Handle mouse button release event. + */ +gint PenTool::_handleButtonRelease(GdkEventButton const &revent) { + if (this->events_disabled) { + // skip event processing if events are disabled + return FALSE; + } + + gint ret = FALSE; + ToolBase *event_context = SP_EVENT_CONTEXT(this); + if ( revent.button == 1 && !event_context->space_panning) { + + FreehandBase *dc = SP_DRAW_CONTEXT (this); + + Geom::Point const event_w(revent.x, + revent.y); + // Find desktop coordinates + Geom::Point p = this->desktop->w2d(event_w); + + // Test whether we hit any anchor. + SPDrawAnchor *anchor = spdc_test_inside(this, event_w); + + switch (this->mode) { + case PenTool::MODE_CLICK: + switch (this->state) { + case PenTool::POINT: + if ( this->npoints == 0 ) { + // Start new thread only with button release + if (anchor) { + p = anchor->dp; + } + this->sa = anchor; + this->_setInitialPoint(p); + } else { + // Set end anchor here + this->ea = anchor; + if (anchor) { + p = anchor->dp; + } + } + this->state = PenTool::CONTROL; + ret = TRUE; + break; + case PenTool::CONTROL: + // End current segment + this->_endpointSnap(p, revent.state); + this->_finishSegment(p, revent.state); + this->state = PenTool::POINT; + ret = TRUE; + break; + case PenTool::CLOSE: + // End current segment + if (!anchor) { // Snap node only if not hitting anchor + this->_endpointSnap(p, revent.state); + } + this->_finishSegment(p, revent.state); + this->_finish(TRUE); + this->state = PenTool::POINT; + ret = TRUE; + break; + case PenTool::STOP: + // This is allowed, if we just canceled curve + this->state = PenTool::POINT; + ret = TRUE; + break; + default: + break; + } + break; + case PenTool::MODE_DRAG: + switch (this->state) { + case PenTool::POINT: + case PenTool::CONTROL: + this->_endpointSnap(p, revent.state); + this->_finishSegment(p, revent.state); + break; + case PenTool::CLOSE: + this->_endpointSnap(p, revent.state); + this->_finishSegment(p, revent.state); + if (this->green_closed) { + // finishing at the start anchor, close curve + this->_finish(TRUE); + } else { + // finishing at some other anchor, finish curve but not close + this->_finish(FALSE); + } + break; + case PenTool::STOP: + // This is allowed, if we just cancelled curve + break; + default: + break; + } + this->state = PenTool::POINT; + ret = TRUE; + break; + default: + break; + } + + if (this->grab) { + // Release grab now + sp_canvas_item_ungrab(this->grab, revent.time); + this->grab = NULL; + } + + ret = TRUE; + + dc->green_closed = FALSE; + } + + // TODO: can we be sure that the path was created correctly? + // TODO: should we offer an option to collect the clicks in a list? + if (this->expecting_clicks_for_LPE == 0 && this->hasWaitingLPE()) { + this->setPolylineMode(); + + ToolBase *ec = SP_EVENT_CONTEXT(this); + Inkscape::Selection *selection = sp_desktop_selection (ec->desktop); + + if (this->waiting_LPE) { + // we have an already created LPE waiting for a path + this->waiting_LPE->acceptParamPath(SP_PATH(selection->singleItem())); + selection->add(SP_OBJECT(this->waiting_item)); + this->waiting_LPE = NULL; + } else { + // the case that we need to create a new LPE and apply it to the just-drawn path is + // handled in spdc_check_for_and_apply_waiting_LPE() in draw-context.cpp + } + } + + return ret; +} + +gint PenTool::_handle2ButtonPress(GdkEventButton const &bevent) { + gint ret = FALSE; + // only end on LMB double click. Otherwise horizontal scrolling causes ending of the path + if (this->npoints != 0 && bevent.button == 1) { + this->_finish(FALSE); + ret = TRUE; + } + return ret; +} + +void PenTool::_redrawAll() { + // green + if (this->green_bpaths) { + // remove old piecewise green canvasitems + while (this->green_bpaths) { + sp_canvas_item_destroy(SP_CANVAS_ITEM(this->green_bpaths->data)); + this->green_bpaths = g_slist_remove(this->green_bpaths, this->green_bpaths->data); + } + // one canvas bpath for all of green_curve + SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(this->desktop), this->green_curve); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), this->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cshape), 0, SP_WIND_RULE_NONZERO); + + this->green_bpaths = g_slist_prepend(this->green_bpaths, cshape); + } + + if (this->green_anchor) + SP_CTRL(this->green_anchor->ctrl)->moveto(this->green_anchor->dp); + + this->red_curve->reset(); + this->red_curve->moveto(this->p[0]); + this->red_curve->curveto(this->p[1], this->p[2], this->p[3]); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), this->red_curve); + + // handles + if (this->p[0] != this->p[1]) { + SP_CTRL(this->c1)->moveto(this->p[1]); + this->cl1->setCoords(this->p[0], this->p[1]); + sp_canvas_item_show(this->c1); + sp_canvas_item_show(this->cl1); + } else { + sp_canvas_item_hide(this->c1); + sp_canvas_item_hide(this->cl1); + } + + Geom::Curve const * last_seg = this->green_curve->last_segment(); + if (last_seg) { + Geom::CubicBezier const * cubic = dynamic_cast<Geom::CubicBezier const *>( last_seg ); + if ( cubic && + (*cubic)[2] != this->p[0] ) + { + Geom::Point p2 = (*cubic)[2]; + SP_CTRL(this->c0)->moveto(p2); + this->cl0->setCoords(p2, this->p[0]); + sp_canvas_item_show(this->c0); + sp_canvas_item_show(this->cl0); + } else { + sp_canvas_item_hide(this->c0); + sp_canvas_item_hide(this->cl0); + } + } +} + +void PenTool::_lastpointMove(gdouble x, gdouble y) { + if (this->npoints != 5) + return; + + // green + if (!this->green_curve->is_empty()) { + this->green_curve->last_point_additive_move( Geom::Point(x,y) ); + } else { + // start anchor too + if (this->green_anchor) { + this->green_anchor->dp += Geom::Point(x, y); + } + } + + // red + this->p[0] += Geom::Point(x, y); + this->p[1] += Geom::Point(x, y); + this->_redrawAll(); +} + +void PenTool::_lastpointMoveScreen(gdouble x, gdouble y) { + this->_lastpointMove(x / this->desktop->current_zoom(), y / this->desktop->current_zoom()); +} + +void PenTool::_lastpointToCurve() { + if (this->npoints != 5) + return; + + Geom::CubicBezier const * cubic = dynamic_cast<Geom::CubicBezier const *>( this->green_curve->last_segment() ); + if ( cubic ) { + this->p[1] = this->p[0] + (Geom::Point)( (*cubic)[3] - (*cubic)[2] ); + } else { + this->p[1] = this->p[0] + (1./3)*(this->p[3] - this->p[0]); + } + + this->_redrawAll(); +} + +void PenTool::_lastpointToLine() { + if (this->npoints != 5) + return; + + this->p[1] = this->p[0]; + + this->_redrawAll(); +} + + +gint PenTool::_handleKeyPress(GdkEvent *event) { + + gint ret = FALSE; + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + gdouble const nudge = prefs->getDoubleLimited("/options/nudgedistance/value", 2, 0, 1000, "px"); // in px + + switch (get_group0_keyval (&event->key)) { + + case GDK_KEY_Left: // move last point left + case GDK_KEY_KP_Left: + if (!MOD__CTRL(event)) { // not ctrl + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) this->_lastpointMoveScreen(-10, 0); // shift + else this->_lastpointMoveScreen(-1, 0); // no shift + } + else { // no alt + if (MOD__SHIFT(event)) this->_lastpointMove(-10*nudge, 0); // shift + else this->_lastpointMove(-nudge, 0); // no shift + } + ret = TRUE; + } + break; + case GDK_KEY_Up: // move last point up + case GDK_KEY_KP_Up: + if (!MOD__CTRL(event)) { // not ctrl + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) this->_lastpointMoveScreen(0, 10); // shift + else this->_lastpointMoveScreen(0, 1); // no shift + } + else { // no alt + if (MOD__SHIFT(event)) this->_lastpointMove(0, 10*nudge); // shift + else this->_lastpointMove(0, nudge); // no shift + } + ret = TRUE; + } + break; + case GDK_KEY_Right: // move last point right + case GDK_KEY_KP_Right: + if (!MOD__CTRL(event)) { // not ctrl + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) this->_lastpointMoveScreen(10, 0); // shift + else this->_lastpointMoveScreen(1, 0); // no shift + } + else { // no alt + if (MOD__SHIFT(event)) this->_lastpointMove(10*nudge, 0); // shift + else this->_lastpointMove(nudge, 0); // no shift + } + ret = TRUE; + } + break; + case GDK_KEY_Down: // move last point down + case GDK_KEY_KP_Down: + if (!MOD__CTRL(event)) { // not ctrl + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) this->_lastpointMoveScreen(0, -10); // shift + else this->_lastpointMoveScreen(0, -1); // no shift + } + else { // no alt + if (MOD__SHIFT(event)) this->_lastpointMove(0, -10*nudge); // shift + else this->_lastpointMove(0, -nudge); // no shift + } + ret = TRUE; + } + break; + +/*TODO: this is not yet enabled?? looks like some traces of the Geometry tool + case GDK_KEY_P: + case GDK_KEY_p: + if (MOD__SHIFT_ONLY(event)) { + sp_pen_context_wait_for_LPE_mouse_clicks(pc, Inkscape::LivePathEffect::PARALLEL, 2); + ret = TRUE; + } + break; + + case GDK_KEY_C: + case GDK_KEY_c: + if (MOD__SHIFT_ONLY(event)) { + sp_pen_context_wait_for_LPE_mouse_clicks(pc, Inkscape::LivePathEffect::CIRCLE_3PTS, 3); + ret = TRUE; + } + break; + + case GDK_KEY_B: + case GDK_KEY_b: + if (MOD__SHIFT_ONLY(event)) { + sp_pen_context_wait_for_LPE_mouse_clicks(pc, Inkscape::LivePathEffect::PERP_BISECTOR, 2); + ret = TRUE; + } + break; + + case GDK_KEY_A: + case GDK_KEY_a: + if (MOD__SHIFT_ONLY(event)) { + sp_pen_context_wait_for_LPE_mouse_clicks(pc, Inkscape::LivePathEffect::ANGLE_BISECTOR, 3); + ret = TRUE; + } + break; +*/ + + case GDK_KEY_U: + case GDK_KEY_u: + if (MOD__SHIFT_ONLY(event)) { + this->_lastpointToCurve(); + ret = TRUE; + } + break; + case GDK_KEY_L: + case GDK_KEY_l: + if (MOD__SHIFT_ONLY(event)) { + this->_lastpointToLine(); + ret = TRUE; + } + break; + + case GDK_KEY_Return: + case GDK_KEY_KP_Enter: + if (this->npoints != 0) { + this->_finish(FALSE); + ret = TRUE; + } + break; + case GDK_KEY_Escape: + if (this->npoints != 0) { + // if drawing, cancel, otherwise pass it up for deselecting + this->_cancel (); + ret = TRUE; + } + break; + case GDK_KEY_z: + case GDK_KEY_Z: + if (MOD__CTRL_ONLY(event) && this->npoints != 0) { + // if drawing, cancel, otherwise pass it up for undo + this->_cancel (); + ret = TRUE; + } + break; + case GDK_KEY_g: + case GDK_KEY_G: + if (MOD__SHIFT_ONLY(event)) { + sp_selection_to_guides(SP_EVENT_CONTEXT(this)->desktop); + ret = true; + } + break; + case GDK_KEY_BackSpace: + case GDK_KEY_Delete: + case GDK_KEY_KP_Delete: + if ( this->green_curve->is_empty() || (this->green_curve->last_segment() == NULL) ) { + if (!this->red_curve->is_empty()) { + this->_cancel (); + ret = TRUE; + } else { + // do nothing; this event should be handled upstream + } + } else { + // Reset red curve + this->red_curve->reset(); + // Destroy topmost green bpath + if (this->green_bpaths) { + if (this->green_bpaths->data) + sp_canvas_item_destroy(SP_CANVAS_ITEM(this->green_bpaths->data)); + this->green_bpaths = g_slist_remove(this->green_bpaths, this->green_bpaths->data); + } + // Get last segment + if ( this->green_curve->is_empty() ) { + g_warning("pen_handle_key_press, case GDK_KP_Delete: Green curve is empty"); + break; + } + // The code below assumes that pc->green_curve has only ONE path ! + Geom::Curve const * crv = this->green_curve->last_segment(); + this->p[0] = crv->initialPoint(); + if ( Geom::CubicBezier const * cubic = dynamic_cast<Geom::CubicBezier const *>(crv)) { + this->p[1] = (*cubic)[1]; + } else { + this->p[1] = this->p[0]; + } + Geom::Point const pt(( this->npoints < 4 + ? (Geom::Point)(crv->finalPoint()) + : this->p[3] )); + this->npoints = 2; + this->green_curve->backspace(); + sp_canvas_item_hide(this->c0); + sp_canvas_item_hide(this->c1); + sp_canvas_item_hide(this->cl0); + sp_canvas_item_hide(this->cl1); + this->state = PenTool::POINT; + this->_setSubsequentPoint(pt, true); + pen_last_paraxial_dir = !pen_last_paraxial_dir; + ret = TRUE; + } + break; + default: + break; + } + return ret; +} + +void PenTool::_resetColors() { + // Red + this->red_curve->reset(); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), NULL); + // Blue + this->blue_curve->reset(); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->blue_bpath), NULL); + // Green + while (this->green_bpaths) { + sp_canvas_item_destroy(SP_CANVAS_ITEM(this->green_bpaths->data)); + this->green_bpaths = g_slist_remove(this->green_bpaths, this->green_bpaths->data); + } + this->green_curve->reset(); + if (this->green_anchor) { + this->green_anchor = sp_draw_anchor_destroy(this->green_anchor); + } + this->sa = NULL; + this->ea = NULL; + this->npoints = 0; + this->red_curve_is_valid = false; +} + + +void PenTool::_setInitialPoint(Geom::Point const p) { + g_assert( this->npoints == 0 ); + + this->p[0] = p; + this->p[1] = p; + this->npoints = 2; + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), NULL); + + this->desktop->canvas->forceFullRedrawAfterInterruptions(5); +} + +/** + * Show the status message for the current line/curve segment. + * This type of message always shows angle/distance as the last + * two parameters ("angle %3.2f°, distance %s"). + */ +void PenTool::_setAngleDistanceStatusMessage(Geom::Point const p, int pc_point_to_compare, gchar const *message) { + g_assert(this != NULL); + g_assert((pc_point_to_compare == 0) || (pc_point_to_compare == 3)); // exclude control handles + g_assert(message != NULL); + + SPDesktop *desktop = SP_EVENT_CONTEXT(this)->desktop; + Geom::Point rel = p - this->p[pc_point_to_compare]; + Inkscape::Util::Quantity q = Inkscape::Util::Quantity(Geom::L2(rel), "px"); + GString *dist = g_string_new(q.string(desktop->namedview->doc_units).c_str()); + double angle = atan2(rel[Geom::Y], rel[Geom::X]) * 180 / M_PI; + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/options/compassangledisplay/value", 0) != 0) { + angle = 90 - angle; + if (angle < 0) { + angle += 360; + } + } + + this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, message, angle, dist->str); + g_string_free(dist, FALSE); +} + +void PenTool::_setSubsequentPoint(Geom::Point const p, bool statusbar, guint status) { + g_assert( this->npoints != 0 ); + // todo: Check callers to see whether 2 <= npoints is guaranteed. + + this->p[2] = p; + this->p[3] = p; + this->p[4] = p; + this->npoints = 5; + this->red_curve->reset(); + bool is_curve; + this->red_curve->moveto(this->p[0]); + if (this->polylines_paraxial && !statusbar) { + // we are drawing horizontal/vertical lines and hit an anchor; + Geom::Point const origin = this->p[0]; + // if the previous point and the anchor are not aligned either horizontally or vertically... + if ((abs(p[Geom::X] - origin[Geom::X]) > 1e-9) && (abs(p[Geom::Y] - origin[Geom::Y]) > 1e-9)) { + // ...then we should draw an L-shaped path, consisting of two paraxial segments + Geom::Point intermed = p; + this->_setToNearestHorizVert(intermed, status, false); + this->red_curve->lineto(intermed); + } + this->red_curve->lineto(p); + is_curve = false; + } else { + // one of the 'regular' modes + if (this->p[1] != this->p[0]) { + this->red_curve->curveto(this->p[1], p, p); + is_curve = true; + } else { + this->red_curve->lineto(p); + is_curve = false; + } + } + + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), this->red_curve); + + if (statusbar) { + gchar *message = is_curve ? + _("<b>Curve segment</b>: angle %3.2f°, distance %s; with <b>Ctrl</b> to snap angle, <b>Enter</b> to finish the path" ): + _("<b>Line segment</b>: angle %3.2f°, distance %s; with <b>Ctrl</b> to snap angle, <b>Enter</b> to finish the path"); + this->_setAngleDistanceStatusMessage(p, 0, message); + } +} + +void PenTool::_setCtrl(Geom::Point const p, guint const state) { + sp_canvas_item_show(this->c1); + sp_canvas_item_show(this->cl1); + + if ( this->npoints == 2 ) { + this->p[1] = p; + sp_canvas_item_hide(this->c0); + sp_canvas_item_hide(this->cl0); + SP_CTRL(this->c1)->moveto(this->p[1]); + this->cl1->setCoords(this->p[0], this->p[1]); + + this->_setAngleDistanceStatusMessage(p, 0, _("<b>Curve handle</b>: angle %3.2f°, length %s; with <b>Ctrl</b> to snap angle")); + } else if ( this->npoints == 5 ) { + this->p[4] = p; + sp_canvas_item_show(this->c0); + sp_canvas_item_show(this->cl0); + bool is_symm = false; + if ( ( ( this->mode == PenTool::MODE_CLICK ) && ( state & GDK_CONTROL_MASK ) ) || + ( ( this->mode == PenTool::MODE_DRAG ) && !( state & GDK_SHIFT_MASK ) ) ) { + Geom::Point delta = p - this->p[3]; + this->p[2] = this->p[3] - delta; + is_symm = true; + this->red_curve->reset(); + this->red_curve->moveto(this->p[0]); + this->red_curve->curveto(this->p[1], this->p[2], this->p[3]); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), this->red_curve); + } + SP_CTRL(this->c0)->moveto(this->p[2]); + this->cl0 ->setCoords(this->p[3], this->p[2]); + SP_CTRL(this->c1)->moveto(this->p[4]); + this->cl1->setCoords(this->p[3], this->p[4]); + + gchar *message = is_symm ? + _("<b>Curve handle, symmetric</b>: angle %3.2f°, length %s; with <b>Ctrl</b> to snap angle, with <b>Shift</b> to move this handle only") : + _("<b>Curve handle</b>: angle %3.2f°, length %s; with <b>Ctrl</b> to snap angle, with <b>Shift</b> to move this handle only"); + this->_setAngleDistanceStatusMessage(p, 3, message); + } else { + g_warning("Something bad happened - npoints is %d", this->npoints); + } +} + +void PenTool::_finishSegment(Geom::Point const p, guint const state) { + if (this->polylines_paraxial) { + pen_last_paraxial_dir = this->nextParaxialDirection(p, this->p[0], state); + } + + ++this->num_clicks; + + if (!this->red_curve->is_empty()) { + this->green_curve->append_continuous(this->red_curve, 0.0625); + SPCurve *curve = this->red_curve->copy(); + /// \todo fixme: + SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(this->desktop), curve); + curve->unref(); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), this->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + + this->green_bpaths = g_slist_prepend(this->green_bpaths, cshape); + + this->p[0] = this->p[3]; + this->p[1] = this->p[4]; + this->npoints = 2; + + this->red_curve->reset(); + } +} + +void PenTool::_finish(gboolean const closed) { + if (this->expecting_clicks_for_LPE > 1) { + // don't let the path be finished before we have collected the required number of mouse clicks + return; + } + + this->num_clicks = 0; + + this->_disableEvents(); + + SPDesktop *const desktop = this->desktop; + this->message_context->clear(); + desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Drawing finished")); + + this->red_curve->reset(); + spdc_concat_colors_and_flush(this, closed); + this->sa = NULL; + this->ea = NULL; + + this->npoints = 0; + this->state = PenTool::POINT; + + sp_canvas_item_hide(this->c0); + sp_canvas_item_hide(this->c1); + sp_canvas_item_hide(this->cl0); + sp_canvas_item_hide(this->cl1); + + if (this->green_anchor) { + this->green_anchor = sp_draw_anchor_destroy(this->green_anchor); + } + + + this->desktop->canvas->endForcedFullRedraws(); + + this->_enableEvents(); +} + +void PenTool::_disableEvents() { + this->events_disabled = true; +} + +void PenTool::_enableEvents() { + g_return_if_fail(this->events_disabled != 0); + + this->events_disabled = false; +} + +void PenTool::waitForLPEMouseClicks(Inkscape::LivePathEffect::EffectType effect_type, unsigned int num_clicks, bool use_polylines) { + if (effect_type == Inkscape::LivePathEffect::INVALID_LPE) + return; + + this->waiting_LPE_type = effect_type; + this->expecting_clicks_for_LPE = num_clicks; + this->polylines_only = use_polylines; + this->polylines_paraxial = false; // TODO: think if this is correct for all cases +} + +int PenTool::nextParaxialDirection(Geom::Point const &pt, Geom::Point const &origin, guint state) const { + // + // after the first mouse click we determine whether the mouse pointer is closest to a + // horizontal or vertical segment; for all subsequent mouse clicks, we use the direction + // orthogonal to the last one; pressing Shift toggles the direction + // + // num_clicks is not reliable because spdc_pen_finish_segment is sometimes called too early + // (on first mouse release), in which case num_clicks immediately becomes 1. + // if (pc->num_clicks == 0) { + + if (this->green_curve->is_empty()) { + // first mouse click + double dist_h = fabs(pt[Geom::X] - origin[Geom::X]); + double dist_v = fabs(pt[Geom::Y] - origin[Geom::Y]); + int ret = (dist_h < dist_v) ? 1 : 0; // 0 = horizontal, 1 = vertical + pen_last_paraxial_dir = (state & GDK_SHIFT_MASK) ? 1 - ret : ret; + return pen_last_paraxial_dir; + } else { + // subsequent mouse click + return (state & GDK_SHIFT_MASK) ? pen_last_paraxial_dir : 1 - pen_last_paraxial_dir; + } +} + +void PenTool::_setToNearestHorizVert(Geom::Point &pt, guint const state, bool snap) const { + Geom::Point const origin = this->p[0]; + + int next_dir = this->nextParaxialDirection(pt, origin, state); + + if (!snap) { + if (next_dir == 0) { + // line is forced to be horizontal + pt[Geom::Y] = origin[Geom::Y]; + } else { + // line is forced to be vertical + pt[Geom::X] = origin[Geom::X]; + } + } else { + // Create a horizontal or vertical constraint line + Inkscape::Snapper::SnapConstraint cl(origin, next_dir ? Geom::Point(0, 1) : Geom::Point(1, 0)); + + // Snap along the constraint line; if we didn't snap then still the constraint will be applied + SnapManager &m = this->desktop->namedview->snap_manager; + + Inkscape::Selection *selection = sp_desktop_selection (this->desktop); + // selection->singleItem() is the item that is currently being drawn. This item will not be snapped to (to avoid self-snapping) + // TODO: Allow snapping to the stationary parts of the item, and only ignore the last segment + + m.setup(this->desktop, true, selection->singleItem()); + m.constrainedSnapReturnByRef(pt, Inkscape::SNAPSOURCE_NODE_HANDLE, cl); + m.unSetup(); + } +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/pen-tool.h b/src/ui/tools/pen-tool.h new file mode 100644 index 000000000..182d270ee --- /dev/null +++ b/src/ui/tools/pen-tool.h @@ -0,0 +1,132 @@ +#ifndef SEEN_PEN_CONTEXT_H +#define SEEN_PEN_CONTEXT_H + +/** \file + * PenTool: a context for pen tool events. + */ + +#include "ui/tools/freehand-base.h" +#include "live_effects/effect.h" + +#define SP_PEN_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::PenTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_PEN_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::PenTool*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +struct SPCtrlLine; + +namespace Inkscape { +namespace UI { +namespace Tools { + +/** + * PenTool: a context for pen tool events. + */ +class PenTool : public FreehandBase { +public: + PenTool(); + PenTool(gchar const *const *cursor_shape, gint hot_x, gint hot_y); + virtual ~PenTool(); + + enum Mode { + MODE_CLICK, + MODE_DRAG + }; + + enum State { + POINT, + CONTROL, + CLOSE, + STOP + }; + + Geom::Point p[5]; + + /** \invar npoints in {0, 2, 5}. */ + // npoints somehow determines the type of the node (what does it mean, exactly? the number of Bezier handles?) + gint npoints; + + Mode mode; + State state; + + bool polylines_only; + bool polylines_paraxial; + int num_clicks; + + unsigned int expecting_clicks_for_LPE; // if positive, finish the path after this many clicks + Inkscape::LivePathEffect::Effect *waiting_LPE; // if NULL, waiting_LPE_type in SPDrawContext is taken into account + SPLPEItem *waiting_item; + + SPCanvasItem *c0; + SPCanvasItem *c1; + + SPCtrlLine *cl0; + SPCtrlLine *cl1; + + bool events_disabled; + + static const std::string prefsPath; + + virtual const std::string& getPrefsPath(); + + int nextParaxialDirection(Geom::Point const &pt, Geom::Point const &origin, guint state) const; + void setPolylineMode(); + bool hasWaitingLPE(); + void waitForLPEMouseClicks(Inkscape::LivePathEffect::EffectType effect_type, unsigned int num_clicks, bool use_polylines = true); + +protected: + virtual void setup(); + virtual void finish(); + virtual void set(const Inkscape::Preferences::Entry& val); + virtual bool root_handler(GdkEvent* event); + virtual bool item_handler(SPItem* item, GdkEvent* event); + +private: + gint _handleButtonPress(GdkEventButton const &bevent); + gint _handleMotionNotify(GdkEventMotion const &mevent); + gint _handleButtonRelease(GdkEventButton const &revent); + gint _handle2ButtonPress(GdkEventButton const &bevent); + gint _handleKeyPress(GdkEvent *event); + + void _setInitialPoint(Geom::Point const p); + void _setSubsequentPoint(Geom::Point const p, bool statusbar, guint status = 0); + void _setCtrl(Geom::Point const p, guint state); + void _finishSegment(Geom::Point p, guint state); + + void _finish(gboolean closed); + + void _resetColors(); + + void _disableEvents(); + void _enableEvents(); + + void _setToNearestHorizVert(Geom::Point &pt, guint const state, bool snap) const; + + void _setAngleDistanceStatusMessage(Geom::Point const p, int pc_point_to_compare, gchar const *message); + + void _lastpointToLine(); + void _lastpointToCurve(); + void _lastpointMoveScreen(gdouble x, gdouble y); + void _lastpointMove(gdouble x, gdouble y); + void _redrawAll(); + + void _endpointSnapHandle(Geom::Point &p, guint const state) const; + void _endpointSnap(Geom::Point &p, guint const state) const; + + void _cancel(); +}; + +} +} +} + +#endif /* !SEEN_PEN_CONTEXT_H */ + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/pencil-tool.cpp b/src/ui/tools/pencil-tool.cpp new file mode 100644 index 000000000..230ec62af --- /dev/null +++ b/src/ui/tools/pencil-tool.cpp @@ -0,0 +1,868 @@ +/** \file + * Pencil event context implementation. + */ + +/* + * Authors: + * Lauris Kaplinski <lauris@kaplinski.com> + * bulia byak <buliabyak@users.sf.net> + * Jon A. Cruz <jon@joncruz.org> + * + * Copyright (C) 2000 Lauris Kaplinski + * Copyright (C) 2000-2001 Ximian, Inc. + * Copyright (C) 2002 Lauris Kaplinski + * Copyright (C) 2004 Monash University + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include <gdk/gdkkeysyms.h> + +#include "ui/tools/pencil-tool.h" +#include "desktop.h" +#include "desktop-handles.h" +#include "selection.h" +#include "selection-chemistry.h" +#include "draw-anchor.h" +#include "message-stack.h" +#include "message-context.h" +#include "modifier-fns.h" +#include "sp-path.h" +#include "preferences.h" +#include "snap.h" +#include "pixmaps/cursor-pencil.xpm" +#include <2geom/sbasis-to-bezier.h> +#include <2geom/bezier-utils.h> +#include "display/canvas-bpath.h" +#include <glibmm/i18n.h> +#include "context-fns.h" +#include "sp-namedview.h" +#include "xml/repr.h" +#include "document.h" +#include "desktop-style.h" +#include "macros.h" +#include "display/sp-canvas.h" +#include "display/curve.h" +#include "livarot/Path.h" +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +static Geom::Point pencil_drag_origin_w(0, 0); +static bool pencil_within_tolerance = false; + +static bool in_svg_plane(Geom::Point const &p) { return Geom::LInfty(p) < 1e18; } + +namespace { + ToolBase* createPencilContext() { + return new PencilTool(); + } + + bool pencilContextRegistered = ToolFactory::instance().registerObject("/tools/freehand/pencil", createPencilContext); +} + +const std::string& PencilTool::getPrefsPath() { + return PencilTool::prefsPath; +} + +const std::string PencilTool::prefsPath = "/tools/freehand/pencil"; + +PencilTool::PencilTool() + : FreehandBase(cursor_pencil_xpm, 4, 4) + , p() + , npoints(0) + , state(SP_PENCIL_CONTEXT_IDLE) + , req_tangent(0, 0) + , is_drawing(false) + , sketch_n(0) +{ +} + +void PencilTool::setup() { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/tools/freehand/pencil/selcue")) { + this->enableSelectionCue(); + } + + FreehandBase::setup(); + + this->is_drawing = false; + this->anchor_statusbar = false; +} + +PencilTool::~PencilTool() { +} + +/** Snaps new node relative to the previous node. */ +void PencilTool::_endpointSnap(Geom::Point &p, guint const state) { + if ((state & GDK_CONTROL_MASK)) { //CTRL enables constrained snapping + if (this->npoints > 0) { + spdc_endpoint_snap_rotation(this, p, this->p[0], state); + } + } else { + if (!(state & GDK_SHIFT_MASK)) { //SHIFT disables all snapping, except the angular snapping above + //After all, the user explicitely asked for angular snapping by + //pressing CTRL + boost::optional<Geom::Point> origin = this->npoints > 0 ? this->p[0] : boost::optional<Geom::Point>(); + spdc_endpoint_snap_free(this, p, origin, state); + } + } +} + +/** + * Callback for handling all pencil context events. + */ +bool PencilTool::root_handler(GdkEvent* event) { + gint ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + ret = this->_handleButtonPress(event->button); + break; + + case GDK_MOTION_NOTIFY: + ret = this->_handleMotionNotify(event->motion); + break; + + case GDK_BUTTON_RELEASE: + ret = this->_handleButtonRelease(event->button); + break; + + case GDK_KEY_PRESS: + ret = this->_handleKeyPress(get_group0_keyval (&event->key), event->key.state); + break; + + case GDK_KEY_RELEASE: + ret = this->_handleKeyRelease(get_group0_keyval (&event->key), event->key.state); + break; + + default: + break; + } + + if (!ret) { + ret = FreehandBase::root_handler(event); + } + + return ret; +} + +gint PencilTool::_handleButtonPress(GdkEventButton const &bevent) { + gint ret = FALSE; + ToolBase *event_context = SP_EVENT_CONTEXT(this); + if ( bevent.button == 1 && !event_context->space_panning) { + + FreehandBase *dc = SP_DRAW_CONTEXT (this); + SPDesktop *desktop = dc->desktop; + Inkscape::Selection *selection = sp_desktop_selection(desktop); + + if (Inkscape::have_viable_layer(desktop, dc->message_context) == false) { + return TRUE; + } + + if (!this->grab) { + /* Grab mouse, so release will not pass unnoticed */ + this->grab = SP_CANVAS_ITEM(desktop->acetate); + sp_canvas_item_grab(this->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK | + GDK_BUTTON_RELEASE_MASK | + GDK_POINTER_MOTION_MASK ), + NULL, bevent.time); + } + + Geom::Point const button_w(bevent.x, bevent.y); + + /* Find desktop coordinates */ + Geom::Point p = this->desktop->w2d(button_w); + + /* Test whether we hit any anchor. */ + SPDrawAnchor *anchor = spdc_test_inside(this, button_w); + + pencil_drag_origin_w = Geom::Point(bevent.x,bevent.y); + pencil_within_tolerance = true; + + switch (this->state) { + case SP_PENCIL_CONTEXT_ADDLINE: + /* Current segment will be finished with release */ + ret = TRUE; + break; + default: + /* Set first point of sequence */ + SnapManager &m = desktop->namedview->snap_manager; + + if (bevent.state & GDK_CONTROL_MASK) { + m.setup(desktop); + if (!(bevent.state & GDK_SHIFT_MASK)) { + m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE); + } + spdc_create_single_dot(event_context, p, "/tools/freehand/pencil", bevent.state); + m.unSetup(); + ret = true; + break; + } + if (anchor) { + p = anchor->dp; + desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path")); + } else { + m.setup(desktop); + if (!(bevent.state & GDK_SHIFT_MASK)) { + // This is the first click of a new curve; deselect item so that + // this curve is not combined with it (unless it is drawn from its + // anchor, which is handled by the sibling branch above) + selection->clear(); + desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path")); + m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE); + } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) { + desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path")); + m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE); + } + m.unSetup(); + } + this->sa = anchor; + this->_setStartpoint(p); + ret = TRUE; + break; + } + + this->is_drawing = true; + } + return ret; +} + +gint PencilTool::_handleMotionNotify(GdkEventMotion const &mevent) { + SPDesktop *const dt = this->desktop; + + if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) { + // mouse was accidentally moved during Ctrl+click; + // ignore the motion and create a single point + this->is_drawing = false; + return TRUE; + } + gint ret = FALSE; + + ToolBase *event_context = SP_EVENT_CONTEXT(this); + if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) { + // allow scrolling + return FALSE; + } + + if ( ( mevent.state & GDK_BUTTON1_MASK ) && !this->grab && this->is_drawing) { + /* Grab mouse, so release will not pass unnoticed */ + this->grab = SP_CANVAS_ITEM(dt->acetate); + sp_canvas_item_grab(this->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK | + GDK_BUTTON_RELEASE_MASK | + GDK_POINTER_MOTION_MASK ), + NULL, mevent.time); + } + + /* Find desktop coordinates */ + Geom::Point p = dt->w2d(Geom::Point(mevent.x, mevent.y)); + + /* Test whether we hit any anchor. */ + SPDrawAnchor *anchor = spdc_test_inside(this, Geom::Point(mevent.x, mevent.y)); + + if (pencil_within_tolerance) { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + if ( Geom::LInfty( Geom::Point(mevent.x,mevent.y) - pencil_drag_origin_w ) < tolerance ) { + return FALSE; // Do not drag if we're within tolerance from origin. + } + } + + // Once the user has moved farther than tolerance from the original location + // (indicating they intend to move the object, not click), then always process the + // motion notify coordinates as given (no snapping back to origin) + pencil_within_tolerance = false; + + switch (this->state) { + case SP_PENCIL_CONTEXT_ADDLINE: + /* Set red endpoint */ + if (anchor) { + p = anchor->dp; + } else { + Geom::Point ptnr(p); + this->_endpointSnap(ptnr, mevent.state); + p = ptnr; + } + this->_setEndpoint(p); + ret = TRUE; + break; + default: + /* We may be idle or already freehand */ + if ( mevent.state & GDK_BUTTON1_MASK && this->is_drawing ) { + if (this->state == SP_PENCIL_CONTEXT_IDLE) { + sp_event_context_discard_delayed_snap_event(event_context); + } + this->state = SP_PENCIL_CONTEXT_FREEHAND; + + if ( !this->sa && !this->green_anchor ) { + /* Create green anchor */ + this->green_anchor = sp_draw_anchor_new(this, this->green_curve, TRUE, this->p[0]); + } + if (anchor) { + p = anchor->dp; + } + + if ( this->npoints != 0) { // buttonpress may have happened before we entered draw context! + if (this->ps.empty()) { + // Only in freehand mode we have to add the first point also to pc->ps (apparently) + // - We cannot add this point in spdc_set_startpoint, because we only need it for freehand + // - We cannot do this in the button press handler because at that point we don't know yet + // wheter we're going into freehand mode or not + this->ps.push_back(this->p[0]); + } + this->_addFreehandPoint(p, mevent.state); + ret = TRUE; + } + + if (anchor && !this->anchor_statusbar) { + this->message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path.")); + this->anchor_statusbar = true; + } else if (!anchor && this->anchor_statusbar) { + this->message_context->clear(); + this->anchor_statusbar = false; + } else if (!anchor) { + this->message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path")); + } + + } else { + if (anchor && !this->anchor_statusbar) { + this->message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point.")); + this->anchor_statusbar = true; + } else if (!anchor && this->anchor_statusbar) { + this->message_context->clear(); + this->anchor_statusbar = false; + } + } + + // Show the pre-snap indicator to communicate to the user where we would snap to if he/she were to + // a) press the mousebutton to start a freehand drawing, or + // b) release the mousebutton to finish a freehand drawing + if (!this->sp_event_context_knot_mouseover()) { + SnapManager &m = dt->namedview->snap_manager; + m.setup(dt); + m.preSnap(Inkscape::SnapCandidatePoint(p, Inkscape::SNAPSOURCE_NODE_HANDLE)); + m.unSetup(); + } + break; + } + return ret; +} + +gint PencilTool::_handleButtonRelease(GdkEventButton const &revent) { + gint ret = FALSE; + + ToolBase *event_context = SP_EVENT_CONTEXT(this); + if ( revent.button == 1 && this->is_drawing && !event_context->space_panning) { + SPDesktop *const dt = this->desktop; + + this->is_drawing = false; + + /* Find desktop coordinates */ + Geom::Point p = dt->w2d(Geom::Point(revent.x, revent.y)); + + /* Test whether we hit any anchor. */ + SPDrawAnchor *anchor = spdc_test_inside(this, Geom::Point(revent.x, + revent.y)); + + switch (this->state) { + case SP_PENCIL_CONTEXT_IDLE: + /* Releasing button in idle mode means single click */ + /* We have already set up start point/anchor in button_press */ + if (!(revent.state & GDK_CONTROL_MASK)) { + // Ctrl+click creates a single point so only set context in ADDLINE mode when Ctrl isn't pressed + this->state = SP_PENCIL_CONTEXT_ADDLINE; + } + ret = TRUE; + break; + case SP_PENCIL_CONTEXT_ADDLINE: + /* Finish segment now */ + if (anchor) { + p = anchor->dp; + } else { + this->_endpointSnap(p, revent.state); + } + this->ea = anchor; + this->_setEndpoint(p); + this->_finishEndpoint(); + this->state = SP_PENCIL_CONTEXT_IDLE; + sp_event_context_discard_delayed_snap_event(event_context); + ret = TRUE; + break; + case SP_PENCIL_CONTEXT_FREEHAND: + if (revent.state & GDK_MOD1_MASK) { + /* sketch mode: interpolate the sketched path and improve the current output path with the new interpolation. don't finish sketch */ + + this->_sketchInterpolate(); + + if (this->green_anchor) { + this->green_anchor = sp_draw_anchor_destroy(this->green_anchor); + } + + this->state = SP_PENCIL_CONTEXT_SKETCH; + } else { + /* Finish segment now */ + /// \todo fixme: Clean up what follows (Lauris) + if (anchor) { + p = anchor->dp; + } else { + Geom::Point p_end = p; + this->_endpointSnap(p_end, revent.state); + if (p_end != p) { + // then we must have snapped! + this->_addFreehandPoint(p_end, revent.state); + } + } + + this->ea = anchor; + /* Write curves to object */ + + dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand")); + + this->_interpolate(); + spdc_concat_colors_and_flush(this, FALSE); + this->sa = NULL; + this->ea = NULL; + if (this->green_anchor) { + this->green_anchor = sp_draw_anchor_destroy(this->green_anchor); + } + this->state = SP_PENCIL_CONTEXT_IDLE; + // reset sketch mode too + this->sketch_n = 0; + } + ret = TRUE; + break; + case SP_PENCIL_CONTEXT_SKETCH: + default: + break; + } + + if (this->grab) { + /* Release grab now */ + sp_canvas_item_ungrab(this->grab, revent.time); + this->grab = NULL; + } + + ret = TRUE; + } + return ret; +} + +void PencilTool::_cancel() { + if (this->grab) { + /* Release grab now */ + sp_canvas_item_ungrab(this->grab, 0); + this->grab = NULL; + } + + this->is_drawing = false; + this->state = SP_PENCIL_CONTEXT_IDLE; + sp_event_context_discard_delayed_snap_event(SP_EVENT_CONTEXT(this)); + + this->red_curve->reset(); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), NULL); + while (this->green_bpaths) { + sp_canvas_item_destroy(SP_CANVAS_ITEM(this->green_bpaths->data)); + this->green_bpaths = g_slist_remove(this->green_bpaths, this->green_bpaths->data); + } + this->green_curve->reset(); + if (this->green_anchor) { + this->green_anchor = sp_draw_anchor_destroy(this->green_anchor); + } + + this->message_context->clear(); + this->message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled")); + + this->desktop->canvas->endForcedFullRedraws(); +} + +gint PencilTool::_handleKeyPress(guint const keyval, guint const state) { + gint ret = FALSE; + switch (keyval) { + case GDK_KEY_Up: + case GDK_KEY_Down: + case GDK_KEY_KP_Up: + case GDK_KEY_KP_Down: + // Prevent the zoom field from activation. + if (!mod_ctrl_only(state)) { + ret = TRUE; + } + break; + case GDK_KEY_Escape: + if (this->npoints != 0) { + // if drawing, cancel, otherwise pass it up for deselecting + if (this->state != SP_PENCIL_CONTEXT_IDLE) { + this->_cancel(); + ret = TRUE; + } + } + break; + case GDK_KEY_z: + case GDK_KEY_Z: + if (mod_ctrl_only(state) && this->npoints != 0) { + // if drawing, cancel, otherwise pass it up for undo + if (this->state != SP_PENCIL_CONTEXT_IDLE) { + this->_cancel(); + ret = TRUE; + } + } + break; + case GDK_KEY_g: + case GDK_KEY_G: + if (mod_shift_only(state)) { + sp_selection_to_guides(SP_EVENT_CONTEXT(this)->desktop); + ret = true; + } + break; + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + case GDK_KEY_Meta_L: + case GDK_KEY_Meta_R: + if (this->state == SP_PENCIL_CONTEXT_IDLE) { + this->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("<b>Sketch mode</b>: holding <b>Alt</b> interpolates between sketched paths. Release <b>Alt</b> to finalize.")); + } + break; + default: + break; + } + return ret; +} + +gint PencilTool::_handleKeyRelease(guint const keyval, guint const /*state*/) { + gint ret = FALSE; + switch (keyval) { + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + case GDK_KEY_Meta_L: + case GDK_KEY_Meta_R: + if (this->state == SP_PENCIL_CONTEXT_SKETCH) { + spdc_concat_colors_and_flush(this, FALSE); + this->sketch_n = 0; + this->sa = NULL; + this->ea = NULL; + if (this->green_anchor) { + this->green_anchor = sp_draw_anchor_destroy(this->green_anchor); + } + this->state = SP_PENCIL_CONTEXT_IDLE; + sp_event_context_discard_delayed_snap_event(SP_EVENT_CONTEXT(this)); + this->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand sketch")); + ret = TRUE; + } + break; + default: + break; + } + return ret; +} + +/** + * Reset points and set new starting point. + */ +void PencilTool::_setStartpoint(Geom::Point const &p) { + this->npoints = 0; + this->red_curve_is_valid = false; + if (in_svg_plane(p)) { + this->p[this->npoints++] = p; + } +} + +/** + * Change moving endpoint position. + * <ul> + * <li>Ctrl constrains to moving to H/V direction, snapping in given direction. + * <li>Otherwise we snap freely to whatever attractors are available. + * </ul> + * + * Number of points is (re)set to 2 always, 2nd point is modified. + * We change RED curve. + */ +void PencilTool::_setEndpoint(Geom::Point const &p) { + if (this->npoints == 0) { + return; + /* May occur if first point wasn't in SVG plane (e.g. weird w2d transform, perhaps from bad + * zoom setting). + */ + } + g_return_if_fail( this->npoints > 0 ); + + this->red_curve->reset(); + if ( ( p == this->p[0] ) + || !in_svg_plane(p) ) + { + this->npoints = 1; + } else { + this->p[1] = p; + this->npoints = 2; + + this->red_curve->moveto(this->p[0]); + this->red_curve->lineto(this->p[1]); + this->red_curve_is_valid = true; + + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), this->red_curve); + } +} + +/** + * Finalize addline. + * + * \todo + * fixme: I'd like remove red reset from concat colors (lauris). + * Still not sure, how it will make most sense. + */ +void PencilTool::_finishEndpoint() { + if ( ( this->red_curve->is_empty() ) + || ( *(this->red_curve->first_point()) == *(this->red_curve->second_point()) ) ) + { + this->red_curve->reset(); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), NULL); + } else { + /* Write curves to object. */ + spdc_concat_colors_and_flush(this, FALSE); + this->sa = NULL; + this->ea = NULL; + } +} + +void PencilTool::_addFreehandPoint(Geom::Point const &p, guint /*state*/) { + g_assert( this->npoints > 0 ); + g_return_if_fail(unsigned(this->npoints) < G_N_ELEMENTS(this->p)); + + if ( ( p != this->p[ this->npoints - 1 ] ) + && in_svg_plane(p) ) + { + this->ps.push_back(p); + this->p[this->npoints++] = p; + this->_fitAndSplit(); + } +} + +static inline double +square(double const x) +{ + return x * x; +} + +void PencilTool::_interpolate() { + if ( this->ps.size() <= 1 ) { + return; + } + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4; + double const tolerance_sq = 0.02 * square( this->desktop->w2d().descrim() * + tol) * exp(0.2*tol - 2); + + g_assert(is_zero(this->req_tangent) + || is_unit_vector(this->req_tangent)); + Geom::Point const tHatEnd(0, 0); + + guint n_points = this->ps.size(); + this->green_curve->reset(); + this->red_curve->reset(); + this->red_curve_is_valid = false; + + Geom::Point * b = g_new(Geom::Point, 4*n_points); + Geom::Point * points = g_new(Geom::Point, 4*n_points); + for (unsigned int i = 0; i < this->ps.size(); i++) { + points[i] = this->ps[i]; + } + + // worst case gives us a segment per point + int max_segs = 4*n_points; + + int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points, + tolerance_sq, max_segs); + + if ( n_segs > 0) + { + /* Fit and draw and reset state */ + this->green_curve->moveto(b[0]); + for (int c = 0; c < n_segs; c++) { + this->green_curve->curveto(b[4*c+1], b[4*c+2], b[4*c+3]); + } + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), this->green_curve); + + /* Fit and draw and copy last point */ + g_assert(!this->green_curve->is_empty()); + + /* Set up direction of next curve. */ + { + Geom::Curve const * last_seg = this->green_curve->last_segment(); + g_assert( last_seg ); // Relevance: validity of (*last_seg) + this->p[0] = last_seg->finalPoint(); + this->npoints = 1; + Geom::Curve *last_seg_reverse = last_seg->reverse(); + Geom::Point const req_vec( -last_seg_reverse->unitTangentAt(0) ); + delete last_seg_reverse; + this->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) ) + ? Geom::Point(0, 0) + : Geom::unit_vector(req_vec) ); + } + } + g_free(b); + g_free(points); + this->ps.clear(); +} + + +/* interpolates the sketched curve and tweaks the current sketch interpolation*/ +void PencilTool::_sketchInterpolate() { + if ( this->ps.size() <= 1 ) { + return; + } + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4; + double const tolerance_sq = 0.02 * square( this->desktop->w2d().descrim() * + tol) * exp(0.2*tol - 2); + + bool average_all_sketches = prefs->getBool("/tools/freehand/pencil/average_all_sketches", true); + + g_assert(is_zero(this->req_tangent) + || is_unit_vector(this->req_tangent)); + Geom::Point const tHatEnd(0, 0); + + guint n_points = this->ps.size(); + this->red_curve->reset(); + this->red_curve_is_valid = false; + + Geom::Point * b = g_new(Geom::Point, 4*n_points); + Geom::Point * points = g_new(Geom::Point, 4*n_points); + for (unsigned i = 0; i < this->ps.size(); i++) { + points[i] = this->ps[i]; + } + + // worst case gives us a segment per point + int max_segs = 4*n_points; + + int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points, + tolerance_sq, max_segs); + + if ( n_segs > 0) + { + Geom::Path fit(b[0]); + for (int c = 0; c < n_segs; c++) { + fit.appendNew<Geom::CubicBezier>(b[4*c+1], b[4*c+2], b[4*c+3]); + } + Geom::Piecewise<Geom::D2<Geom::SBasis> > fit_pwd2 = fit.toPwSb(); + + if ( this->sketch_n > 0 ) { + double t =0.; + if (average_all_sketches) { + // Average = (sum of all) / n + // = (sum of all + new one) / n+1 + // = ((old average)*n + new one) / n+1 + t = this->sketch_n / (this->sketch_n + 1.); + } else { + t = 0.5; + } + this->sketch_interpolation = Geom::lerp(t, fit_pwd2, this->sketch_interpolation); + // simplify path, to eliminate small segments + Path *path = new Path; + path->LoadPathVector(Geom::path_from_piecewise(this->sketch_interpolation, 0.01)); + path->Simplify(0.5); + Geom::PathVector *pathv = path->MakePathVector(); + this->sketch_interpolation = (*pathv)[0].toPwSb(); + delete path; + delete pathv; + } else { + this->sketch_interpolation = fit_pwd2; + } + this->sketch_n++; + + this->green_curve->reset(); + this->green_curve->set_pathvector(Geom::path_from_piecewise(this->sketch_interpolation, 0.01)); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), this->green_curve); + + /* Fit and draw and copy last point */ + g_assert(!this->green_curve->is_empty()); + + /* Set up direction of next curve. */ + { + Geom::Curve const * last_seg = this->green_curve->last_segment(); + g_assert( last_seg ); // Relevance: validity of (*last_seg) + this->p[0] = last_seg->finalPoint(); + this->npoints = 1; + Geom::Curve *last_seg_reverse = last_seg->reverse(); + Geom::Point const req_vec( -last_seg_reverse->unitTangentAt(0) ); + delete last_seg_reverse; + this->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) ) + ? Geom::Point(0, 0) + : Geom::unit_vector(req_vec) ); + } + } + g_free(b); + g_free(points); + this->ps.clear(); +} + +void PencilTool::_fitAndSplit() { + g_assert( this->npoints > 1 ); + + double const tolerance_sq = 0; + + Geom::Point b[4]; + g_assert(is_zero(this->req_tangent) + || is_unit_vector(this->req_tangent)); + Geom::Point const tHatEnd(0, 0); + int const n_segs = Geom::bezier_fit_cubic_full(b, NULL, this->p, this->npoints, + this->req_tangent, tHatEnd, + tolerance_sq, 1); + if ( n_segs > 0 + && unsigned(this->npoints) < G_N_ELEMENTS(this->p) ) + { + /* Fit and draw and reset state */ + this->red_curve->reset(); + this->red_curve->moveto(b[0]); + this->red_curve->curveto(b[1], b[2], b[3]); + sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(this->red_bpath), this->red_curve); + this->red_curve_is_valid = true; + } else { + /* Fit and draw and copy last point */ + + g_assert(!this->red_curve->is_empty()); + + /* Set up direction of next curve. */ + { + Geom::Curve const * last_seg = this->red_curve->last_segment(); + g_assert( last_seg ); // Relevance: validity of (*last_seg) + this->p[0] = last_seg->finalPoint(); + this->npoints = 1; + Geom::Curve *last_seg_reverse = last_seg->reverse(); + Geom::Point const req_vec( -last_seg_reverse->unitTangentAt(0) ); + delete last_seg_reverse; + this->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) ) + ? Geom::Point(0, 0) + : Geom::unit_vector(req_vec) ); + } + + + this->green_curve->append_continuous(this->red_curve, 0.0625); + SPCurve *curve = this->red_curve->copy(); + + /// \todo fixme: + SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(this->desktop), curve); + curve->unref(); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), this->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + + this->green_bpaths = g_slist_prepend(this->green_bpaths, cshape); + + this->red_curve_is_valid = false; + } +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/pencil-tool.h b/src/ui/tools/pencil-tool.h new file mode 100644 index 000000000..efc1f60e0 --- /dev/null +++ b/src/ui/tools/pencil-tool.h @@ -0,0 +1,86 @@ +#ifndef SEEN_PENCIL_CONTEXT_H +#define SEEN_PENCIL_CONTEXT_H + +/** \file + * PencilTool: a context for pencil tool events + */ + +#include "ui/tools/freehand-base.h" + +#define SP_PENCIL_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::PencilTool*>((ToolBase*)obj)) +#define SP_IS_PENCIL_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::PencilTool*>((const ToolBase*)obj) != NULL) + +namespace Inkscape { +namespace UI { +namespace Tools { + +enum PencilState { + SP_PENCIL_CONTEXT_IDLE, + SP_PENCIL_CONTEXT_ADDLINE, + SP_PENCIL_CONTEXT_FREEHAND, + SP_PENCIL_CONTEXT_SKETCH +}; + +/** + * PencilTool: a context for pencil tool events + */ +class PencilTool : public FreehandBase { +public: + PencilTool(); + virtual ~PencilTool(); + + Geom::Point p[16]; + gint npoints; + PencilState state; + Geom::Point req_tangent; + + bool is_drawing; + + std::vector<Geom::Point> ps; + + Geom::Piecewise<Geom::D2<Geom::SBasis> > sketch_interpolation; // the current proposal from the sketched paths + unsigned sketch_n; // number of sketches done + + static const std::string prefsPath; + + virtual const std::string& getPrefsPath(); + +protected: + virtual void setup(); + virtual bool root_handler(GdkEvent* event); + +private: + gint _handleButtonPress(GdkEventButton const &bevent); + gint _handleMotionNotify(GdkEventMotion const &mevent); + gint _handleButtonRelease(GdkEventButton const &revent); + gint _handleKeyPress(guint const keyval, guint const state); + gint _handleKeyRelease(guint const keyval, guint const state); + + void _setStartpoint(Geom::Point const &p); + void _setEndpoint(Geom::Point const &p); + void _finishEndpoint(); + void _addFreehandPoint(Geom::Point const &p, guint state); + void _fitAndSplit(); + void _interpolate(); + void _sketchInterpolate(); + + void _cancel(); + void _endpointSnap(Geom::Point &p, guint const state); +}; + +} +} +} + +#endif /* !SEEN_PENCIL_CONTEXT_H */ + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/rect-tool.cpp b/src/ui/tools/rect-tool.cpp new file mode 100644 index 000000000..39f422c1a --- /dev/null +++ b/src/ui/tools/rect-tool.cpp @@ -0,0 +1,519 @@ +/* + * Rectangle drawing context + * + * Author: + * Lauris Kaplinski <lauris@kaplinski.com> + * bulia byak <buliabyak@users.sf.net> + * Jon A. Cruz <jon@joncruz.org> + * Abhishek Sharma + * + * Copyright (C) 2006 Johan Engelen <johan@shouraizou.nl> + * Copyright (C) 2000-2005 authors + * Copyright (C) 2000-2001 Ximian, Inc. + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "config.h" + +#include <gdk/gdkkeysyms.h> +#include <cstring> +#include <string> + +#include "macros.h" +#include "display/sp-canvas.h" +#include "sp-rect.h" +#include "document.h" +#include "document-undo.h" +#include "sp-namedview.h" +#include "selection.h" +#include "selection-chemistry.h" +#include "desktop-handles.h" +#include "snap.h" +#include "desktop.h" +#include "desktop-style.h" +#include "message-context.h" +#include "pixmaps/cursor-rect.xpm" +#include "ui/tools/rect-tool.h" +#include <glibmm/i18n.h> +#include "xml/repr.h" +#include "xml/node-event-vector.h" +#include "preferences.h" +#include "context-fns.h" +#include "shape-editor.h" +#include "verbs.h" +#include "display/sp-canvas-item.h" + +using Inkscape::DocumentUndo; + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +namespace { + ToolBase* createRectContext() { + return new RectTool(); + } + + bool rectContextRegistered = ToolFactory::instance().registerObject("/tools/shapes/rect", createRectContext); +} + +const std::string& RectTool::getPrefsPath() { + return RectTool::prefsPath; +} + +const std::string RectTool::prefsPath = "/tools/shapes/rect"; + +RectTool::RectTool() + : ToolBase(cursor_rect_xpm, 4, 4) + , rect(NULL) + , rx(0) + , ry(0) +{ +} + +void RectTool::finish() { + sp_canvas_item_ungrab(SP_CANVAS_ITEM(this->desktop->acetate), GDK_CURRENT_TIME); + + this->finishItem(); + this->sel_changed_connection.disconnect(); + + ToolBase::finish(); +} + +RectTool::~RectTool() { + this->enableGrDrag(false); + + this->sel_changed_connection.disconnect(); + + delete this->shape_editor; + this->shape_editor = NULL; + + /* fixme: This is necessary because we do not grab */ + if (this->rect) { + this->finishItem(); + } +} + +/** + * Callback that processes the "changed" signal on the selection; + * destroys old and creates new knotholder. + */ +void RectTool::selection_changed(Inkscape::Selection* selection) { + this->shape_editor->unset_item(SH_KNOTHOLDER); + this->shape_editor->set_item(selection->singleItem(), SH_KNOTHOLDER); +} + +void RectTool::setup() { + ToolBase::setup(); + + this->shape_editor = new ShapeEditor(this->desktop); + + SPItem *item = sp_desktop_selection(this->desktop)->singleItem(); + if (item) { + this->shape_editor->set_item(item, SH_KNOTHOLDER); + } + + this->sel_changed_connection.disconnect(); + this->sel_changed_connection = sp_desktop_selection(this->desktop)->connectChanged( + sigc::mem_fun(this, &RectTool::selection_changed) + ); + + sp_event_context_read(this, "rx"); + sp_event_context_read(this, "ry"); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/tools/shapes/selcue")) { + this->enableSelectionCue(); + } + + if (prefs->getBool("/tools/shapes/gradientdrag")) { + this->enableGrDrag(); + } +} + +void RectTool::set(const Inkscape::Preferences::Entry& val) { + /* fixme: Proper error handling for non-numeric data. Use a locale-independent function like + * g_ascii_strtod (or a thin wrapper that does the right thing for invalid values inf/nan). */ + Glib::ustring name = val.getEntryName(); + + if ( name == "rx" ) { + this->rx = val.getDoubleLimited(); // prevents NaN and +/-Inf from messing up + } else if ( name == "ry" ) { + this->ry = val.getDoubleLimited(); + } +} + +bool RectTool::item_handler(SPItem* item, GdkEvent* event) { + gint ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + if ( event->button.button == 1 && !this->space_panning) { + Inkscape::setup_for_drag_start(desktop, this, event); + ret = TRUE; + } + break; + // motion and release are always on root (why?) + default: + break; + } + + ret = ToolBase::item_handler(item, event); + + return ret; +} + +bool RectTool::root_handler(GdkEvent* event) { + static bool dragging; + + SPDesktop *desktop = this->desktop; + Inkscape::Selection *selection = sp_desktop_selection (desktop); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + this->tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + + gint ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + Geom::Point const button_w(event->button.x, event->button.y); + + // save drag origin + this->xp = (gint) button_w[Geom::X]; + this->yp = (gint) button_w[Geom::Y]; + this->within_tolerance = true; + + // remember clicked item, disregarding groups, honoring Alt + this->item_to_select = sp_event_context_find_item (desktop, button_w, event->button.state & GDK_MOD1_MASK, TRUE); + + dragging = true; + + /* Position center */ + Geom::Point button_dt(desktop->w2d(button_w)); + this->center = button_dt; + + /* Snap center */ + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + m.freeSnapReturnByRef(button_dt, Inkscape::SNAPSOURCE_NODE_HANDLE); + m.unSetup(); + this->center = button_dt; + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + ( GDK_KEY_PRESS_MASK | + GDK_BUTTON_RELEASE_MASK | + GDK_POINTER_MOTION_MASK | + GDK_POINTER_MOTION_HINT_MASK | + GDK_BUTTON_PRESS_MASK ), + NULL, event->button.time); + + ret = TRUE; + } + break; + case GDK_MOTION_NOTIFY: + if ( dragging + && (event->motion.state & GDK_BUTTON1_MASK) && !this->space_panning) + { + if ( this->within_tolerance + && ( abs( (gint) event->motion.x - this->xp ) < this->tolerance ) + && ( abs( (gint) event->motion.y - this->yp ) < this->tolerance ) ) { + break; // do not drag if we're within tolerance from origin + } + // Once the user has moved farther than tolerance from the original location + // (indicating they intend to draw, not click), then always process the + // motion notify coordinates as given (no snapping back to origin) + this->within_tolerance = false; + + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); + + this->drag(motion_dt, event->motion.state); // this will also handle the snapping + gobble_motion_events(GDK_BUTTON1_MASK); + ret = TRUE; + } else if (!this->sp_event_context_knot_mouseover()) { + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); + + m.preSnap(Inkscape::SnapCandidatePoint(motion_dt, Inkscape::SNAPSOURCE_NODE_HANDLE)); + m.unSetup(); + } + break; + case GDK_BUTTON_RELEASE: + this->xp = this->yp = 0; + if (event->button.button == 1 && !this->space_panning) { + dragging = false; + sp_event_context_discard_delayed_snap_event(this); + + if (!this->within_tolerance) { + // we've been dragging, finish the rect + this->finishItem(); + } else if (this->item_to_select) { + // no dragging, select clicked item if any + if (event->button.state & GDK_SHIFT_MASK) { + selection->toggle(this->item_to_select); + } else { + selection->set(this->item_to_select); + } + } else { + // click in an empty space + selection->clear(); + } + + this->item_to_select = NULL; + ret = TRUE; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), + event->button.time); + } + break; + case GDK_KEY_PRESS: + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + case GDK_KEY_Meta_L: // Meta is when you press Shift+Alt (at least on my machine) + case GDK_KEY_Meta_R: + if (!dragging){ + sp_event_show_modifier_tip (this->defaultMessageContext(), event, + _("<b>Ctrl</b>: make square or integer-ratio rect, lock a rounded corner circular"), + _("<b>Shift</b>: draw around the starting point"), + NULL); + } + break; + case GDK_KEY_Up: + case GDK_KEY_Down: + case GDK_KEY_KP_Up: + case GDK_KEY_KP_Down: + // prevent the zoom field from activation + if (!MOD__CTRL_ONLY(event)) + ret = TRUE; + break; + + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo ("altx-rect"); + ret = TRUE; + } + break; + + case GDK_KEY_g: + case GDK_KEY_G: + if (MOD__SHIFT_ONLY(event)) { + sp_selection_to_guides(desktop); + ret = true; + } + break; + + case GDK_KEY_Escape: + if (dragging) { + dragging = false; + sp_event_context_discard_delayed_snap_event(this); + // if drawing, cancel, otherwise pass it up for deselecting + this->cancel(); + ret = TRUE; + } + break; + + case GDK_KEY_space: + if (dragging) { + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), + event->button.time); + dragging = false; + sp_event_context_discard_delayed_snap_event(this); + + if (!this->within_tolerance) { + // we've been dragging, finish the rect + this->finishItem(); + } + // do not return true, so that space would work switching to selector + } + break; + + case GDK_KEY_Delete: + case GDK_KEY_KP_Delete: + case GDK_KEY_BackSpace: + ret = this->deleteSelectedDrag(MOD__CTRL_ONLY(event)); + break; + + default: + break; + } + break; + case GDK_KEY_RELEASE: + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + case GDK_KEY_Meta_L: // Meta is when you press Shift+Alt + case GDK_KEY_Meta_R: + this->defaultMessageContext()->clear(); + break; + default: + break; + } + break; + default: + break; + } + + if (!ret) { + ret = ToolBase::root_handler(event); + } + + return ret; +} + +void RectTool::drag(Geom::Point const pt, guint state) { + SPDesktop *desktop = this->desktop; + + if (!this->rect) { + if (Inkscape::have_viable_layer(desktop, this->message_context) == false) { + return; + } + + // Create object + Inkscape::XML::Document *xml_doc = this->desktop->doc()->getReprDoc(); + Inkscape::XML::Node *repr = xml_doc->createElement("svg:rect"); + + // Set style + sp_desktop_apply_style_tool (desktop, repr, "/tools/shapes/rect", false); + + this->rect = SP_RECT(desktop->currentLayer()->appendChildRepr(repr)); + Inkscape::GC::release(repr); + + this->rect->transform = SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); + this->rect->updateRepr(); + + desktop->canvas->forceFullRedrawAfterInterruptions(5); + } + + Geom::Rect const r = Inkscape::snap_rectangular_box(desktop, this->rect, pt, this->center, state); + + this->rect->setPosition(r.min()[Geom::X], r.min()[Geom::Y], r.dimensions()[Geom::X], r.dimensions()[Geom::Y]); + + if (this->rx != 0.0) { + this->rect->setRx(true, this->rx); + } + + if (this->ry != 0.0) { + if (this->rx == 0.0) + this->rect->setRy(true, CLAMP(this->ry, 0, MIN(r.dimensions()[Geom::X], r.dimensions()[Geom::Y])/2)); + else + this->rect->setRy(true, CLAMP(this->ry, 0, r.dimensions()[Geom::Y])); + } + + // status text + double rdimx = r.dimensions()[Geom::X]; + double rdimy = r.dimensions()[Geom::Y]; + + Inkscape::Util::Quantity rdimx_q = Inkscape::Util::Quantity(rdimx, "px"); + Inkscape::Util::Quantity rdimy_q = Inkscape::Util::Quantity(rdimy, "px"); + GString *xs = g_string_new(rdimx_q.string(desktop->namedview->doc_units).c_str()); + GString *ys = g_string_new(rdimy_q.string(desktop->namedview->doc_units).c_str()); + + if (state & GDK_CONTROL_MASK) { + int ratio_x, ratio_y; + bool is_golden_ratio = false; + + if (fabs (rdimx) > fabs (rdimy)) { + if (fabs(rdimx / rdimy - goldenratio) < 1e-6) { + is_golden_ratio = true; + } + + ratio_x = (int) rint (rdimx / rdimy); + ratio_y = 1; + } else { + if (fabs(rdimy / rdimx - goldenratio) < 1e-6) { + is_golden_ratio = true; + } + + ratio_x = 1; + ratio_y = (int) rint (rdimy / rdimx); + } + + if (!is_golden_ratio) { + this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Rectangle</b>: %s × %s (constrained to ratio %d:%d); with <b>Shift</b> to draw around the starting point"), xs->str, ys->str, ratio_x, ratio_y); + } else { + if (ratio_y == 1) { + this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Rectangle</b>: %s × %s (constrained to golden ratio 1.618 : 1); with <b>Shift</b> to draw around the starting point"), xs->str, ys->str); + } else { + this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Rectangle</b>: %s × %s (constrained to golden ratio 1 : 1.618); with <b>Shift</b> to draw around the starting point"), xs->str, ys->str); + } + } + } else { + this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Rectangle</b>: %s × %s; with <b>Ctrl</b> to make square or integer-ratio rectangle; with <b>Shift</b> to draw around the starting point"), xs->str, ys->str); + } + + g_string_free(xs, FALSE); + g_string_free(ys, FALSE); +} + +void RectTool::finishItem() { + this->message_context->clear(); + + if (this->rect != NULL) { + if (this->rect->width.computed == 0 || this->rect->height.computed == 0) { + this->cancel(); // Don't allow the creating of zero sized rectangle, for example when the start and and point snap to the snap grid point + return; + } + + this->rect->updateRepr(); + this->rect->doWriteTransform(this->rect->getRepr(), this->rect->transform, NULL, true); + + this->desktop->canvas->endForcedFullRedraws(); + + sp_desktop_selection(this->desktop)->set(this->rect); + + DocumentUndo::done(sp_desktop_document(this->desktop), SP_VERB_CONTEXT_RECT, _("Create rectangle")); + + this->rect = NULL; + } +} + +void RectTool::cancel(){ + sp_desktop_selection(this->desktop)->clear(); + sp_canvas_item_ungrab(SP_CANVAS_ITEM(this->desktop->acetate), 0); + + if (this->rect != NULL) { + this->rect->deleteObject(); + this->rect = NULL; + } + + this->within_tolerance = false; + this->xp = 0; + this->yp = 0; + this->item_to_select = NULL; + + this->desktop->canvas->endForcedFullRedraws(); + + DocumentUndo::cancel(sp_desktop_document(this->desktop)); +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/rect-tool.h b/src/ui/tools/rect-tool.h new file mode 100644 index 000000000..a50fd7b24 --- /dev/null +++ b/src/ui/tools/rect-tool.h @@ -0,0 +1,65 @@ +#ifndef __SP_RECT_CONTEXT_H__ +#define __SP_RECT_CONTEXT_H__ + +/* + * Rectangle drawing context + * + * Author: + * Lauris Kaplinski <lauris@kaplinski.com> + * + * Copyright (C) 2000 Lauris Kaplinski + * Copyright (C) 2000-2001 Ximian, Inc. + * Copyright (C) 2002 Lauris Kaplinski + * + * Released under GNU GPL + */ + +#include <stddef.h> +#include <sigc++/sigc++.h> +#include <2geom/point.h> +#include "ui/tools/tool-base.h" + +#include "sp-rect.h" + +#define SP_RECT_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::RectTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_RECT_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::RectTool*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +namespace Inkscape { +namespace UI { +namespace Tools { + +class RectTool : public ToolBase { +public: + RectTool(); + virtual ~RectTool(); + + static const std::string prefsPath; + + virtual void setup(); + virtual void finish(); + virtual void set(const Inkscape::Preferences::Entry& val); + virtual bool root_handler(GdkEvent* event); + virtual bool item_handler(SPItem* item, GdkEvent* event); + + virtual const std::string& getPrefsPath(); + +private: + SPRect *rect; + Geom::Point center; + + gdouble rx; /* roundness radius (x direction) */ + gdouble ry; /* roundness radius (y direction) */ + + sigc::connection sel_changed_connection; + + void drag(Geom::Point const pt, guint state); + void finishItem(); + void cancel(); + void selection_changed(Inkscape::Selection* selection); +}; + +} +} +} + +#endif diff --git a/src/ui/tools/select-tool.cpp b/src/ui/tools/select-tool.cpp new file mode 100644 index 000000000..83bef17c9 --- /dev/null +++ b/src/ui/tools/select-tool.cpp @@ -0,0 +1,1240 @@ +/* + * Selection and transformation context + * + * Authors: + * Lauris Kaplinski <lauris@kaplinski.com> + * bulia byak <buliabyak@users.sf.net> + * Abhishek Sharma + * Jon A. Cruz <jon@joncruz.org> + * + * Copyright (C) 2010 authors + * Copyright (C) 2006 Johan Engelen <johan@shouraizou.nl> + * Copyright (C) 1999-2005 Authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif +#include <cstring> +#include <string> +#include <gdk/gdkkeysyms.h> +#include "macros.h" +#include "rubberband.h" +#include "document.h" +#include "document-undo.h" +#include "selection.h" +#include "sp-cursor.h" +#include "style.h" +#include "pixmaps/cursor-select-m.xpm" +#include "pixmaps/cursor-select-d.xpm" +#include "pixmaps/handles.xpm" +#include <glibmm/i18n.h> + +#include "ui/tools/select-tool.h" +#include "selection-chemistry.h" +#ifdef WITH_DBUS +#include "extension/dbus/document-interface.h" +#endif +#include "desktop.h" +#include "desktop-handles.h" +#include "sp-root.h" +#include "preferences.h" +#include "tools-switch.h" +#include "message-stack.h" +#include "selection-describer.h" +#include "seltrans.h" +#include "box3d.h" +#include "display/sp-canvas.h" +#include "display/sp-canvas-item.h" +#include "display/drawing-item.h" +#include "tool-factory.h" + +using Inkscape::DocumentUndo; + +GdkPixbuf *handles[13]; + +namespace Inkscape { +namespace UI { +namespace Tools { + +static GdkCursor *CursorSelectMouseover = NULL; +static GdkCursor *CursorSelectDragging = NULL; + +static gint rb_escaped = 0; // if non-zero, rubberband was canceled by esc, so the next button release should not deselect +static gint drag_escaped = 0; // if non-zero, drag was canceled by esc + +namespace { + ToolBase* createSelectContext() { + return new SelectTool(); + } + + bool selectContextRegistered = ToolFactory::instance().registerObject("/tools/select", createSelectContext); +} + +const std::string& SelectTool::getPrefsPath() { + return SelectTool::prefsPath; +} + +const std::string SelectTool::prefsPath = "/tools/select"; + + +//Creates rotated variations for handles +static void +sp_load_handles(int start, int count, char const **xpm) { + handles[start] = gdk_pixbuf_new_from_xpm_data((gchar const **)xpm); + for(int i = start + 1; i < start + count; i++) { + // We use either the original at *start or previous loop item to rotate + handles[i] = gdk_pixbuf_rotate_simple(handles[i-1], GDK_PIXBUF_ROTATE_CLOCKWISE); + } +} + +SelectTool::SelectTool() + // Don't load a default cursor + : ToolBase(NULL, 0, 0) + , dragging(false) + , moved(false) + , button_press_shift(false) + , button_press_ctrl(false) + , button_press_alt(false) + , cycling_items(NULL) + , cycling_items_cmp(NULL) + , cycling_items_selected_before(NULL) + , cycling_cur_item(NULL) + , cycling_wrap(true) + , item(NULL) + , grabbed(NULL) + , _seltrans(NULL) + , _describer(NULL) +{ + // cursors in select context + CursorSelectMouseover = sp_cursor_new_from_xpm(cursor_select_m_xpm , 1, 1); + CursorSelectDragging = sp_cursor_new_from_xpm(cursor_select_d_xpm , 1, 1); + + // selection handles + sp_load_handles(0, 2, handle_scale_xpm); + sp_load_handles(2, 2, handle_stretch_xpm); + sp_load_handles(4, 4, handle_rotate_xpm); + sp_load_handles(8, 4, handle_skew_xpm); + sp_load_handles(12, 1, handle_center_xpm); +} + +//static gint xp = 0, yp = 0; // where drag started +//static gint tolerance = 0; +//static bool within_tolerance = false; +static bool is_cycling = false; +static bool moved_while_cycling = false; + + +SelectTool::~SelectTool() { + this->enableGrDrag(false); + + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed, GDK_CURRENT_TIME); + this->grabbed = NULL; + } + + delete this->_seltrans; + this->_seltrans = NULL; + + delete this->_describer; + this->_describer = NULL; + + if (CursorSelectDragging) { +#if GTK_CHECK_VERSION(3,0,0) + g_object_unref(CursorSelectDragging); +#else + gdk_cursor_unref (CursorSelectDragging); +#endif + CursorSelectDragging = NULL; + } + + if (CursorSelectMouseover) { +#if GTK_CHECK_VERSION(3,0,0) + g_object_unref(CursorSelectMouseover); +#else + gdk_cursor_unref (CursorSelectMouseover); +#endif + CursorSelectMouseover = NULL; + } +} + +void SelectTool::setup() { + ToolBase::setup(); + + this->_describer = new Inkscape::SelectionDescriber( + desktop->selection, + desktop->messageStack(), + _("Click selection to toggle scale/rotation handles"), + _("No objects selected. Click, Shift+click, Alt+scroll mouse on top of objects, or drag around objects to select.") + ); + + this->_seltrans = new Inkscape::SelTrans(desktop); + + sp_event_context_read(this, "show"); + sp_event_context_read(this, "transform"); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + if (prefs->getBool("/tools/select/gradientdrag")) { + this->enableGrDrag(); + } +} + +void SelectTool::set(const Inkscape::Preferences::Entry& val) { + Glib::ustring path = val.getEntryName(); + + if (path == "show") { + if (val.getString() == "outline") { + this->_seltrans->setShow(Inkscape::SelTrans::SHOW_OUTLINE); + } else { + this->_seltrans->setShow(Inkscape::SelTrans::SHOW_CONTENT); + } + } +} + +bool SelectTool::sp_select_context_abort() { + Inkscape::SelTrans *seltrans = this->_seltrans; + + if (this->dragging) { + if (this->moved) { // cancel dragging an object + seltrans->ungrab(); + this->moved = FALSE; + this->dragging = FALSE; + sp_event_context_discard_delayed_snap_event(this); + drag_escaped = 1; + + if (this->item) { + // only undo if the item is still valid + if (this->item->document) { + DocumentUndo::undo(sp_desktop_document(desktop)); + } + + sp_object_unref( this->item, NULL); + } else if (this->button_press_ctrl) { + // NOTE: This is a workaround to a bug. + // When the ctrl key is held, sc->item is not defined + // so in this case (only), we skip the object doc check + DocumentUndo::undo(sp_desktop_document(desktop)); + } + this->item = NULL; + + SP_EVENT_CONTEXT(this)->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Move canceled.")); + return true; + } + } else { + if (Inkscape::Rubberband::get(desktop)->is_started()) { + Inkscape::Rubberband::get(desktop)->stop(); + rb_escaped = 1; + SP_EVENT_CONTEXT(this)->defaultMessageContext()->clear(); + SP_EVENT_CONTEXT(this)->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Selection canceled.")); + return true; + } + } + return false; +} + +static bool +key_is_a_modifier (guint key) { + return (key == GDK_KEY_Alt_L || + key == GDK_KEY_Alt_R || + key == GDK_KEY_Control_L || + key == GDK_KEY_Control_R || + key == GDK_KEY_Shift_L || + key == GDK_KEY_Shift_R || + key == GDK_KEY_Meta_L || // Meta is when you press Shift+Alt (at least on my machine) + key == GDK_KEY_Meta_R); +} + +static void +sp_select_context_up_one_layer(SPDesktop *desktop) +{ + /* Click in empty place, go up one level -- but don't leave a layer to root. + * + * (Rationale: we don't usually allow users to go to the root, since that + * detracts from the layer metaphor: objects at the root level can in front + * of or behind layers. Whereas it's fine to go to the root if editing + * a document that has no layers (e.g. a non-Inkscape document).) + * + * Once we support editing SVG "islands" (e.g. <svg> embedded in an xhtml + * document), we might consider further restricting the below to disallow + * leaving a layer to go to a non-layer. + */ + SPObject *const current_layer = desktop->currentLayer(); + if (current_layer) { + SPObject *const parent = current_layer->parent; + if ( parent + && ( parent->parent + || !( SP_IS_GROUP(current_layer) + && ( SPGroup::LAYER + == SP_GROUP(current_layer)->layerMode() ) ) ) ) + { + desktop->setCurrentLayer(parent); + if (SP_IS_GROUP(current_layer) && SPGroup::LAYER != SP_GROUP(current_layer)->layerMode()) + sp_desktop_selection(desktop)->set(current_layer); + } + } +} + +bool SelectTool::item_handler(SPItem* item, GdkEvent* event) { + gint ret = FALSE; + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + + // make sure we still have valid objects to move around + if (this->item && this->item->document == NULL) { + this->sp_select_context_abort(); + } + + switch (event->type) { + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + /* Left mousebutton */ + + // save drag origin + xp = (gint) event->button.x; + yp = (gint) event->button.y; + within_tolerance = true; + + // remember what modifiers were on before button press + this->button_press_shift = (event->button.state & GDK_SHIFT_MASK) ? true : false; + this->button_press_ctrl = (event->button.state & GDK_CONTROL_MASK) ? true : false; + this->button_press_alt = (event->button.state & GDK_MOD1_MASK) ? true : false; + + if (event->button.state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK)) { + // if shift or ctrl was pressed, do not move objects; + // pass the event to root handler which will perform rubberband, shift-click, ctrl-click, ctrl-drag + } else { + GdkWindow* window = gtk_widget_get_window (GTK_WIDGET (sp_desktop_canvas(desktop))); + + this->dragging = TRUE; + this->moved = FALSE; + + gdk_window_set_cursor(window, CursorSelectDragging); + + desktop->canvas->forceFullRedrawAfterInterruptions(5); + + // remember the clicked item in this->item: + if (this->item) { + sp_object_unref(this->item, NULL); + this->item = NULL; + } + + this->item = sp_event_context_find_item (desktop, + Geom::Point(event->button.x, event->button.y), event->button.state & GDK_MOD1_MASK, FALSE); + sp_object_ref(this->item, NULL); + + rb_escaped = drag_escaped = 0; + + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed, event->button.time); + this->grabbed = NULL; + } + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->drawing), + GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_BUTTON_RELEASE_MASK | GDK_BUTTON_PRESS_MASK | + GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK, + NULL, event->button.time); + + this->grabbed = SP_CANVAS_ITEM(desktop->drawing); + + desktop->canvas->forceFullRedrawAfterInterruptions(5); + + ret = TRUE; + } + } else if (event->button.button == 3) { + // right click; do not eat it so that right-click menu can appear, but cancel dragging & rubberband + this->sp_select_context_abort(); + } + break; + + case GDK_ENTER_NOTIFY: { + if (!desktop->isWaitingCursor() && !this->dragging) { + GdkWindow* window = gtk_widget_get_window (GTK_WIDGET (sp_desktop_canvas(desktop))); + + gdk_window_set_cursor(window, CursorSelectMouseover); + } + break; + } + case GDK_LEAVE_NOTIFY: + if (!desktop->isWaitingCursor() && !this->dragging) { + GdkWindow* window = gtk_widget_get_window (GTK_WIDGET (sp_desktop_canvas(desktop))); + + gdk_window_set_cursor(window, this->cursor); + } + break; + + case GDK_KEY_PRESS: + if (get_group0_keyval (&event->key) == GDK_KEY_space) { + if (this->dragging && this->grabbed) { + /* stamping mode: show content mode moving */ + _seltrans->stamp(); + ret = TRUE; + } + } else if (get_group0_keyval (&event->key) == GDK_KEY_Tab) { + if (this->dragging && this->grabbed) { + _seltrans->getNextClosestPoint(false); + ret = TRUE; + } + } else if (get_group0_keyval (&event->key) == GDK_KEY_ISO_Left_Tab) { + if (this->dragging && this->grabbed) { + _seltrans->getNextClosestPoint(true); + ret = TRUE; + } + } + break; + + default: + break; + } + + if (!ret) { + ret = ToolBase::item_handler(item, event); + } + + return ret; +} + +void SelectTool::sp_select_context_cycle_through_items(Inkscape::Selection *selection, GdkEventScroll *scroll_event, bool shift_pressed) { + if (!this->cycling_cur_item) { + return; + } + + Inkscape::DrawingItem *arenaitem; + SPItem *item = SP_ITEM(this->cycling_cur_item->data); + + // Deactivate current item + if (!g_list_find(this->cycling_items_selected_before, item) && selection->includes(item)) { + selection->remove(item); + } + + arenaitem = item->get_arenaitem(desktop->dkey); + arenaitem->setOpacity(0.3); + + // Find next item and activate it + GList *next; + if (scroll_event->direction == GDK_SCROLL_UP) { + next = this->cycling_cur_item->next; + if (next == NULL && this->cycling_wrap) + next = this->cycling_items; + } else { + next = this->cycling_cur_item->prev; + if (next == NULL && this->cycling_wrap) + next = g_list_last(this->cycling_items); + } + + if (next) { + this->cycling_cur_item = next; + item = SP_ITEM(this->cycling_cur_item->data); + } + + arenaitem = item->get_arenaitem(desktop->dkey); + arenaitem->setOpacity(1.0); + + if (shift_pressed) { + selection->add(item); + } else { + selection->set(item); + } +} + +void SelectTool::sp_select_context_reset_opacities() { + for (GList *l = this->cycling_items; l != NULL; l = g_list_next(l)) { + Inkscape::DrawingItem *arenaitem = SP_ITEM(l->data)->get_arenaitem(this->desktop->dkey); + arenaitem->setOpacity(SP_SCALE24_TO_FLOAT(SP_ITEM(l->data)->style->opacity.value)); + } + + g_list_free(this->cycling_items); + g_list_free(this->cycling_items_selected_before); + g_list_free(this->cycling_items_cmp); + + this->cycling_items = NULL; + this->cycling_items_selected_before = NULL; + this->cycling_cur_item = NULL; + this->cycling_items_cmp = NULL; +} + +bool SelectTool::root_handler(GdkEvent* event) { + SPItem *item = NULL; + SPItem *item_at_point = NULL, *group_at_point = NULL, *item_in_group = NULL; + gint ret = FALSE; + + Inkscape::Selection *selection = sp_desktop_selection(desktop); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + // make sure we still have valid objects to move around + if (this->item && this->item->document == NULL) { + this->sp_select_context_abort(); + } + + switch (event->type) { + case GDK_2BUTTON_PRESS: + if (event->button.button == 1) { + if (!selection->isEmpty()) { + SPItem *clicked_item = static_cast<SPItem *>(selection->itemList()->data); + + if (SP_IS_GROUP(clicked_item) && !SP_IS_BOX3D(clicked_item)) { // enter group if it's not a 3D box + desktop->setCurrentLayer(reinterpret_cast<SPObject *>(clicked_item)); + sp_desktop_selection(desktop)->clear(); + this->dragging = false; + sp_event_context_discard_delayed_snap_event(this); + + desktop->canvas->endForcedFullRedraws(); + } else { // switch tool + Geom::Point const button_pt(event->button.x, event->button.y); + Geom::Point const p(desktop->w2d(button_pt)); + tools_switch_by_item (desktop, clicked_item, p); + } + } else { + sp_select_context_up_one_layer(desktop); + } + + ret = TRUE; + } + break; + + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + // save drag origin + xp = (gint) event->button.x; + yp = (gint) event->button.y; + within_tolerance = true; + + Geom::Point const button_pt(event->button.x, event->button.y); + Geom::Point const p(desktop->w2d(button_pt)); + + if (event->button.state & GDK_MOD1_MASK) { + Inkscape::Rubberband::get(desktop)->setMode(RUBBERBAND_MODE_TOUCHPATH); + } + + Inkscape::Rubberband::get(desktop)->start(desktop, p); + + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed, event->button.time); + this->grabbed = NULL; + } + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK, + NULL, event->button.time); + + this->grabbed = SP_CANVAS_ITEM(desktop->acetate); + + // remember what modifiers were on before button press + this->button_press_shift = (event->button.state & GDK_SHIFT_MASK) ? true : false; + this->button_press_ctrl = (event->button.state & GDK_CONTROL_MASK) ? true : false; + this->button_press_alt = (event->button.state & GDK_MOD1_MASK) ? true : false; + + this->moved = FALSE; + + rb_escaped = drag_escaped = 0; + + ret = TRUE; + } else if (event->button.button == 3) { + // right click; do not eat it so that right-click menu can appear, but cancel dragging & rubberband + this->sp_select_context_abort(); + } + break; + + case GDK_MOTION_NOTIFY: + { + if (is_cycling) { + moved_while_cycling = true; + } + + tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + + if ((event->motion.state & GDK_BUTTON1_MASK) && !this->space_panning) { + Geom::Point const motion_pt(event->motion.x, event->motion.y); + Geom::Point const p(desktop->w2d(motion_pt)); + + if ( within_tolerance + && ( abs( (gint) event->motion.x - xp ) < tolerance ) + && ( abs( (gint) event->motion.y - yp ) < tolerance ) ) { + break; // do not drag if we're within tolerance from origin + } + // Once the user has moved farther than tolerance from the original location + // (indicating they intend to move the object, not click), then always process the + // motion notify coordinates as given (no snapping back to origin) + within_tolerance = false; + + if (this->button_press_ctrl || (this->button_press_alt && !this->button_press_shift && !selection->isEmpty())) { + // if it's not click and ctrl or alt was pressed (the latter with some selection + // but not with shift) we want to drag rather than rubberband + this->dragging = TRUE; + + GdkWindow* window = gtk_widget_get_window (GTK_WIDGET (sp_desktop_canvas(desktop))); + + gdk_window_set_cursor(window, CursorSelectDragging); + + desktop->canvas->forceFullRedrawAfterInterruptions(5); + } + + if (this->dragging) { + /* User has dragged fast, so we get events on root (lauris)*/ + // not only that; we will end up here when ctrl-dragging as well + // and also when we started within tolerance, but trespassed tolerance outside of item + Inkscape::Rubberband::get(desktop)->stop(); + this->defaultMessageContext()->clear(); + + item_at_point = desktop->getItemAtPoint(Geom::Point(event->button.x, event->button.y), FALSE); + + if (!item_at_point) { // if no item at this point, try at the click point (bug 1012200) + item_at_point = desktop->getItemAtPoint(Geom::Point(xp, yp), FALSE); + } + + if (item_at_point || this->moved || this->button_press_alt) { + // drag only if starting from an item, or if something is already grabbed, or if alt-dragging + if (!this->moved) { + item_in_group = desktop->getItemAtPoint(Geom::Point(event->button.x, event->button.y), TRUE); + group_at_point = desktop->getGroupAtPoint(Geom::Point(event->button.x, event->button.y)); + + if (SP_IS_LAYER(selection->single())) { + group_at_point = SP_GROUP(selection->single()); + } + + // group-at-point is meant to be topmost item if it's a group, + // not topmost group of all items at point + if (group_at_point != item_in_group && + !(group_at_point && item_at_point && + group_at_point->isAncestorOf(item_at_point))) { + group_at_point = NULL; + } + + // if neither a group nor an item (possibly in a group) at point are selected, set selection to the item at point + if ((!item_in_group || !selection->includes(item_in_group)) && + (!group_at_point || !selection->includes(group_at_point)) + && !this->button_press_alt) { + // select what is under cursor + if (!_seltrans->isEmpty()) { + _seltrans->resetState(); + } + + // when simply ctrl-dragging, we don't want to go into groups + if (item_at_point && !selection->includes(item_at_point)) { + selection->set(item_at_point); + } + } // otherwise, do not change selection so that dragging selected-within-group items, as well as alt-dragging, is possible + + _seltrans->grab(p, -1, -1, FALSE, TRUE); + this->moved = TRUE; + } + + if (!_seltrans->isEmpty()) { + _seltrans->moveTo(p, event->button.state); + } + + desktop->scroll_to_point(p); + gobble_motion_events(GDK_BUTTON1_MASK); + ret = TRUE; + } else { + this->dragging = FALSE; + sp_event_context_discard_delayed_snap_event(this); + desktop->canvas->endForcedFullRedraws(); + } + } else { + if (Inkscape::Rubberband::get(desktop)->is_started()) { + Inkscape::Rubberband::get(desktop)->move(p); + + if (Inkscape::Rubberband::get(desktop)->getMode() == RUBBERBAND_MODE_TOUCHPATH) { + this->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Draw over</b> objects to select them; release <b>Alt</b> to switch to rubberband selection")); + } else { + this->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag around</b> objects to select them; press <b>Alt</b> to switch to touch selection")); + } + + gobble_motion_events(GDK_BUTTON1_MASK); + } + } + } + break; + } + case GDK_BUTTON_RELEASE: + xp = yp = 0; + + if ((event->button.button == 1) && (this->grabbed) && !this->space_panning) { + if (this->dragging) { + GdkWindow* window; + + if (this->moved) { + // item has been moved + _seltrans->ungrab(); + this->moved = FALSE; +#ifdef WITH_DBUS + dbus_send_ping(desktop, this->item); +#endif + } else if (this->item && !drag_escaped) { + // item has not been moved -> simply a click, do selecting + if (!selection->isEmpty()) { + if (event->button.state & GDK_SHIFT_MASK) { + // with shift, toggle selection + _seltrans->resetState(); + selection->toggle(this->item); + } else { + SPObject* single = selection->single(); + // without shift, increase state (i.e. toggle scale/rotation handles) + if (selection->includes(this->item)) { + _seltrans->increaseState(); + } else if (SP_IS_LAYER(single) && single->isAncestorOf(this->item)) { + _seltrans->increaseState(); + } else { + _seltrans->resetState(); + selection->set(this->item); + } + } + } else { // simple or shift click, no previous selection + _seltrans->resetState(); + selection->set(this->item); + } + } + + this->dragging = FALSE; + window = gtk_widget_get_window (GTK_WIDGET (sp_desktop_canvas(desktop))); + + gdk_window_set_cursor(window, CursorSelectMouseover); + sp_event_context_discard_delayed_snap_event(this); + desktop->canvas->endForcedFullRedraws(); + + if (this->item) { + sp_object_unref( this->item, NULL); + } + + this->item = NULL; + } else { + Inkscape::Rubberband *r = Inkscape::Rubberband::get(desktop); + + if (r->is_started() && !within_tolerance) { + // this was a rubberband drag + GSList *items = NULL; + + if (r->getMode() == RUBBERBAND_MODE_RECT) { + Geom::OptRect const b = r->getRectangle(); + items = sp_desktop_document(desktop)->getItemsInBox(desktop->dkey, *b); + } else if (r->getMode() == RUBBERBAND_MODE_TOUCHPATH) { + items = sp_desktop_document(desktop)->getItemsAtPoints(desktop->dkey, r->getPoints()); + } + + _seltrans->resetState(); + r->stop(); + this->defaultMessageContext()->clear(); + + if (event->button.state & GDK_SHIFT_MASK) { + // with shift, add to selection + selection->addList (items); + } else { + // without shift, simply select anew + selection->setList (items); + } + + g_slist_free (items); + } else { // it was just a click, or a too small rubberband + r->stop(); + + if (this->button_press_shift && !rb_escaped && !drag_escaped) { + // this was a shift+click or alt+shift+click, select what was clicked upon + this->button_press_shift = false; + + if (this->button_press_ctrl) { + // go into groups, honoring Alt + item = sp_event_context_find_item (desktop, + Geom::Point(event->button.x, event->button.y), event->button.state & GDK_MOD1_MASK, TRUE); + this->button_press_ctrl = FALSE; + } else { + // don't go into groups, honoring Alt + item = sp_event_context_find_item (desktop, + Geom::Point(event->button.x, event->button.y), event->button.state & GDK_MOD1_MASK, FALSE); + } + + if (item) { + selection->toggle(item); + item = NULL; + } + + } else if ((this->button_press_ctrl || this->button_press_alt) && !rb_escaped && !drag_escaped) { // ctrl+click, alt+click + item = sp_event_context_find_item (desktop, + Geom::Point(event->button.x, event->button.y), this->button_press_alt, this->button_press_ctrl); + + this->button_press_ctrl = FALSE; + this->button_press_alt = FALSE; + + if (item) { + if (selection->includes(item)) { + _seltrans->increaseState(); + } else { + _seltrans->resetState(); + selection->set(item); + } + + item = NULL; + } + } else { // click without shift, simply deselect, unless with Alt or something was cancelled + if (!selection->isEmpty()) { + if (!(rb_escaped) && !(drag_escaped) && !(event->button.state & GDK_MOD1_MASK)) { + selection->clear(); + } + + rb_escaped = 0; + ret = TRUE; + } + } + } + + ret = TRUE; + } + + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed, event->button.time); + this->grabbed = NULL; + } + + desktop->updateNow(); + } + + if (event->button.button == 1) { + Inkscape::Rubberband::get(desktop)->stop(); // might have been started in another tool! + } + + this->button_press_shift = false; + this->button_press_ctrl = false; + this->button_press_alt = false; + break; + + case GDK_SCROLL: { + GdkEventScroll *scroll_event = (GdkEventScroll*) event; + + if (scroll_event->state & GDK_MOD1_MASK) { // alt modified pressed + if (moved_while_cycling) { + moved_while_cycling = false; + this->sp_select_context_reset_opacities(); + } + + is_cycling = true; + + bool shift_pressed = scroll_event->state & GDK_SHIFT_MASK; + + /* Rebuild list of items underneath the mouse pointer */ + Geom::Point p = desktop->d2w(desktop->point()); + SPItem *item = desktop->getItemAtPoint(p, true, NULL); + + // Save pointer to current cycle-item so that we can find it again later, in the freshly built list + SPItem *tmp_cur_item = this->cycling_cur_item ? SP_ITEM(this->cycling_cur_item->data) : NULL; + g_list_free(this->cycling_items); + this->cycling_items = NULL; + this->cycling_cur_item = NULL; + + while(item != NULL) { + this->cycling_items = g_list_append(this->cycling_items, item); + item = desktop->getItemAtPoint(p, true, item); + } + + /* Compare current item list with item list during previous scroll ... */ + GList *l1, *l2; + bool item_lists_differ = false; + + // Note that we can do an 'or' comparison in the loop because it is safe to call g_list_next with a NULL pointer. + for (l1 = this->cycling_items, l2 = this->cycling_items_cmp; l1 != NULL || l2 != NULL; l1 = g_list_next(l1), l2 = g_list_next(l2)) { + if ((l1 !=NULL && l2 == NULL) || (l1 == NULL && l2 != NULL) || (l1->data != l2->data)) { + item_lists_differ = true; + break; + } + } + + /* If list of items under mouse pointer hasn't changed ... */ + if (!item_lists_differ) { + // ... find current item in the freshly built list and continue cycling ... + // TODO: This wouldn't be necessary if cycling_cur_item pointed to an element of cycling_items_cmp instead + this->cycling_cur_item = g_list_find(this->cycling_items, tmp_cur_item); + g_assert(this->cycling_cur_item != NULL || this->cycling_items == NULL); + } else { + // ... otherwise reset opacities for outdated items ... + Inkscape::DrawingItem *arenaitem; + + for(GList *l = this->cycling_items_cmp; l != NULL; l = l->next) { + arenaitem = SP_ITEM(l->data)->get_arenaitem(desktop->dkey); + arenaitem->setOpacity(1.0); + //if (!shift_pressed && !g_list_find(this->cycling_items_selected_before, SP_ITEM(l->data)) && selection->includes(SP_ITEM(l->data))) + if (!g_list_find(this->cycling_items_selected_before, SP_ITEM(l->data)) && selection->includes(SP_ITEM(l->data))) { + selection->remove(SP_ITEM(l->data)); + } + } + + // ... clear the lists ... + g_list_free(this->cycling_items_cmp); + g_list_free(this->cycling_items_selected_before); + + this->cycling_items_cmp = NULL; + this->cycling_items_selected_before = NULL; + this->cycling_cur_item = NULL; + + // ... and rebuild them with the new items. + this->cycling_items_cmp = g_list_copy(this->cycling_items); + SPItem *item; + + for(GList *l = this->cycling_items; l != NULL; l = l->next) { + item = SP_ITEM(l->data); + arenaitem = item->get_arenaitem(desktop->dkey); + arenaitem->setOpacity(0.3); + + if (selection->includes(item)) { + // already selected items are stored separately, too + this->cycling_items_selected_before = g_list_append(this->cycling_items_selected_before, item); + } + } + + // set the current item to the bottommost one so that the cycling step below re-starts at the top + this->cycling_cur_item = g_list_last(this->cycling_items); + } + + this->cycling_wrap = prefs->getBool("/options/selection/cycleWrap", true); + + // Cycle through the items underneath the mouse pointer, one-by-one + this->sp_select_context_cycle_through_items(selection, scroll_event, shift_pressed); + + ret = TRUE; + + GtkWindow *w =GTK_WINDOW(gtk_widget_get_toplevel( GTK_WIDGET(desktop->canvas) )); + if (w) + { + gtk_window_present(w); + gtk_widget_grab_focus (GTK_WIDGET(desktop->canvas)); + } + } + break; + } + + case GDK_KEY_PRESS: // keybindings for select context + { + { + guint keyval = get_group0_keyval(&event->key); + + bool alt = ( MOD__ALT(event) + || (keyval == GDK_KEY_Alt_L) + || (keyval == GDK_KEY_Alt_R) + || (keyval == GDK_KEY_Meta_L) + || (keyval == GDK_KEY_Meta_R)); + + if (!key_is_a_modifier (keyval)) { + this->defaultMessageContext()->clear(); + } else if (this->grabbed || _seltrans->isGrabbed()) { + if (Inkscape::Rubberband::get(desktop)->is_started()) { + // if Alt then change cursor to moving cursor: + if (alt) { + Inkscape::Rubberband::get(desktop)->setMode(RUBBERBAND_MODE_TOUCHPATH); + } + } else { + // do not change the statusbar text when mousekey is down to move or transform the object, + // because the statusbar text is already updated somewhere else. + break; + } + } else { + sp_event_show_modifier_tip (this->defaultMessageContext(), event, + _("<b>Ctrl</b>: click to select in groups; drag to move hor/vert"), + _("<b>Shift</b>: click to toggle select; drag for rubberband selection"), + _("<b>Alt</b>: click to select under; scroll mouse-wheel to cycle-select; drag to move selected or select by touch")); + + // if Alt and nonempty selection, show moving cursor ("move selected"): + if (alt && !selection->isEmpty() && !desktop->isWaitingCursor()) { + GdkWindow* window = gtk_widget_get_window (GTK_WIDGET (sp_desktop_canvas(desktop))); + + gdk_window_set_cursor(window, CursorSelectDragging); + } + //*/ + break; + } + } + + gdouble const nudge = prefs->getDoubleLimited("/options/nudgedistance/value", 2, 0, 1000, "px"); // in px + gdouble const offset = prefs->getDoubleLimited("/options/defaultscale/value", 2, 0, 1000, "px"); + int const snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12); + + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Left: // move selection left + case GDK_KEY_KP_Left: + if (!MOD__CTRL(event)) { // not ctrl + gint mul = 1 + gobble_key_events( get_group0_keyval(&event->key), 0); // with any mask + + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) { + sp_selection_move_screen(sp_desktop_selection(desktop), mul*-10, 0); // shift + } else { + sp_selection_move_screen(sp_desktop_selection(desktop), mul*-1, 0); // no shift + } + } else { // no alt + if (MOD__SHIFT(event)) { + sp_selection_move(sp_desktop_selection(desktop), mul*-10*nudge, 0); // shift + } else { + sp_selection_move(sp_desktop_selection(desktop), mul*-nudge, 0); // no shift + } + } + + ret = TRUE; + } + break; + + case GDK_KEY_Up: // move selection up + case GDK_KEY_KP_Up: + if (!MOD__CTRL(event)) { // not ctrl + gint mul = 1 + gobble_key_events(get_group0_keyval(&event->key), 0); // with any mask + + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) { + sp_selection_move_screen(sp_desktop_selection(desktop), 0, mul*10); // shift + } else { + sp_selection_move_screen(sp_desktop_selection(desktop), 0, mul*1); // no shift + } + } else { // no alt + if (MOD__SHIFT(event)) { + sp_selection_move(sp_desktop_selection(desktop), 0, mul*10*nudge); // shift + } else { + sp_selection_move(sp_desktop_selection(desktop), 0, mul*nudge); // no shift + } + } + + ret = TRUE; + } + break; + + case GDK_KEY_Right: // move selection right + case GDK_KEY_KP_Right: + if (!MOD__CTRL(event)) { // not ctrl + gint mul = 1 + gobble_key_events(get_group0_keyval(&event->key), 0); // with any mask + + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) { + sp_selection_move_screen(sp_desktop_selection(desktop), mul*10, 0); // shift + } else { + sp_selection_move_screen(sp_desktop_selection(desktop), mul*1, 0); // no shift + } + } else { // no alt + if (MOD__SHIFT(event)) { + sp_selection_move(sp_desktop_selection(desktop), mul*10*nudge, 0); // shift + } else { + sp_selection_move(sp_desktop_selection(desktop), mul*nudge, 0); // no shift + } + } + + ret = TRUE; + } + break; + + case GDK_KEY_Down: // move selection down + case GDK_KEY_KP_Down: + if (!MOD__CTRL(event)) { // not ctrl + gint mul = 1 + gobble_key_events(get_group0_keyval(&event->key), 0); // with any mask + + if (MOD__ALT(event)) { // alt + if (MOD__SHIFT(event)) { + sp_selection_move_screen(sp_desktop_selection(desktop), 0, mul*-10); // shift + } else { + sp_selection_move_screen(sp_desktop_selection(desktop), 0, mul*-1); // no shift + } + } else { // no alt + if (MOD__SHIFT(event)) { + sp_selection_move(sp_desktop_selection(desktop), 0, mul*-10*nudge); // shift + } else { + sp_selection_move(sp_desktop_selection(desktop), 0, mul*-nudge); // no shift + } + } + + ret = TRUE; + } + break; + + case GDK_KEY_Escape: + if (!this->sp_select_context_abort()) { + selection->clear(); + } + + ret = TRUE; + break; + + case GDK_KEY_a: + case GDK_KEY_A: + if (MOD__CTRL_ONLY(event)) { + sp_edit_select_all(desktop); + ret = TRUE; + } + break; + + case GDK_KEY_space: + /* stamping mode: show outline mode moving */ + /* FIXME: Is next condition ok? (lauris) */ + if (this->dragging && this->grabbed) { + _seltrans->stamp(); + ret = TRUE; + } + break; + + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo ("altx"); + ret = TRUE; + } + break; + + case GDK_KEY_bracketleft: + if (MOD__ALT(event)) { + gint mul = 1 + gobble_key_events(get_group0_keyval(&event->key), 0); // with any mask + sp_selection_rotate_screen(selection, mul*1); + } else if (MOD__CTRL(event)) { + sp_selection_rotate(selection, 90); + } else if (snaps) { + sp_selection_rotate(selection, 180.0/snaps); + } + + ret = TRUE; + break; + + case GDK_KEY_bracketright: + if (MOD__ALT(event)) { + gint mul = 1 + gobble_key_events(get_group0_keyval(&event->key), 0); // with any mask + sp_selection_rotate_screen(selection, -1*mul); + } else if (MOD__CTRL(event)) { + sp_selection_rotate(selection, -90); + } else if (snaps) { + sp_selection_rotate(selection, -180.0/snaps); + } + + ret = TRUE; + break; + + case GDK_KEY_less: + case GDK_KEY_comma: + if (MOD__ALT(event)) { + gint mul = 1 + gobble_key_events(get_group0_keyval(&event->key), 0); // with any mask + sp_selection_scale_screen(selection, -2*mul); + } else if (MOD__CTRL(event)) { + sp_selection_scale_times(selection, 0.5); + } else { + gint mul = 1 + gobble_key_events(get_group0_keyval(&event->key), 0); // with any mask + sp_selection_scale(selection, -offset*mul); + } + + ret = TRUE; + break; + + case GDK_KEY_greater: + case GDK_KEY_period: + if (MOD__ALT(event)) { + gint mul = 1 + gobble_key_events(get_group0_keyval(&event->key), 0); // with any mask + sp_selection_scale_screen(selection, 2*mul); + } else if (MOD__CTRL(event)) { + sp_selection_scale_times(selection, 2); + } else { + gint mul = 1 + gobble_key_events(get_group0_keyval(&event->key), 0); // with any mask + sp_selection_scale(selection, offset*mul); + } + + ret = TRUE; + break; + + case GDK_KEY_Return: + if (MOD__CTRL_ONLY(event)) { + if (selection->singleItem()) { + SPItem *clicked_item = selection->singleItem(); + + if ( SP_IS_GROUP(clicked_item) || SP_IS_BOX3D(clicked_item)) { // enter group or a 3D box + desktop->setCurrentLayer(reinterpret_cast<SPObject *>(clicked_item)); + sp_desktop_selection(desktop)->clear(); + } else { + this->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Selected object is not a group. Cannot enter.")); + } + } + + ret = TRUE; + } + break; + + case GDK_KEY_BackSpace: + if (MOD__CTRL_ONLY(event)) { + sp_select_context_up_one_layer(desktop); + ret = TRUE; + } + break; + + case GDK_KEY_s: + case GDK_KEY_S: + if (MOD__SHIFT_ONLY(event)) { + if (!selection->isEmpty()) { + _seltrans->increaseState(); + } + + ret = TRUE; + } + break; + + case GDK_KEY_g: + case GDK_KEY_G: + if (MOD__SHIFT_ONLY(event)) { + sp_selection_to_guides(desktop); + ret = true; + } + break; + + default: + break; + } + break; + } + case GDK_KEY_RELEASE: { + guint keyval = get_group0_keyval(&event->key); + if (key_is_a_modifier (keyval)) { + this->defaultMessageContext()->clear(); + } + + bool alt = ( MOD__ALT(event) + || (keyval == GDK_KEY_Alt_L) + || (keyval == GDK_KEY_Alt_R) + || (keyval == GDK_KEY_Meta_L) + || (keyval == GDK_KEY_Meta_R)); + + if (Inkscape::Rubberband::get(desktop)->is_started()) { + // if Alt then change cursor to moving cursor: + if (alt) { + Inkscape::Rubberband::get(desktop)->setMode(RUBBERBAND_MODE_RECT); + } + } else { + if (alt) { + // quit cycle-selection and reset opacities + if (is_cycling) { + this->sp_select_context_reset_opacities(); + is_cycling = false; + } + } + } + + // set cursor to default. + if (!desktop->isWaitingCursor()) { + // Do we need to reset the cursor here on key release ? + //GdkWindow* window = gtk_widget_get_window (GTK_WIDGET (sp_desktop_canvas(desktop))); + //gdk_window_set_cursor(window, event_context->cursor); + } + break; + } + default: + break; + } + + if (!ret) { + ret = ToolBase::root_handler(event); + } + + return ret; +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/tools/select-tool.h b/src/ui/tools/select-tool.h new file mode 100644 index 000000000..edc4069a2 --- /dev/null +++ b/src/ui/tools/select-tool.h @@ -0,0 +1,74 @@ +#ifndef __SP_SELECT_CONTEXT_H__ +#define __SP_SELECT_CONTEXT_H__ + +/* + * Select tool + * + * Authors: + * Lauris Kaplinski <lauris@kaplinski.com> + * + * Copyright (C) 1999-2002 authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "ui/tools/tool-base.h" +#include <gtk/gtk.h> + +#define SP_SELECT_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::SelectTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_SELECT_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::SelectTool*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +struct SPCanvasItem; + +namespace Inkscape { + class MessageContext; + class SelTrans; + class SelectionDescriber; +} + +namespace Inkscape { +namespace UI { +namespace Tools { + +class SelectTool : public ToolBase { +public: + SelectTool(); + virtual ~SelectTool(); + + bool dragging; + bool moved; + bool button_press_shift; + bool button_press_ctrl; + bool button_press_alt; + + GList *cycling_items; + GList *cycling_items_cmp; + GList *cycling_items_selected_before; + GList *cycling_cur_item; + bool cycling_wrap; + + SPItem *item; + SPCanvasItem *grabbed; + Inkscape::SelTrans *_seltrans; + Inkscape::SelectionDescriber *_describer; + + static const std::string prefsPath; + + virtual void setup(); + virtual void set(const Inkscape::Preferences::Entry& val); + virtual bool root_handler(GdkEvent* event); + virtual bool item_handler(SPItem* item, GdkEvent* event); + + virtual const std::string& getPrefsPath(); + +private: + bool sp_select_context_abort(); + void sp_select_context_cycle_through_items(Inkscape::Selection *selection, GdkEventScroll *scroll_event, bool shift_pressed); + void sp_select_context_reset_opacities(); +}; + +} +} +} + +#endif diff --git a/src/ui/tools/spiral-tool.cpp b/src/ui/tools/spiral-tool.cpp new file mode 100644 index 000000000..5ae229df8 --- /dev/null +++ b/src/ui/tools/spiral-tool.cpp @@ -0,0 +1,459 @@ +/* + * Spiral drawing context + * + * Authors: + * Mitsuru Oka + * Lauris Kaplinski <lauris@kaplinski.com> + * bulia byak <buliabyak@users.sf.net> + * Jon A. Cruz <jon@joncruz.org> + * Abhishek Sharma + * + * Copyright (C) 1999-2001 Lauris Kaplinski + * Copyright (C) 2001-2002 Mitsuru Oka + * + * Released under GNU GPL + */ + +#include "config.h" + +#include <gdk/gdkkeysyms.h> +#include <cstring> +#include <string> + +#include "macros.h" +#include "display/sp-canvas.h" +#include "sp-spiral.h" +#include "document.h" +#include "document-undo.h" +#include "sp-namedview.h" +#include "selection.h" +#include "desktop-handles.h" +#include "snap.h" +#include "desktop.h" +#include "desktop-style.h" +#include "message-context.h" +#include "pixmaps/cursor-spiral.xpm" +#include "ui/tools/spiral-tool.h" +#include <glibmm/i18n.h> +#include "xml/repr.h" +#include "xml/node-event-vector.h" +#include "preferences.h" +#include "context-fns.h" +#include "shape-editor.h" +#include "verbs.h" +#include "display/sp-canvas-item.h" + +using Inkscape::DocumentUndo; + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +namespace { + ToolBase* createSpiralContext() { + return new SpiralTool(); + } + + bool spiralContextRegistered = ToolFactory::instance().registerObject("/tools/shapes/spiral", createSpiralContext); +} + +const std::string& SpiralTool::getPrefsPath() { + return SpiralTool::prefsPath; +} + +const std::string SpiralTool::prefsPath = "/tools/shapes/spiral"; + +SpiralTool::SpiralTool() + : ToolBase(cursor_spiral_xpm, 4, 4) + , spiral(NULL) + , revo(3) + , exp(1) + , t0(0) +{ +} + +void SpiralTool::finish() { + SPDesktop *desktop = this->desktop; + + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), GDK_CURRENT_TIME); + + this->finishItem(); + this->sel_changed_connection.disconnect(); + + ToolBase::finish(); +} + +SpiralTool::~SpiralTool() { + this->enableGrDrag(false); + + this->sel_changed_connection.disconnect(); + + delete this->shape_editor; + this->shape_editor = NULL; + + /* fixme: This is necessary because we do not grab */ + if (this->spiral) { + this->finishItem(); + } +} + +/** + * Callback that processes the "changed" signal on the selection; + * destroys old and creates new knotholder. + */ +void SpiralTool::selection_changed(Inkscape::Selection *selection) { + this->shape_editor->unset_item(SH_KNOTHOLDER); + this->shape_editor->set_item(selection->singleItem(), SH_KNOTHOLDER); +} + +void SpiralTool::setup() { + ToolBase::setup(); + + sp_event_context_read(this, "expansion"); + sp_event_context_read(this, "revolution"); + sp_event_context_read(this, "t0"); + + this->shape_editor = new ShapeEditor(this->desktop); + + SPItem *item = sp_desktop_selection(this->desktop)->singleItem(); + if (item) { + this->shape_editor->set_item(item, SH_KNOTHOLDER); + } + + Inkscape::Selection *selection = sp_desktop_selection(this->desktop); + this->sel_changed_connection.disconnect(); + + this->sel_changed_connection = selection->connectChanged(sigc::mem_fun(this, &SpiralTool::selection_changed)); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + if (prefs->getBool("/tools/shapes/selcue")) { + this->enableSelectionCue(); + } + + if (prefs->getBool("/tools/shapes/gradientdrag")) { + this->enableGrDrag(); + } +} + +void SpiralTool::set(const Inkscape::Preferences::Entry& val) { + Glib::ustring name = val.getEntryName(); + + if (name == "expansion") { + this->exp = CLAMP(val.getDouble(), 0.0, 1000.0); + } else if (name == "revolution") { + this->revo = CLAMP(val.getDouble(3.0), 0.05, 40.0); + } else if (name == "t0") { + this->t0 = CLAMP(val.getDouble(), 0.0, 0.999); + } +} + +bool SpiralTool::root_handler(GdkEvent* event) { + static gboolean dragging; + + SPDesktop *desktop = this->desktop; + Inkscape::Selection *selection = sp_desktop_selection (desktop); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + this->tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + + gint ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + dragging = TRUE; + + this->center = Inkscape::setup_for_drag_start(desktop, this, event); + + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + m.freeSnapReturnByRef(this->center, Inkscape::SNAPSOURCE_NODE_HANDLE); + m.unSetup(); + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + ( GDK_KEY_PRESS_MASK | + GDK_BUTTON_RELEASE_MASK | + GDK_POINTER_MOTION_MASK | + GDK_POINTER_MOTION_HINT_MASK | + GDK_BUTTON_PRESS_MASK ), + NULL, event->button.time); + ret = TRUE; + } + break; + + case GDK_MOTION_NOTIFY: + if (dragging && (event->motion.state & GDK_BUTTON1_MASK) && !this->space_panning) { + if ( this->within_tolerance + && ( abs( (gint) event->motion.x - this->xp ) < this->tolerance ) + && ( abs( (gint) event->motion.y - this->yp ) < this->tolerance ) ) { + break; // do not drag if we're within tolerance from origin + } + // Once the user has moved farther than tolerance from the original location + // (indicating they intend to draw, not click), then always process the + // motion notify coordinates as given (no snapping back to origin) + this->within_tolerance = false; + + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point motion_dt(this->desktop->w2d(motion_w)); + + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop, true, this->spiral); + m.freeSnapReturnByRef(motion_dt, Inkscape::SNAPSOURCE_NODE_HANDLE); + m.unSetup(); + + this->drag(motion_dt, event->motion.state); + + gobble_motion_events(GDK_BUTTON1_MASK); + + ret = TRUE; + } else if (!this->sp_event_context_knot_mouseover()) { + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); + m.preSnap(Inkscape::SnapCandidatePoint(motion_dt, Inkscape::SNAPSOURCE_NODE_HANDLE)); + m.unSetup(); + } + break; + + case GDK_BUTTON_RELEASE: + this->xp = this->yp = 0; + if (event->button.button == 1 && !this->space_panning) { + dragging = FALSE; + sp_event_context_discard_delayed_snap_event(this); + + if (!this->within_tolerance) { + // we've been dragging, finish the spiral + this->finishItem(); + } else if (this->item_to_select) { + // no dragging, select clicked item if any + if (event->button.state & GDK_SHIFT_MASK) { + selection->toggle(this->item_to_select); + } else { + selection->set(this->item_to_select); + } + } else { + // click in an empty space + selection->clear(); + } + + this->item_to_select = NULL; + ret = TRUE; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time); + } + break; + + case GDK_KEY_PRESS: + switch (get_group0_keyval(&event->key)) { + case GDK_KEY_Alt_R: + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + case GDK_KEY_Meta_L: // Meta is when you press Shift+Alt (at least on my machine) + case GDK_KEY_Meta_R: + sp_event_show_modifier_tip(this->defaultMessageContext(), event, + _("<b>Ctrl</b>: snap angle"), + NULL, + _("<b>Alt</b>: lock spiral radius")); + break; + case GDK_KEY_Up: + case GDK_KEY_Down: + case GDK_KEY_KP_Up: + case GDK_KEY_KP_Down: + // prevent the zoom field from activation + if (!MOD__CTRL_ONLY(event)) + ret = TRUE; + break; + + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo ("altx-spiral"); + ret = TRUE; + } + break; + + case GDK_KEY_Escape: + if (dragging) { + dragging = false; + sp_event_context_discard_delayed_snap_event(this); + // if drawing, cancel, otherwise pass it up for deselecting + this->cancel(); + ret = TRUE; + } + break; + + case GDK_KEY_space: + if (dragging) { + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), + event->button.time); + dragging = false; + sp_event_context_discard_delayed_snap_event(this); + + if (!this->within_tolerance) { + // we've been dragging, finish the spiral + this->finish(); + } + // do not return true, so that space would work switching to selector + } + break; + + case GDK_KEY_Delete: + case GDK_KEY_KP_Delete: + case GDK_KEY_BackSpace: + ret = this->deleteSelectedDrag(MOD__CTRL_ONLY(event)); + break; + + default: + break; + } + break; + + case GDK_KEY_RELEASE: + switch (get_group0_keyval(&event->key)) { + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + case GDK_KEY_Meta_L: // Meta is when you press Shift+Alt + case GDK_KEY_Meta_R: + this->defaultMessageContext()->clear(); + break; + + default: + break; + } + break; + + default: + break; + } + + if (!ret) { + ret = ToolBase::root_handler(event); + } + + return ret; +} + +void SpiralTool::drag(Geom::Point const &p, guint state) { + SPDesktop *desktop = SP_EVENT_CONTEXT(this)->desktop; + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int const snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12); + + if (!this->spiral) { + if (Inkscape::have_viable_layer(desktop, this->message_context) == false) { + return; + } + + // Create object + Inkscape::XML::Document *xml_doc = this->desktop->doc()->getReprDoc(); + Inkscape::XML::Node *repr = xml_doc->createElement("svg:path"); + repr->setAttribute("sodipodi:type", "spiral"); + + // Set style + sp_desktop_apply_style_tool(desktop, repr, "/tools/shapes/spiral", false); + + this->spiral = SP_SPIRAL(desktop->currentLayer()->appendChildRepr(repr)); + Inkscape::GC::release(repr); + this->spiral->transform = SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); + this->spiral->updateRepr(); + + desktop->canvas->forceFullRedrawAfterInterruptions(5); + } + + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop, true, this->spiral); + Geom::Point pt2g = p; + m.freeSnapReturnByRef(pt2g, Inkscape::SNAPSOURCE_NODE_HANDLE); + m.unSetup(); + Geom::Point const p0 = desktop->dt2doc(this->center); + Geom::Point const p1 = desktop->dt2doc(pt2g); + + Geom::Point const delta = p1 - p0; + gdouble const rad = Geom::L2(delta); + + gdouble arg = Geom::atan2(delta) - 2.0*M_PI*this->spiral->revo; + + if (state & GDK_CONTROL_MASK) { + arg = sp_round(arg, M_PI/snaps); + } + + /* Fixme: these parameters should be got from dialog box */ + this->spiral->setPosition(p0[Geom::X], p0[Geom::Y], + /*expansion*/ this->exp, + /*revolution*/ this->revo, + rad, arg, + /*t0*/ this->t0); + + /* status text */ + Inkscape::Util::Quantity q = Inkscape::Util::Quantity(rad, "px"); + GString *rads = g_string_new(q.string(desktop->namedview->doc_units).c_str()); + this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, + _("<b>Spiral</b>: radius %s, angle %5g°; with <b>Ctrl</b> to snap angle"), + rads->str, sp_round((arg + 2.0*M_PI*this->spiral->revo)*180/M_PI, 0.0001)); + g_string_free(rads, FALSE); +} + +void SpiralTool::finishItem() { + this->message_context->clear(); + + if (this->spiral != NULL) { + if (this->spiral->rad == 0) { + this->cancel(); // Don't allow the creating of zero sized spiral, for example when the start and and point snap to the snap grid point + return; + } + + spiral->set_shape(); + spiral->updateRepr(SP_OBJECT_WRITE_EXT); + spiral->doWriteTransform(spiral->getRepr(), spiral->transform, NULL, true); + + this->desktop->canvas->endForcedFullRedraws(); + + sp_desktop_selection(this->desktop)->set(this->spiral); + DocumentUndo::done(sp_desktop_document(this->desktop), SP_VERB_CONTEXT_SPIRAL, _("Create spiral")); + + this->spiral = NULL; + } +} + +void SpiralTool::cancel() { + sp_desktop_selection(this->desktop)->clear(); + sp_canvas_item_ungrab(SP_CANVAS_ITEM(this->desktop->acetate), 0); + + if (this->spiral != NULL) { + this->spiral->deleteObject(); + this->spiral = NULL; + } + + this->within_tolerance = false; + this->xp = 0; + this->yp = 0; + this->item_to_select = NULL; + + this->desktop->canvas->endForcedFullRedraws(); + + DocumentUndo::cancel(sp_desktop_document(this->desktop)); +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/spiral-tool.h b/src/ui/tools/spiral-tool.h new file mode 100644 index 000000000..416aeb7e4 --- /dev/null +++ b/src/ui/tools/spiral-tool.h @@ -0,0 +1,66 @@ +#ifndef __SP_SPIRAL_CONTEXT_H__ +#define __SP_SPIRAL_CONTEXT_H__ + +/** \file + * Spiral drawing context + */ +/* + * Authors: + * Mitsuru Oka + * Lauris Kaplinski <lauris@kaplinski.com> + * + * Copyright (C) 1999-2001 Lauris Kaplinski + * Copyright (C) 2001-2002 Mitsuru Oka + * + * Released under GNU GPL + */ + +#include <gtk/gtk.h> +#include <stddef.h> +#include <sigc++/sigc++.h> +#include <2geom/point.h> +#include "ui/tools/tool-base.h" + +#include "sp-spiral.h" + +#define SP_SPIRAL_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::SpiralTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_SPIRAL_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::SpiralTool*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +namespace Inkscape { +namespace UI { +namespace Tools { + +class SpiralTool : public ToolBase { +public: + SpiralTool(); + virtual ~SpiralTool(); + + static const std::string prefsPath; + + virtual void setup(); + virtual void finish(); + virtual void set(const Inkscape::Preferences::Entry& val); + virtual bool root_handler(GdkEvent* event); + + virtual const std::string& getPrefsPath(); + +private: + SPSpiral * spiral; + Geom::Point center; + gdouble revo; + gdouble exp; + gdouble t0; + + sigc::connection sel_changed_connection; + + void drag(Geom::Point const &p, guint state); + void finishItem(); + void cancel(); + void selection_changed(Inkscape::Selection *selection); +}; + +} +} +} + +#endif diff --git a/src/ui/tools/spray-tool.cpp b/src/ui/tools/spray-tool.cpp new file mode 100644 index 000000000..08d3119a1 --- /dev/null +++ b/src/ui/tools/spray-tool.cpp @@ -0,0 +1,903 @@ +/* + * Spray Tool + * + * Authors: + * Pierre-Antoine MARC + * Pierre CACLIN + * Aurel-Aimé MARMION + * Julien LERAY + * Benoît LAVORATA + * Vincent MONTAGNE + * Pierre BARBRY-BLOT + * Steren GIANNINI (steren.giannini@gmail.com) + * Jon A. Cruz <jon@joncruz.org> + * Abhishek Sharma + * + * Copyright (C) 2009 authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "config.h" + +#include <numeric> + +#include "ui/dialog/dialog-manager.h" + +#include "svg/svg.h" + +#include <glib.h> +#include "macros.h" +#include "document.h" +#include "document-undo.h" +#include "selection.h" +#include "desktop.h" +#include "desktop-events.h" +#include "desktop-handles.h" +#include "message-context.h" +#include "pixmaps/cursor-spray.xpm" +#include <boost/optional.hpp> +#include "xml/repr.h" +#include "context-fns.h" +#include "sp-item.h" +#include "inkscape.h" + +#include "splivarot.h" +#include "sp-item-group.h" +#include "sp-shape.h" +#include "sp-path.h" +#include "path-chemistry.h" + +#include "sp-text.h" +#include "sp-flowtext.h" +#include "display/sp-canvas.h" +#include "display/canvas-bpath.h" +#include "display/canvas-arena.h" +#include "display/curve.h" +#include "livarot/Shape.h" +#include <2geom/circle.h> +#include <2geom/transforms.h> +#include "preferences.h" +#include "style.h" +#include "box3d.h" +#include "sp-item-transform.h" +#include "filter-chemistry.h" + +#include "ui/tools/spray-tool.h" +#include "helper/action.h" +#include "verbs.h" + +#include <iostream> + +#include <gtk/gtk.h> +#include <gdk/gdkkeysyms.h> +#include <glibmm/i18n.h> + +using Inkscape::DocumentUndo; +using namespace std; + +#define DDC_RED_RGBA 0xff0000ff +#define DYNA_MIN_WIDTH 1.0e-6 + +// Disabled in 0.91 because of Bug #1274831 (crash, spraying an object +// with the mode: spray object in single path) +// Please enable again when working on 1.0 +#define ENABLE_SPRAY_MODE_SINGLE_PATH + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +namespace { + ToolBase* createSprayContext() { + return new SprayTool(); + } + + bool sprayContextRegistered = ToolFactory::instance().registerObject("/tools/spray", createSprayContext); +} + +const std::string& SprayTool::getPrefsPath() { + return SprayTool::prefsPath; +} + +const std::string SprayTool::prefsPath = "/tools/spray"; + +/** + * This function returns pseudo-random numbers from a normal distribution + * @param mu : mean + * @param sigma : standard deviation ( > 0 ) + */ +inline double NormalDistribution(double mu, double sigma) +{ + // use Box Muller's algorithm + return mu + sigma * sqrt( -2.0 * log(g_random_double_range(0, 1)) ) * cos( 2.0*M_PI*g_random_double_range(0, 1) ); +} + +/* Method to rotate items */ +static void sp_spray_rotate_rel(Geom::Point c, SPDesktop */*desktop*/, SPItem *item, Geom::Rotate const &rotation) +{ + Geom::Translate const s(c); + Geom::Affine affine = s.inverse() * rotation * s; + // Rotate item. + item->set_i2d_affine(item->i2dt_affine() * affine); + // Use each item's own transform writer, consistent with sp_selection_apply_affine() + item->doWriteTransform(item->getRepr(), item->transform); + // Restore the center position (it's changed because the bbox center changed) + if (item->isCenterSet()) { + item->setCenter(c); + item->updateRepr(); + } +} + +/* Method to scale items */ +static void sp_spray_scale_rel(Geom::Point c, SPDesktop */*desktop*/, SPItem *item, Geom::Scale const &scale) +{ + Geom::Translate const s(c); + item->set_i2d_affine(item->i2dt_affine() * s.inverse() * scale * s); + item->doWriteTransform(item->getRepr(), item->transform); +} + +SprayTool::SprayTool() + : ToolBase(cursor_spray_xpm, 4, 4, false) + , pressure(TC_DEFAULT_PRESSURE) + , dragging(false) + , usepressure(0) + , usetilt(0) + , usetext(false) + , width(0.2) + , ratio(0) + , tilt(0) + , rotation_variation(0) + , force(0.2) + , population(0) + , scale_variation(1) + , scale(1) + , mean(0.2) + , standard_deviation(0.2) + , distrib(1) + , mode(0) + , is_drawing(false) + , is_dilating(false) + , has_dilated(false) + , dilate_area(NULL) +{ +} + +SprayTool::~SprayTool() { + this->enableGrDrag(false); + this->style_set_connection.disconnect(); + + if (this->dilate_area) { + sp_canvas_item_destroy(this->dilate_area); + this->dilate_area = NULL; + } +} + +static bool is_transform_modes(gint mode) +{ + return (mode == SPRAY_MODE_COPY || + mode == SPRAY_MODE_CLONE || + mode == SPRAY_MODE_SINGLE_PATH || + mode == SPRAY_OPTION); +} + +void SprayTool::update_cursor(bool /*with_shift*/) { + guint num = 0; + gchar *sel_message = NULL; + + if (!desktop->selection->isEmpty()) { + num = g_slist_length(const_cast<GSList *>(desktop->selection->itemList())); + sel_message = g_strdup_printf(ngettext("<b>%i</b> object selected","<b>%i</b> objects selected",num), num); + } else { + sel_message = g_strdup_printf("%s", _("<b>Nothing</b> selected")); + } + + switch (this->mode) { + case SPRAY_MODE_COPY: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag, click or click and scroll to spray <b>copies</b> of the initial selection."), sel_message); + break; + case SPRAY_MODE_CLONE: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag, click or click and scroll to spray <b>clones</b> of the initial selection."), sel_message); + break; + case SPRAY_MODE_SINGLE_PATH: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag, click or click and scroll to spray in a <b>single path</b> of the initial selection."), sel_message); + break; + default: + break; + } + + this->sp_event_context_update_cursor(); + g_free(sel_message); +} + +void SprayTool::setup() { + ToolBase::setup(); + + { + /* TODO: have a look at sp_dyna_draw_context_setup where the same is done.. generalize? at least make it an arcto! */ + Geom::PathVector path; + Geom::Circle(0, 0, 1).getPath(path); + + SPCurve *c = new SPCurve(path); + + this->dilate_area = sp_canvas_bpath_new(sp_desktop_controls(this->desktop), c); + c->unref(); + sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(this->dilate_area), 0x00000000,(SPWindRule)0); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->dilate_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_item_hide(this->dilate_area); + } + + this->is_drawing = false; + + sp_event_context_read(this, "distrib"); + sp_event_context_read(this, "width"); + sp_event_context_read(this, "ratio"); + sp_event_context_read(this, "tilt"); + sp_event_context_read(this, "rotation_variation"); + sp_event_context_read(this, "scale_variation"); + sp_event_context_read(this, "mode"); + sp_event_context_read(this, "population"); + sp_event_context_read(this, "force"); + sp_event_context_read(this, "mean"); + sp_event_context_read(this, "standard_deviation"); + sp_event_context_read(this, "usepressure"); + sp_event_context_read(this, "Scale"); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/tools/spray/selcue")) { + this->enableSelectionCue(); + } + if (prefs->getBool("/tools/spray/gradientdrag")) { + this->enableGrDrag(); + } +} + +void SprayTool::set(const Inkscape::Preferences::Entry& val) { + Glib::ustring path = val.getEntryName(); + + if (path == "mode") { + this->mode = val.getInt(); + this->update_cursor(false); + } else if (path == "width") { + this->width = 0.01 * CLAMP(val.getInt(10), 1, 100); + } else if (path == "usepressure") { + this->usepressure = val.getBool(); + } else if (path == "population") { + this->population = 0.01 * CLAMP(val.getInt(10), 1, 100); + } else if (path == "rotation_variation") { + this->rotation_variation = CLAMP(val.getDouble(0.0), 0, 100.0); + } else if (path == "scale_variation") { + this->scale_variation = CLAMP(val.getDouble(1.0), 0, 100.0); + } else if (path == "standard_deviation") { + this->standard_deviation = 0.01 * CLAMP(val.getInt(10), 1, 100); + } else if (path == "mean") { + this->mean = 0.01 * CLAMP(val.getInt(10), 1, 100); +// Not implemented in the toolbar and preferences yet + } else if (path == "distribution") { + this->distrib = val.getInt(1); + } else if (path == "tilt") { + this->tilt = CLAMP(val.getDouble(0.1), 0, 1000.0); + } else if (path == "ratio") { + this->ratio = CLAMP(val.getDouble(), 0.0, 0.9); + } else if (path == "force") { + this->force = CLAMP(val.getDouble(1.0), 0, 1.0); + } +} + +static void sp_spray_extinput(SprayTool *tc, GdkEvent *event) +{ + if (gdk_event_get_axis(event, GDK_AXIS_PRESSURE, &tc->pressure)) { + tc->pressure = CLAMP(tc->pressure, TC_MIN_PRESSURE, TC_MAX_PRESSURE); + } else { + tc->pressure = TC_DEFAULT_PRESSURE; + } +} + +static double get_dilate_radius(SprayTool *tc) +{ + return 250 * tc->width/SP_EVENT_CONTEXT(tc)->desktop->current_zoom(); +} + +static double get_path_force(SprayTool *tc) +{ + double force = 8 * (tc->usepressure? tc->pressure : TC_DEFAULT_PRESSURE) + /sqrt(SP_EVENT_CONTEXT(tc)->desktop->current_zoom()); + if (force > 3) { + force += 4 * (force - 3); + } + return force * tc->force; +} + +static double get_path_mean(SprayTool *tc) +{ + return tc->mean; +} + +static double get_path_standard_deviation(SprayTool *tc) +{ + return tc->standard_deviation; +} + +static double get_move_force(SprayTool *tc) +{ + double force = (tc->usepressure? tc->pressure : TC_DEFAULT_PRESSURE); + return force * tc->force; +} + +static double get_move_mean(SprayTool *tc) +{ + return tc->mean; +} + +static double get_move_standard_deviation(SprayTool *tc) +{ + return tc->standard_deviation; +} + +/** + * Method to handle the distribution of the items + * @param[out] radius : radius of the position of the sprayed object + * @param[out] angle : angle of the position of the sprayed object + * @param[in] a : mean + * @param[in] s : standard deviation + * @param[in] choice : + + */ +static void random_position(double &radius, double &angle, double &a, double &s, int /*choice*/) +{ + // angle is taken from an uniform distribution + angle = g_random_double_range(0, M_PI*2.0); + + // radius is taken from a Normal Distribution + double radius_temp =-1; + while(!((radius_temp >= 0) && (radius_temp <=1 ))) + { + radius_temp = NormalDistribution(a, s); + } + // Because we are in polar coordinates, a special treatment has to be done to the radius. + // Otherwise, positions taken from an uniform repartition on radius and angle will not seam to + // be uniformily distributed on the disk (more at the center and less at the boundary). + // We counter this effect with a 0.5 exponent. This is empiric. + radius = pow(radius_temp, 0.5); + +} + +static bool sp_spray_recursive(SPDesktop *desktop, + Inkscape::Selection *selection, + SPItem *item, + Geom::Point p, + Geom::Point /*vector*/, + gint mode, + double radius, + double /*force*/, + double population, + double &scale, + double scale_variation, + bool /*reverse*/, + double mean, + double standard_deviation, + double ratio, + double tilt, + double rotation_variation, + gint _distrib) +{ + bool did = false; + + if (SP_IS_BOX3D(item) ) { + // convert 3D boxes to ordinary groups before spraying their shapes + item = box3d_convert_to_group(SP_BOX3D(item)); + selection->add(item); + } + + double _fid = g_random_double_range(0, 1); + double angle = g_random_double_range( - rotation_variation / 100.0 * M_PI , rotation_variation / 100.0 * M_PI ); + double _scale = g_random_double_range( 1.0 - scale_variation / 100.0, 1.0 + scale_variation / 100.0 ); + double dr; double dp; + random_position( dr, dp, mean, standard_deviation, _distrib ); + dr=dr*radius; + + if (mode == SPRAY_MODE_COPY) { + Geom::OptRect a = item->documentVisualBounds(); + if (a) { + SPItem *item_copied; + if(_fid <= population) + { + // Duplicate + SPDocument *doc = item->document; + Inkscape::XML::Document* xml_doc = doc->getReprDoc(); + Inkscape::XML::Node *old_repr = item->getRepr(); + Inkscape::XML::Node *parent = old_repr->parent(); + Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc); + parent->appendChild(copy); + + SPObject *new_obj = doc->getObjectByRepr(copy); + item_copied = SP_ITEM(new_obj); // Convertion object->item + Geom::Point center=item->getCenter(); + sp_spray_scale_rel(center,desktop, item_copied, Geom::Scale(_scale,_scale)); + sp_spray_scale_rel(center,desktop, item_copied, Geom::Scale(scale,scale)); + + sp_spray_rotate_rel(center,desktop,item_copied, Geom::Rotate(angle)); + // Move the cursor p + Geom::Point move = (Geom::Point(cos(tilt)*cos(dp)*dr/(1-ratio)+sin(tilt)*sin(dp)*dr/(1+ratio), -sin(tilt)*cos(dp)*dr/(1-ratio)+cos(tilt)*sin(dp)*dr/(1+ratio)))+(p-a->midpoint()); + sp_item_move_rel(item_copied, Geom::Translate(move[Geom::X], -move[Geom::Y])); + did = true; + } + } +#ifdef ENABLE_SPRAY_MODE_SINGLE_PATH + } else if (mode == SPRAY_MODE_SINGLE_PATH) { + + SPItem *parent_item = NULL; // Initial object + SPItem *item_copied = NULL; // Projected object + SPItem *unionResult = NULL; // Previous union + + int i=1; + for (GSList *items = g_slist_copy(const_cast<GSList *>(selection->itemList())); + items != NULL; + items = items->next) { + + SPItem *item1 = SP_ITEM(items->data); + if (i == 1) { + parent_item = item1; + } + if (i == 2) { + unionResult = item1; + } + i++; + } + SPDocument *doc = parent_item->document; + Inkscape::XML::Document* xml_doc = doc->getReprDoc(); + Inkscape::XML::Node *old_repr = parent_item->getRepr(); + Inkscape::XML::Node *parent = old_repr->parent(); + + Geom::OptRect a = parent_item->documentVisualBounds(); + if (a) { + if (_fid <= population) { // Rules the population of objects sprayed + // Duplicates the parent item + Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc); + parent->appendChild(copy); + SPObject *new_obj = doc->getObjectByRepr(copy); + item_copied = SP_ITEM(new_obj); + + // Move around the cursor + Geom::Point move = (Geom::Point(cos(tilt)*cos(dp)*dr/(1-ratio)+sin(tilt)*sin(dp)*dr/(1+ratio), -sin(tilt)*cos(dp)*dr/(1-ratio)+cos(tilt)*sin(dp)*dr/(1+ratio)))+(p-a->midpoint()); + + Geom::Point center = parent_item->getCenter(); + sp_spray_scale_rel(center, desktop, item_copied, Geom::Scale(_scale, _scale)); + sp_spray_scale_rel(center, desktop, item_copied, Geom::Scale(scale, scale)); + sp_spray_rotate_rel(center, desktop, item_copied, Geom::Rotate(angle)); + sp_item_move_rel(item_copied, Geom::Translate(move[Geom::X], -move[Geom::Y])); + + // Union and duplication + selection->clear(); + selection->add(item_copied); + if (unionResult) { // No need to add the very first item (initialized with NULL). + selection->add(unionResult); + } + sp_selected_path_union_skip_undo(selection, selection->desktop()); + selection->add(parent_item); + Inkscape::GC::release(copy); + did = true; + } + } +#endif + } else if (mode == SPRAY_MODE_CLONE) { + Geom::OptRect a = item->documentVisualBounds(); + if (a) { + if(_fid <= population) { + SPItem *item_copied; + SPDocument *doc = item->document; + Inkscape::XML::Document* xml_doc = doc->getReprDoc(); + Inkscape::XML::Node *old_repr = item->getRepr(); + Inkscape::XML::Node *parent = old_repr->parent(); + + // Creation of the clone + Inkscape::XML::Node *clone = xml_doc->createElement("svg:use"); + // Ad the clone to the list of the parent's children + parent->appendChild(clone); + // Generates the link between parent and child attributes + gchar *href_str = g_strdup_printf("#%s", old_repr->attribute("id")); + clone->setAttribute("xlink:href", href_str, false); + g_free(href_str); + + SPObject *clone_object = doc->getObjectByRepr(clone); + // Conversion object->item + item_copied = SP_ITEM(clone_object); + Geom::Point center = item->getCenter(); + sp_spray_scale_rel(center, desktop, item_copied, Geom::Scale(_scale, _scale)); + sp_spray_scale_rel(center, desktop, item_copied, Geom::Scale(scale, scale)); + sp_spray_rotate_rel(center, desktop, item_copied, Geom::Rotate(angle)); + Geom::Point move = (Geom::Point(cos(tilt)*cos(dp)*dr/(1-ratio)+sin(tilt)*sin(dp)*dr/(1+ratio), -sin(tilt)*cos(dp)*dr/(1-ratio)+cos(tilt)*sin(dp)*dr/(1+ratio)))+(p-a->midpoint()); + sp_item_move_rel(item_copied, Geom::Translate(move[Geom::X], -move[Geom::Y])); + + Inkscape::GC::release(clone); + + did = true; + } + } + } + + return did; +} + +static bool sp_spray_dilate(SprayTool *tc, Geom::Point /*event_p*/, Geom::Point p, Geom::Point vector, bool reverse) +{ + SPDesktop *desktop = tc->desktop; + Inkscape::Selection *selection = sp_desktop_selection(desktop); + + if (selection->isEmpty()) { + return false; + } + + bool did = false; + double radius = get_dilate_radius(tc); + double path_force = get_path_force(tc); + if (radius == 0 || path_force == 0) { + return false; + } + double path_mean = get_path_mean(tc); + if (radius == 0 || path_mean == 0) { + return false; + } + double path_standard_deviation = get_path_standard_deviation(tc); + if (radius == 0 || path_standard_deviation == 0) { + return false; + } + double move_force = get_move_force(tc); + double move_mean = get_move_mean(tc); + double move_standard_deviation = get_move_standard_deviation(tc); + + { + GSList *const original_selection = g_slist_copy(const_cast<GSList *>(selection->itemList())); + + for (GSList *items = original_selection; + items != NULL; + items = items->next) { + sp_object_ref(SP_ITEM(items->data)); + } + + for (GSList *items = original_selection; + items != NULL; + items = items->next) { + SPItem *item = SP_ITEM(items->data); + + if (is_transform_modes(tc->mode)) { + if (sp_spray_recursive(desktop, selection, item, p, vector, tc->mode, radius, move_force, tc->population, tc->scale, tc->scale_variation, reverse, move_mean, move_standard_deviation, tc->ratio, tc->tilt, tc->rotation_variation, tc->distrib)) { + did = true; + } + } else { + if (sp_spray_recursive(desktop, selection, item, p, vector, tc->mode, radius, path_force, tc->population, tc->scale, tc->scale_variation, reverse, path_mean, path_standard_deviation, tc->ratio, tc->tilt, tc->rotation_variation, tc->distrib)) { + did = true; + } + } + } + + for (GSList *items = original_selection; + items != NULL; + items = items->next) { + sp_object_unref(SP_ITEM(items->data)); + } + } + + return did; +} + +static void sp_spray_update_area(SprayTool *tc) +{ + double radius = get_dilate_radius(tc); + Geom::Affine const sm ( Geom::Scale(radius/(1-tc->ratio), radius/(1+tc->ratio)) ); + sp_canvas_item_affine_absolute(tc->dilate_area, (sm* Geom::Rotate(tc->tilt))* Geom::Translate(SP_EVENT_CONTEXT(tc)->desktop->point())); + sp_canvas_item_show(tc->dilate_area); +} + +static void sp_spray_switch_mode(SprayTool *tc, gint mode, bool with_shift) +{ + // Select the button mode + SP_EVENT_CONTEXT(tc)->desktop->setToolboxSelectOneValue("spray_tool_mode", mode); + // Need to set explicitly, because the prefs may not have changed by the previous + tc->mode = mode; + tc->update_cursor(with_shift); +} + +bool SprayTool::root_handler(GdkEvent* event) { + gint ret = FALSE; + + switch (event->type) { + case GDK_ENTER_NOTIFY: + sp_canvas_item_show(this->dilate_area); + break; + case GDK_LEAVE_NOTIFY: + sp_canvas_item_hide(this->dilate_area); + break; + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + if (Inkscape::have_viable_layer(desktop, this->message_context) == false) { + return TRUE; + } + + Geom::Point const motion_w(event->button.x, event->button.y); + Geom::Point const motion_dt(desktop->w2d(motion_w)); + this->last_push = desktop->dt2doc(motion_dt); + + sp_spray_extinput(this, event); + + desktop->canvas->forceFullRedrawAfterInterruptions(3); + this->is_drawing = true; + this->is_dilating = true; + this->has_dilated = false; + + if(this->is_dilating && event->button.button == 1 && !this->space_panning) { + sp_spray_dilate(this, motion_w, desktop->dt2doc(motion_dt), Geom::Point(0,0), MOD__SHIFT(event)); + } + + this->has_dilated = true; + ret = TRUE; + } + break; + case GDK_MOTION_NOTIFY: { + Geom::Point const motion_w(event->motion.x, + event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); + Geom::Point motion_doc(desktop->dt2doc(motion_dt)); + sp_spray_extinput(this, event); + + // Draw the dilating cursor + double radius = get_dilate_radius(this); + Geom::Affine const sm (Geom::Scale(radius/(1-this->ratio), radius/(1+this->ratio)) ); + sp_canvas_item_affine_absolute(this->dilate_area, (sm*Geom::Rotate(this->tilt))*Geom::Translate(desktop->w2d(motion_w))); + sp_canvas_item_show(this->dilate_area); + + guint num = 0; + if (!desktop->selection->isEmpty()) { + num = g_slist_length(const_cast<GSList *>(desktop->selection->itemList())); + } + if (num == 0) { + this->message_context->flash(Inkscape::ERROR_MESSAGE, _("<b>Nothing selected!</b> Select objects to spray.")); + } + + // Dilating: + if (this->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK )) { + sp_spray_dilate(this, motion_w, motion_doc, motion_doc - this->last_push, event->button.state & GDK_SHIFT_MASK? true : false); + //this->last_push = motion_doc; + this->has_dilated = true; + + // It's slow, so prevent clogging up with events + gobble_motion_events(GDK_BUTTON1_MASK); + return TRUE; + } + } + break; + /* Spray with the scroll */ + case GDK_SCROLL: { + if (event->scroll.state & GDK_BUTTON1_MASK) { + double temp ; + temp = this->population; + this->population = 1.0; + desktop->setToolboxAdjustmentValue("population", this->population * 100); + Geom::Point const scroll_w(event->button.x, event->button.y); + Geom::Point const scroll_dt = desktop->point();; + Geom::Point motion_doc(desktop->dt2doc(scroll_dt)); + switch (event->scroll.direction) { + case GDK_SCROLL_DOWN: + case GDK_SCROLL_UP: { + if (Inkscape::have_viable_layer(desktop, this->message_context) == false) { + return TRUE; + } + this->last_push = desktop->dt2doc(scroll_dt); + sp_spray_extinput(this, event); + desktop->canvas->forceFullRedrawAfterInterruptions(3); + this->is_drawing = true; + this->is_dilating = true; + this->has_dilated = false; + if(this->is_dilating && !this->space_panning) { + sp_spray_dilate(this, scroll_w, desktop->dt2doc(scroll_dt), Geom::Point(0,0), false); + } + this->has_dilated = true; + + this->population = temp; + desktop->setToolboxAdjustmentValue("population", this->population * 100); + + ret = TRUE; + } + break; + case GDK_SCROLL_RIGHT: + {} break; + case GDK_SCROLL_LEFT: + {} break; + } + } + break; + } + + case GDK_BUTTON_RELEASE: { + Geom::Point const motion_w(event->button.x, event->button.y); + Geom::Point const motion_dt(desktop->w2d(motion_w)); + + desktop->canvas->endForcedFullRedraws(); + this->is_drawing = false; + + if (this->is_dilating && event->button.button == 1 && !this->space_panning) { + if (!this->has_dilated) { + // If we did not rub, do a light tap + this->pressure = 0.03; + sp_spray_dilate(this, motion_w, desktop->dt2doc(motion_dt), Geom::Point(0,0), MOD__SHIFT(event)); + } + this->is_dilating = false; + this->has_dilated = false; + switch (this->mode) { + case SPRAY_MODE_COPY: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_SPRAY, _("Spray with copies")); + break; + case SPRAY_MODE_CLONE: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_SPRAY, _("Spray with clones")); + break; + case SPRAY_MODE_SINGLE_PATH: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_SPRAY, _("Spray in single path")); + break; + } + } + break; + } + + case GDK_KEY_PRESS: + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_j: + case GDK_KEY_J: + if (MOD__SHIFT_ONLY(event)) { + sp_spray_switch_mode(this, SPRAY_MODE_COPY, MOD__SHIFT(event)); + ret = TRUE; + } + break; + case GDK_KEY_k: + case GDK_KEY_K: + if (MOD__SHIFT_ONLY(event)) { + sp_spray_switch_mode(this, SPRAY_MODE_CLONE, MOD__SHIFT(event)); + ret = TRUE; + } + break; +#ifdef ENABLE_SPRAY_MODE_SINGLE_PATH + case GDK_KEY_l: + case GDK_KEY_L: + if (MOD__SHIFT_ONLY(event)) { + sp_spray_switch_mode(this, SPRAY_MODE_SINGLE_PATH, MOD__SHIFT(event)); + ret = TRUE; + } + break; +#endif + case GDK_KEY_Up: + case GDK_KEY_KP_Up: + if (!MOD__CTRL_ONLY(event)) { + this->population += 0.01; + if (this->population > 1.0) { + this->population = 1.0; + } + desktop->setToolboxAdjustmentValue("spray-population", this->population * 100); + ret = TRUE; + } + break; + case GDK_KEY_Down: + case GDK_KEY_KP_Down: + if (!MOD__CTRL_ONLY(event)) { + this->population -= 0.01; + if (this->population < 0.0) { + this->population = 0.0; + } + desktop->setToolboxAdjustmentValue("spray-population", this->population * 100); + ret = TRUE; + } + break; + case GDK_KEY_Right: + case GDK_KEY_KP_Right: + if (!MOD__CTRL_ONLY(event)) { + this->width += 0.01; + if (this->width > 1.0) { + this->width = 1.0; + } + // The same spinbutton is for alt+x + desktop->setToolboxAdjustmentValue("altx-spray", this->width * 100); + sp_spray_update_area(this); + ret = TRUE; + } + break; + case GDK_KEY_Left: + case GDK_KEY_KP_Left: + if (!MOD__CTRL_ONLY(event)) { + this->width -= 0.01; + if (this->width < 0.01) { + this->width = 0.01; + } + desktop->setToolboxAdjustmentValue("altx-spray", this->width * 100); + sp_spray_update_area(this); + ret = TRUE; + } + break; + case GDK_KEY_Home: + case GDK_KEY_KP_Home: + this->width = 0.01; + desktop->setToolboxAdjustmentValue("altx-spray", this->width * 100); + sp_spray_update_area(this); + ret = TRUE; + break; + case GDK_KEY_End: + case GDK_KEY_KP_End: + this->width = 1.0; + desktop->setToolboxAdjustmentValue("altx-spray", this->width * 100); + sp_spray_update_area(this); + ret = TRUE; + break; + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo("altx-spray"); + ret = TRUE; + } + break; + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + this->update_cursor(true); + break; + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + break; + case GDK_KEY_Delete: + case GDK_KEY_KP_Delete: + case GDK_KEY_BackSpace: + ret = this->deleteSelectedDrag(MOD__CTRL_ONLY(event)); + break; + + default: + break; + } + break; + + case GDK_KEY_RELEASE: { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + switch (get_group0_keyval(&event->key)) { + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + this->update_cursor(false); + break; + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + sp_spray_switch_mode (this, prefs->getInt("/tools/spray/mode"), MOD__SHIFT(event)); + this->message_context->clear(); + break; + default: + sp_spray_switch_mode (this, prefs->getInt("/tools/spray/mode"), MOD__SHIFT(event)); + break; + } + } + + default: + break; + } + + if (!ret) { +// if ((SP_EVENT_CONTEXT_CLASS(sp_spray_context_parent_class))->root_handler) { +// ret = (SP_EVENT_CONTEXT_CLASS(sp_spray_context_parent_class))->root_handler(event_context, event); +// } + ret = ToolBase::root_handler(event); + } + + return ret; +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : + diff --git a/src/ui/tools/spray-tool.h b/src/ui/tools/spray-tool.h new file mode 100644 index 000000000..1a8f98006 --- /dev/null +++ b/src/ui/tools/spray-tool.h @@ -0,0 +1,121 @@ +#ifndef __SP_SPRAY_CONTEXT_H__ +#define __SP_SPRAY_CONTEXT_H__ + +/* + * Spray Tool + * + * Authors: + * Pierre-Antoine MARC + * Pierre CACLIN + * Aurel-Aimé MARMION + * Julien LERAY + * Benoît LAVORATA + * Vincent MONTAGNE + * Pierre BARBRY-BLOT + * + * Copyright (C) 2009 authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include <2geom/point.h> +#include "ui/tools/tool-base.h" + +#define SP_SPRAY_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::SprayTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_SPRAY_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::SprayTool*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +namespace Inkscape { + namespace UI { + namespace Dialog { + class Dialog; + } + } +} + + +#define SAMPLING_SIZE 8 /* fixme: ?? */ + +#define TC_MIN_PRESSURE 0.0 +#define TC_MAX_PRESSURE 1.0 +#define TC_DEFAULT_PRESSURE 0.35 + +namespace Inkscape { +namespace UI { +namespace Tools { + +enum { + SPRAY_MODE_COPY, + SPRAY_MODE_CLONE, + SPRAY_MODE_SINGLE_PATH, + SPRAY_OPTION, +}; + +class SprayTool : public ToolBase { +public: + SprayTool(); + virtual ~SprayTool(); + + //ToolBase event_context; + //Inkscape::UI::Dialog::Dialog *dialog_option;//Attribut de type SprayOptionClass, localisé dans scr/ui/dialog + /* extended input data */ + gdouble pressure; + + /* attributes */ + bool dragging; /* mouse state: mouse is dragging */ + bool usepressure; + bool usetilt; + bool usetext; + + double width; + double ratio; + double tilt; + double rotation_variation; + double force; + double population; + double scale_variation; + double scale; + double mean; + double standard_deviation; + + gint distrib; + + gint mode; + + bool is_drawing; + + bool is_dilating; + bool has_dilated; + Geom::Point last_push; + SPCanvasItem *dilate_area; + + sigc::connection style_set_connection; + + static const std::string prefsPath; + + virtual void setup(); + virtual void set(const Inkscape::Preferences::Entry& val); + virtual bool root_handler(GdkEvent* event); + + virtual const std::string& getPrefsPath(); + + + void update_cursor(bool /*with_shift*/); +}; + +} +} +} + +#endif + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : + diff --git a/src/ui/tools/star-tool.cpp b/src/ui/tools/star-tool.cpp new file mode 100644 index 000000000..68f998920 --- /dev/null +++ b/src/ui/tools/star-tool.cpp @@ -0,0 +1,484 @@ +/* + * Star drawing context + * + * Authors: + * Mitsuru Oka <oka326@parkcity.ne.jp> + * Lauris Kaplinski <lauris@kaplinski.com> + * bulia byak <buliabyak@users.sf.net> + * Jon A. Cruz <jon@joncruz.org> + * Abhishek Sharma + * + * Copyright (C) 1999-2002 Lauris Kaplinski + * Copyright (C) 2001-2002 Mitsuru Oka + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include <cstring> +#include <string> + +#include <gdk/gdkkeysyms.h> + +#include "macros.h" +#include "display/sp-canvas.h" +#include "sp-star.h" +#include "document.h" +#include "document-undo.h" +#include "sp-namedview.h" +#include "selection.h" +#include "desktop-handles.h" +#include "snap.h" +#include "desktop.h" +#include "desktop-style.h" +#include "message-context.h" +#include "pixmaps/cursor-star.xpm" +#include <glibmm/i18n.h> +#include "preferences.h" +#include "xml/repr.h" +#include "xml/node-event-vector.h" +#include "context-fns.h" +#include "shape-editor.h" +#include "verbs.h" +#include "display/sp-canvas-item.h" + +#include "ui/tools/star-tool.h" + +using Inkscape::DocumentUndo; + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +namespace { + ToolBase* createStarContext() { + return new StarTool(); + } + + bool starContextRegistered = ToolFactory::instance().registerObject("/tools/shapes/star", createStarContext); +} + +const std::string& StarTool::getPrefsPath() { + return StarTool::prefsPath; +} + +const std::string StarTool::prefsPath = "/tools/shapes/star"; + +StarTool::StarTool() + : ToolBase(cursor_star_xpm, 4, 4) + , star(NULL) + , magnitude(5) + , proportion(0.5) + , isflatsided(false) + , rounded(0) + , randomized(0) +{ +} + +void StarTool::finish() { + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), GDK_CURRENT_TIME); + + this->finishItem(); + this->sel_changed_connection.disconnect(); + + ToolBase::finish(); +} + +StarTool::~StarTool() { + this->enableGrDrag(false); + + this->sel_changed_connection.disconnect(); + + delete this->shape_editor; + this->shape_editor = NULL; + + /* fixme: This is necessary because we do not grab */ + if (this->star) { + this->finishItem(); + } +} + +/** + * Callback that processes the "changed" signal on the selection; + * destroys old and creates new knotholder. + * + * @param selection Should not be NULL. + */ +void StarTool::selection_changed(Inkscape::Selection* selection) { + g_assert (selection != NULL); + + this->shape_editor->unset_item(SH_KNOTHOLDER); + this->shape_editor->set_item(selection->singleItem(), SH_KNOTHOLDER); +} + +void StarTool::setup() { + ToolBase::setup(); + + sp_event_context_read(this, "magnitude"); + sp_event_context_read(this, "proportion"); + sp_event_context_read(this, "isflatsided"); + sp_event_context_read(this, "rounded"); + sp_event_context_read(this, "randomized"); + + this->shape_editor = new ShapeEditor(this->desktop); + + SPItem *item = sp_desktop_selection(this->desktop)->singleItem(); + if (item) { + this->shape_editor->set_item(item, SH_KNOTHOLDER); + } + + Inkscape::Selection *selection = sp_desktop_selection(this->desktop); + + this->sel_changed_connection.disconnect(); + + this->sel_changed_connection = selection->connectChanged(sigc::mem_fun(this, &StarTool::selection_changed)); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/tools/shapes/selcue")) { + this->enableSelectionCue(); + } + + if (prefs->getBool("/tools/shapes/gradientdrag")) { + this->enableGrDrag(); + } +} + +void StarTool::set(const Inkscape::Preferences::Entry& val) { + Glib::ustring path = val.getEntryName(); + + if (path == "magnitude") { + this->magnitude = CLAMP(val.getInt(5), 3, 1024); + } else if (path == "proportion") { + this->proportion = CLAMP(val.getDouble(0.5), 0.01, 2.0); + } else if (path == "isflatsided") { + this->isflatsided = val.getBool(); + } else if (path == "rounded") { + this->rounded = val.getDouble(); + } else if (path == "randomized") { + this->randomized = val.getDouble(); + } +} + +bool StarTool::root_handler(GdkEvent* event) { + static bool dragging; + + SPDesktop *desktop = this->desktop; + Inkscape::Selection *selection = sp_desktop_selection (desktop); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + this->tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + + gint ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + dragging = true; + + this->center = Inkscape::setup_for_drag_start(desktop, this, event); + + /* Snap center */ + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop, true); + m.freeSnapReturnByRef(this->center, Inkscape::SNAPSOURCE_NODE_HANDLE); + m.unSetup(); + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + GDK_KEY_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | + GDK_POINTER_MOTION_MASK | + GDK_POINTER_MOTION_HINT_MASK | + GDK_BUTTON_PRESS_MASK, + NULL, event->button.time); + ret = TRUE; + } + break; + + case GDK_MOTION_NOTIFY: + if (dragging && (event->motion.state & GDK_BUTTON1_MASK) && !this->space_panning) { + if ( this->within_tolerance + && ( abs( (gint) event->motion.x - this->xp ) < this->tolerance ) + && ( abs( (gint) event->motion.y - this->yp ) < this->tolerance ) ) { + break; // do not drag if we're within tolerance from origin + } + // Once the user has moved farther than tolerance from the original location + // (indicating they intend to draw, not click), then always process the + // motion notify coordinates as given (no snapping back to origin) + this->within_tolerance = false; + + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); + + this->drag(motion_dt, event->motion.state); + + gobble_motion_events(GDK_BUTTON1_MASK); + + ret = TRUE; + } else if (!this->sp_event_context_knot_mouseover()) { + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); + + m.preSnap(Inkscape::SnapCandidatePoint(motion_dt, Inkscape::SNAPSOURCE_NODE_HANDLE)); + m.unSetup(); + } + break; + case GDK_BUTTON_RELEASE: + this->xp = this->yp = 0; + + if (event->button.button == 1 && !this->space_panning) { + dragging = false; + + sp_event_context_discard_delayed_snap_event(this); + + if (!this->within_tolerance) { + // we've been dragging, finish the star + this->finishItem(); + } else if (this->item_to_select) { + // no dragging, select clicked item if any + if (event->button.state & GDK_SHIFT_MASK) { + selection->toggle(this->item_to_select); + } else { + selection->set(this->item_to_select); + } + } else { + // click in an empty space + selection->clear(); + } + + this->item_to_select = NULL; + ret = TRUE; + sp_canvas_item_ungrab(SP_CANVAS_ITEM (desktop->acetate), event->button.time); + } + break; + + case GDK_KEY_PRESS: + switch (get_group0_keyval(&event->key)) { + case GDK_KEY_Alt_R: + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + case GDK_KEY_Meta_L: // Meta is when you press Shift+Alt (at least on my machine) + case GDK_KEY_Meta_R: + sp_event_show_modifier_tip(this->defaultMessageContext(), event, + _("<b>Ctrl</b>: snap angle; keep rays radial"), + NULL, + NULL); + break; + + case GDK_KEY_Up: + case GDK_KEY_Down: + case GDK_KEY_KP_Up: + case GDK_KEY_KP_Down: + // prevent the zoom field from activation + if (!MOD__CTRL_ONLY(event)) + ret = TRUE; + break; + + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo ("altx-star"); + ret = TRUE; + } + break; + + case GDK_KEY_Escape: + if (dragging) { + dragging = false; + sp_event_context_discard_delayed_snap_event(this); + // if drawing, cancel, otherwise pass it up for deselecting + this->cancel(); + ret = TRUE; + } + break; + + case GDK_KEY_space: + if (dragging) { + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time); + + dragging = false; + + sp_event_context_discard_delayed_snap_event(this); + + if (!this->within_tolerance) { + // we've been dragging, finish the star + this->finishItem(); + } + // do not return true, so that space would work switching to selector + } + break; + + case GDK_KEY_Delete: + case GDK_KEY_KP_Delete: + case GDK_KEY_BackSpace: + ret = this->deleteSelectedDrag(MOD__CTRL_ONLY(event)); + break; + + default: + break; + } + break; + + case GDK_KEY_RELEASE: + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + case GDK_KEY_Meta_L: // Meta is when you press Shift+Alt + case GDK_KEY_Meta_R: + this->defaultMessageContext()->clear(); + break; + + default: + break; + } + break; + + default: + break; + } + + if (!ret) { + ret = ToolBase::root_handler(event); + } + + return ret; +} + +void StarTool::drag(Geom::Point p, guint state) +{ + SPDesktop *desktop = this->desktop; + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int const snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12); + + if (!this->star) { + if (Inkscape::have_viable_layer(desktop, this->message_context) == false) { + return; + } + + // Create object + Inkscape::XML::Document *xml_doc = this->desktop->doc()->getReprDoc(); + Inkscape::XML::Node *repr = xml_doc->createElement("svg:path"); + repr->setAttribute("sodipodi:type", "star"); + + // Set style + sp_desktop_apply_style_tool(desktop, repr, "/tools/shapes/star", false); + + this->star = SP_STAR(desktop->currentLayer()->appendChildRepr(repr)); + + Inkscape::GC::release(repr); + this->star->transform = SP_ITEM(desktop->currentLayer())->i2doc_affine().inverse(); + this->star->updateRepr(); + + desktop->canvas->forceFullRedrawAfterInterruptions(5); + } + + /* Snap corner point with no constraints */ + SnapManager &m = desktop->namedview->snap_manager; + + m.setup(desktop, true, this->star); + Geom::Point pt2g = p; + m.freeSnapReturnByRef(pt2g, Inkscape::SNAPSOURCE_NODE_HANDLE); + m.unSetup(); + + Geom::Point const p0 = desktop->dt2doc(this->center); + Geom::Point const p1 = desktop->dt2doc(pt2g); + + double const sides = (gdouble) this->magnitude; + Geom::Point const d = p1 - p0; + Geom::Coord const r1 = Geom::L2(d); + double arg1 = atan2(d); + + if (state & GDK_CONTROL_MASK) { + /* Snap angle */ + arg1 = sp_round(arg1, M_PI / snaps); + } + + sp_star_position_set(this->star, this->magnitude, p0, r1, r1 * this->proportion, + arg1, arg1 + M_PI / sides, this->isflatsided, this->rounded, this->randomized); + + /* status text */ + Inkscape::Util::Quantity q = Inkscape::Util::Quantity(r1, "px"); + GString *rads = g_string_new(q.string(desktop->namedview->doc_units).c_str()); + this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, + ( this->isflatsided? + _("<b>Polygon</b>: radius %s, angle %5g°; with <b>Ctrl</b> to snap angle") + : _("<b>Star</b>: radius %s, angle %5g°; with <b>Ctrl</b> to snap angle") ), + rads->str, sp_round((arg1) * 180 / M_PI, 0.0001)); + + g_string_free(rads, FALSE); +} + +void StarTool::finishItem() { + this->message_context->clear(); + + if (this->star != NULL) { + if (this->star->r[1] == 0) { + // Don't allow the creating of zero sized arc, for example + // when the start and and point snap to the snap grid point + this->cancel(); + return; + } + + // Set transform center, so that odd stars rotate correctly + // LP #462157 + this->star->setCenter(this->center); + this->star->set_shape(); + this->star->updateRepr(SP_OBJECT_WRITE_EXT); + this->star->doWriteTransform(this->star->getRepr(), this->star->transform, NULL, true); + + desktop->canvas->endForcedFullRedraws(); + + sp_desktop_selection(desktop)->set(this->star); + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_STAR, + _("Create star")); + + this->star = NULL; + } +} + +void StarTool::cancel() { + sp_desktop_selection(desktop)->clear(); + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0); + + if (this->star != NULL) { + this->star->deleteObject(); + this->star = NULL; + } + + this->within_tolerance = false; + this->xp = 0; + this->yp = 0; + this->item_to_select = NULL; + + desktop->canvas->endForcedFullRedraws(); + + DocumentUndo::cancel(sp_desktop_document(desktop)); +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/star-tool.h b/src/ui/tools/star-tool.h new file mode 100644 index 000000000..da3774e68 --- /dev/null +++ b/src/ui/tools/star-tool.h @@ -0,0 +1,74 @@ +#ifndef __SP_STAR_CONTEXT_H__ +#define __SP_STAR_CONTEXT_H__ + +/* + * Star drawing context + * + * Authors: + * Mitsuru Oka <oka326@parkcity.ne.jp> + * Lauris Kaplinski <lauris@kaplinski.com> + * + * Copyright (C) 1999-2002 Lauris Kaplinski + * Copyright (C) 2001-2002 Mitsuru Oka + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include <stddef.h> +#include <sigc++/sigc++.h> +#include <2geom/point.h> +#include "ui/tools/tool-base.h" + +#include "sp-star.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +class StarTool : public ToolBase { +public: + StarTool(); + virtual ~StarTool(); + + static const std::string prefsPath; + + virtual void setup(); + virtual void finish(); + virtual void set(const Inkscape::Preferences::Entry& val); + virtual bool root_handler(GdkEvent* event); + + virtual const std::string& getPrefsPath(); + +private: + SPStar* star; + + Geom::Point center; + + /* Number of corners */ + gint magnitude; + + /* Outer/inner radius ratio */ + gdouble proportion; + + /* flat sides or not? */ + bool isflatsided; + + /* rounded corners ratio */ + gdouble rounded; + + // randomization + gdouble randomized; + + sigc::connection sel_changed_connection; + + void drag(Geom::Point p, guint state); + void finishItem(); + void cancel(); + void selection_changed(Inkscape::Selection* selection); +}; + +} +} +} + +#endif diff --git a/src/ui/tools/text-tool.cpp b/src/ui/tools/text-tool.cpp new file mode 100644 index 000000000..ac830fe6b --- /dev/null +++ b/src/ui/tools/text-tool.cpp @@ -0,0 +1,1732 @@ +/* + * TextTool + * + * Authors: + * Lauris Kaplinski <lauris@kaplinski.com> + * bulia byak <buliabyak@users.sf.net> + * Jon A. Cruz <jon@joncruz.org> + * Abhishek Sharma + * + * Copyright (C) 1999-2005 authors + * Copyright (C) 2001 Ximian, Inc. + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#include <gtkmm/clipboard.h> +#include <display/sp-ctrlline.h> +#include <display/sodipodi-ctrlrect.h> +#include <display/sp-ctrlquadr.h> +#include <gdk/gdkkeysyms.h> +#include <glibmm/i18n.h> +#include <sstream> + +#include "context-fns.h" +#include "desktop-handles.h" +#include "desktop-style.h" +#include "desktop.h" +#include "document.h" +#include "document-undo.h" +#include "macros.h" +#include "message-context.h" +#include "message-stack.h" +#include "pixmaps/cursor-text-insert.xpm" +#include "pixmaps/cursor-text.xpm" +#include "preferences.h" +#include "rubberband.h" +#include "selection-chemistry.h" +#include "selection.h" +#include "shape-editor.h" +#include "sp-flowtext.h" +#include "sp-namedview.h" +#include "sp-text.h" +#include "style.h" +#include "ui/tools/text-tool.h" +#include "text-editing.h" +#include "ui/control-manager.h" +#include "verbs.h" +#include "xml/node-event-vector.h" +#include "xml/repr.h" +#include <gtk/gtk.h> +#include "tool-factory.h" + +using Inkscape::ControlManager; +using Inkscape::DocumentUndo; + +namespace Inkscape { +namespace UI { +namespace Tools { + +static void sp_text_context_validate_cursor_iterators(TextTool *tc); +static void sp_text_context_update_cursor(TextTool *tc, bool scroll_to_see = true); +static void sp_text_context_update_text_selection(TextTool *tc); +static gint sp_text_context_timeout(TextTool *tc); +static void sp_text_context_forget_text(TextTool *tc); + +static gint sptc_focus_in(GtkWidget *widget, GdkEventFocus *event, TextTool *tc); +static gint sptc_focus_out(GtkWidget *widget, GdkEventFocus *event, TextTool *tc); +static void sptc_commit(GtkIMContext *imc, gchar *string, TextTool *tc); + +namespace { + ToolBase* createTextContext() { + return new TextTool(); + } + + bool textContextRegistered = ToolFactory::instance().registerObject("/tools/text", createTextContext); +} + +const std::string& TextTool::getPrefsPath() { + return TextTool::prefsPath; +} + +const std::string TextTool::prefsPath = "/tools/text"; + + +TextTool::TextTool() + : ToolBase(cursor_text_xpm, 7, 7) + , imc(NULL) + , text(NULL) + , pdoc(0, 0) + , unimode(false) + , unipos(0) + , cursor(NULL) + , indicator(NULL) + , frame(NULL) + , timeout(0) + , show(false) + , phase(false) + , nascent_object(false) + , over_text(false) + , dragging(0) + , creating(false) + , grabbed(NULL) + , preedit_string(NULL) +{ +} + +TextTool::~TextTool() { + delete this->shape_editor; + this->shape_editor = NULL; + + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed, GDK_CURRENT_TIME); + this->grabbed = NULL; + } + + Inkscape::Rubberband::get(this->desktop)->stop(); +} + +void TextTool::setup() { + GtkSettings* settings = gtk_settings_get_default(); + gint timeout = 0; + g_object_get( settings, "gtk-cursor-blink-time", &timeout, NULL ); + + if (timeout < 0) { + timeout = 200; + } else { + timeout /= 2; + } + + this->cursor = ControlManager::getManager().createControlLine(sp_desktop_controls(desktop), Geom::Point(100, 0), Geom::Point(100, 100)); + this->cursor->setRgba32(0x000000ff); + sp_canvas_item_hide(this->cursor); + + this->indicator = sp_canvas_item_new(sp_desktop_controls(desktop), SP_TYPE_CTRLRECT, NULL); + SP_CTRLRECT(this->indicator)->setRectangle(Geom::Rect(Geom::Point(0, 0), Geom::Point(100, 100))); + SP_CTRLRECT(this->indicator)->setColor(0x0000ff7f, false, 0); + SP_CTRLRECT(this->indicator)->setShadow(1, 0xffffff7f); + sp_canvas_item_hide(this->indicator); + + this->frame = sp_canvas_item_new(sp_desktop_controls(desktop), SP_TYPE_CTRLRECT, NULL); + SP_CTRLRECT(this->frame)->setRectangle(Geom::Rect(Geom::Point(0, 0), Geom::Point(100, 100))); + SP_CTRLRECT(this->frame)->setColor(0x0000ff7f, false, 0); + sp_canvas_item_hide(this->frame); + + this->timeout = g_timeout_add(timeout, (GSourceFunc) sp_text_context_timeout, this); + + this->imc = gtk_im_multicontext_new(); + if (this->imc) { + GtkWidget *canvas = GTK_WIDGET(sp_desktop_canvas(desktop)); + + /* im preedit handling is very broken in inkscape for + * multi-byte characters. See bug 1086769. + * We need to let the IM handle the preediting, and + * just take in the characters when they're finished being + * entered. + */ + gtk_im_context_set_use_preedit(this->imc, FALSE); + gtk_im_context_set_client_window(this->imc, + gtk_widget_get_window (canvas)); + + g_signal_connect(G_OBJECT(canvas), "focus_in_event", G_CALLBACK(sptc_focus_in), this); + g_signal_connect(G_OBJECT(canvas), "focus_out_event", G_CALLBACK(sptc_focus_out), this); + g_signal_connect(G_OBJECT(this->imc), "commit", G_CALLBACK(sptc_commit), this); + + if (gtk_widget_has_focus(canvas)) { + sptc_focus_in(canvas, NULL, this); + } + } + + ToolBase::setup(); + + this->shape_editor = new ShapeEditor(this->desktop); + + SPItem *item = sp_desktop_selection(this->desktop)->singleItem(); + if (item && SP_IS_FLOWTEXT(item) && SP_FLOWTEXT(item)->has_internal_frame()) { + this->shape_editor->set_item(item, SH_KNOTHOLDER); + } + + this->sel_changed_connection = sp_desktop_selection(desktop)->connectChangedFirst( + sigc::mem_fun(*this, &TextTool::_selectionChanged) + ); + this->sel_modified_connection = sp_desktop_selection(desktop)->connectModifiedFirst( + sigc::mem_fun(*this, &TextTool::_selectionModified) + ); + this->style_set_connection = desktop->connectSetStyle( + sigc::mem_fun(*this, &TextTool::_styleSet) + ); + this->style_query_connection = desktop->connectQueryStyle( + sigc::mem_fun(*this, &TextTool::_styleQueried) + ); + + _selectionChanged(sp_desktop_selection(desktop)); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/tools/text/selcue")) { + this->enableSelectionCue(); + } + if (prefs->getBool("/tools/text/gradientdrag")) { + this->enableGrDrag(); + } +} + +void TextTool::finish() { + if (this->desktop) { + sp_signal_disconnect_by_data(sp_desktop_canvas(this->desktop), this); + } + + this->enableGrDrag(false); + + this->style_set_connection.disconnect(); + this->style_query_connection.disconnect(); + this->sel_changed_connection.disconnect(); + this->sel_modified_connection.disconnect(); + + sp_text_context_forget_text(SP_TEXT_CONTEXT(this)); + + if (this->imc) { + g_object_unref(G_OBJECT(this->imc)); + this->imc = NULL; + } + + if (this->timeout) { + g_source_remove(this->timeout); + this->timeout = 0; + } + + if (this->cursor) { + sp_canvas_item_destroy(this->cursor); + this->cursor = NULL; + } + + if (this->indicator) { + sp_canvas_item_destroy(this->indicator); + this->indicator = NULL; + } + + if (this->frame) { + sp_canvas_item_destroy(this->frame); + this->frame = NULL; + } + + for (std::vector<SPCanvasItem*>::iterator it = this->text_selection_quads.begin() ; + it != this->text_selection_quads.end() ; ++it) { + sp_canvas_item_hide(*it); + sp_canvas_item_destroy(*it); + } + + this->text_selection_quads.clear(); + + ToolBase::finish(); +} + +bool TextTool::item_handler(SPItem* item, GdkEvent* event) { + SPItem *item_ungrouped; + + gint ret = FALSE; + + sp_text_context_validate_cursor_iterators(this); + Inkscape::Text::Layout::iterator old_start = this->text_sel_start; + + switch (event->type) { + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + // find out clicked item, disregarding groups + item_ungrouped = desktop->getItemAtPoint(Geom::Point(event->button.x, event->button.y), TRUE); + if (SP_IS_TEXT(item_ungrouped) || SP_IS_FLOWTEXT(item_ungrouped)) { + sp_desktop_selection(desktop)->set(item_ungrouped); + if (this->text) { + // find out click point in document coordinates + Geom::Point p = desktop->w2d(Geom::Point(event->button.x, event->button.y)); + // set the cursor closest to that point + if (event->button.state & GDK_SHIFT_MASK) { + this->text_sel_start = old_start; + this->text_sel_end = sp_te_get_position_by_coords(this->text, p); + } else { + this->text_sel_start = this->text_sel_end = sp_te_get_position_by_coords(this->text, p); + } + // update display + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + this->dragging = 1; + } + ret = TRUE; + } + } + break; + case GDK_2BUTTON_PRESS: + if (event->button.button == 1 && this->text) { + Inkscape::Text::Layout const *layout = te_get_layout(this->text); + if (layout) { + if (!layout->isStartOfWord(this->text_sel_start)) + this->text_sel_start.prevStartOfWord(); + if (!layout->isEndOfWord(this->text_sel_end)) + this->text_sel_end.nextEndOfWord(); + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + this->dragging = 2; + ret = TRUE; + } + } + break; + case GDK_3BUTTON_PRESS: + if (event->button.button == 1 && this->text) { + this->text_sel_start.thisStartOfLine(); + this->text_sel_end.thisEndOfLine(); + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + this->dragging = 3; + ret = TRUE; + } + break; + case GDK_BUTTON_RELEASE: + if (event->button.button == 1 && this->dragging && !this->space_panning) { + this->dragging = 0; + sp_event_context_discard_delayed_snap_event(this); + ret = TRUE; + } + break; + case GDK_MOTION_NOTIFY: + if ((event->motion.state & GDK_BUTTON1_MASK) && this->dragging && !this->space_panning) { + Inkscape::Text::Layout const *layout = te_get_layout(this->text); + if (!layout) break; + // find out click point in document coordinates + Geom::Point p = desktop->w2d(Geom::Point(event->button.x, event->button.y)); + // set the cursor closest to that point + Inkscape::Text::Layout::iterator new_end = sp_te_get_position_by_coords(this->text, p); + if (this->dragging == 2) { + // double-click dragging: go by word + if (new_end < this->text_sel_start) { + if (!layout->isStartOfWord(new_end)) + new_end.prevStartOfWord(); + } else + if (!layout->isEndOfWord(new_end)) + new_end.nextEndOfWord(); + } else if (this->dragging == 3) { + // triple-click dragging: go by line + if (new_end < this->text_sel_start) + new_end.thisStartOfLine(); + else + new_end.thisEndOfLine(); + } + // update display + if (this->text_sel_end != new_end) { + this->text_sel_end = new_end; + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + } + gobble_motion_events(GDK_BUTTON1_MASK); + ret = TRUE; + break; + } + // find out item under mouse, disregarding groups + item_ungrouped = desktop->getItemAtPoint(Geom::Point(event->button.x, event->button.y), TRUE); + if (SP_IS_TEXT(item_ungrouped) || SP_IS_FLOWTEXT(item_ungrouped)) { + + Inkscape::Text::Layout const *layout = te_get_layout(item_ungrouped); + if (layout->inputTruncated()) { + SP_CTRLRECT(this->indicator)->setColor(0xff0000ff, false, 0); + } else { + SP_CTRLRECT(this->indicator)->setColor(0x0000ff7f, false, 0); + } + Geom::OptRect ibbox = item_ungrouped->desktopVisualBounds(); + if (ibbox) { + SP_CTRLRECT(this->indicator)->setRectangle(*ibbox); + } + sp_canvas_item_show(this->indicator); + + this->cursor_shape = cursor_text_insert_xpm; + this->hot_x = 7; + this->hot_y = 10; + this->sp_event_context_update_cursor(); + sp_text_context_update_text_selection(this); + + if (SP_IS_TEXT (item_ungrouped)) { + desktop->event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Click</b> to edit the text, <b>drag</b> to select part of the text.")); + } else { + desktop->event_context->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("<b>Click</b> to edit the flowed text, <b>drag</b> to select part of the text.")); + } + + this->over_text = true; + + ret = TRUE; + } + break; + default: + break; + } + + if (!ret) { + ret = ToolBase::item_handler(item, event); + } + + return ret; +} + +static void sp_text_context_setup_text(TextTool *tc) +{ + ToolBase *ec = SP_EVENT_CONTEXT(tc); + + /* Create <text> */ + Inkscape::XML::Document *xml_doc = ec->desktop->doc()->getReprDoc(); + Inkscape::XML::Node *rtext = xml_doc->createElement("svg:text"); + rtext->setAttribute("xml:space", "preserve"); // we preserve spaces in the text objects we create + + /* Set style */ + sp_desktop_apply_style_tool(ec->desktop, rtext, "/tools/text", true); + + sp_repr_set_svg_double(rtext, "x", tc->pdoc[Geom::X]); + sp_repr_set_svg_double(rtext, "y", tc->pdoc[Geom::Y]); + + /* Create <tspan> */ + Inkscape::XML::Node *rtspan = xml_doc->createElement("svg:tspan"); + rtspan->setAttribute("sodipodi:role", "line"); // otherwise, why bother creating the tspan? + rtext->addChild(rtspan, NULL); + Inkscape::GC::release(rtspan); + + /* Create TEXT */ + Inkscape::XML::Node *rstring = xml_doc->createTextNode(""); + rtspan->addChild(rstring, NULL); + Inkscape::GC::release(rstring); + SPItem *text_item = SP_ITEM(ec->desktop->currentLayer()->appendChildRepr(rtext)); + /* fixme: Is selection::changed really immediate? */ + /* yes, it's immediate .. why does it matter? */ + sp_desktop_selection(ec->desktop)->set(text_item); + Inkscape::GC::release(rtext); + text_item->transform = SP_ITEM(ec->desktop->currentLayer())->i2doc_affine().inverse(); + + text_item->updateRepr(); + text_item->doWriteTransform(text_item->getRepr(), text_item->transform, NULL, true); + DocumentUndo::done(sp_desktop_document(ec->desktop), SP_VERB_CONTEXT_TEXT, + _("Create text")); +} + +/** + * Insert the character indicated by tc.uni to replace the current selection, + * and reset tc.uni/tc.unipos to empty string. + * + * \pre tc.uni/tc.unipos non-empty. + */ +static void insert_uni_char(TextTool *const tc) +{ + g_return_if_fail(tc->unipos + && tc->unipos < sizeof(tc->uni) + && tc->uni[tc->unipos] == '\0'); + unsigned int uv; + std::stringstream ss; + ss << std::hex << tc->uni; + ss >> uv; + tc->unipos = 0; + tc->uni[tc->unipos] = '\0'; + + if ( !g_unichar_isprint(static_cast<gunichar>(uv)) + && !(g_unichar_validate(static_cast<gunichar>(uv)) && (g_unichar_type(static_cast<gunichar>(uv)) == G_UNICODE_PRIVATE_USE) ) ) { + // This may be due to bad input, so it goes to statusbar. + tc->desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, + _("Non-printable character")); + } else { + if (!tc->text) { // printable key; create text if none (i.e. if nascent_object) + sp_text_context_setup_text(tc); + tc->nascent_object = 0; // we don't need it anymore, having created a real <text> + } + + gchar u[10]; + guint const len = g_unichar_to_utf8(uv, u); + u[len] = '\0'; + + tc->text_sel_start = tc->text_sel_end = sp_te_replace(tc->text, tc->text_sel_start, tc->text_sel_end, u); + sp_text_context_update_cursor(tc); + sp_text_context_update_text_selection(tc); + DocumentUndo::done(sp_desktop_document(tc->desktop), SP_VERB_DIALOG_TRANSFORM, + _("Insert Unicode character")); + } +} + +static void hex_to_printable_utf8_buf(char const *const ehex, char *utf8) +{ + unsigned int uv; + std::stringstream ss; + ss << std::hex << ehex; + ss >> uv; + if (!g_unichar_isprint((gunichar) uv)) { + uv = 0xfffd; + } + guint const len = g_unichar_to_utf8(uv, utf8); + utf8[len] = '\0'; +} + +static void show_curr_uni_char(TextTool *const tc) +{ + g_return_if_fail(tc->unipos < sizeof(tc->uni) + && tc->uni[tc->unipos] == '\0'); + if (tc->unipos) { + char utf8[10]; + hex_to_printable_utf8_buf(tc->uni, utf8); + + /* Status bar messages are in pango markup, so we need xml escaping. */ + if (utf8[1] == '\0') { + switch(utf8[0]) { + case '<': strcpy(utf8, "<"); break; + case '>': strcpy(utf8, ">"); break; + case '&': strcpy(utf8, "&"); break; + default: break; + } + } + tc->defaultMessageContext()->setF(Inkscape::NORMAL_MESSAGE, + _("Unicode (<b>Enter</b> to finish): %s: %s"), tc->uni, utf8); + } else { + tc->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("Unicode (<b>Enter</b> to finish): ")); + } +} + +bool TextTool::root_handler(GdkEvent* event) { + sp_canvas_item_hide(this->indicator); + + sp_text_context_validate_cursor_iterators(this); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + this->tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + + switch (event->type) { + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + + if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) { + return TRUE; + } + + // save drag origin + this->xp = (gint) event->button.x; + this->yp = (gint) event->button.y; + this->within_tolerance = true; + + Geom::Point const button_pt(event->button.x, event->button.y); + Geom::Point button_dt(desktop->w2d(button_pt)); + + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + m.freeSnapReturnByRef(button_dt, Inkscape::SNAPSOURCE_NODE_HANDLE); + m.unSetup(); + + this->p0 = button_dt; + Inkscape::Rubberband::get(desktop)->start(desktop, this->p0); + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + GDK_KEY_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK, + NULL, event->button.time); + this->grabbed = SP_CANVAS_ITEM(desktop->acetate); + this->creating = 1; + + /* Processed */ + return TRUE; + } + break; + case GDK_MOTION_NOTIFY: + if (this->over_text) { + this->over_text = 0; + // update cursor and statusbar: we are not over a text object now + this->cursor_shape = cursor_text_xpm; + this->hot_x = 7; + this->hot_y = 7; + this->sp_event_context_update_cursor(); + desktop->event_context->defaultMessageContext()->clear(); + } + + if (this->creating && (event->motion.state & GDK_BUTTON1_MASK) && !this->space_panning) { + if ( this->within_tolerance + && ( abs( (gint) event->motion.x - this->xp ) < this->tolerance ) + && ( abs( (gint) event->motion.y - this->yp ) < this->tolerance ) ) { + break; // do not drag if we're within tolerance from origin + } + // Once the user has moved farther than tolerance from the original location + // (indicating they intend to draw, not click), then always process the + // motion notify coordinates as given (no snapping back to origin) + this->within_tolerance = false; + + Geom::Point const motion_pt(event->motion.x, event->motion.y); + Geom::Point p = desktop->w2d(motion_pt); + + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE); + m.unSetup(); + + Inkscape::Rubberband::get(desktop)->move(p); + gobble_motion_events(GDK_BUTTON1_MASK); + + // status text + Inkscape::Util::Quantity x_q = Inkscape::Util::Quantity(fabs((p - this->p0)[Geom::X]), "px"); + Inkscape::Util::Quantity y_q = Inkscape::Util::Quantity(fabs((p - this->p0)[Geom::Y]), "px"); + GString *xs = g_string_new(x_q.string(desktop->namedview->doc_units).c_str()); + GString *ys = g_string_new(y_q.string(desktop->namedview->doc_units).c_str()); + this->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Flowed text frame</b>: %s × %s"), xs->str, ys->str); + + g_string_free(xs, FALSE); + g_string_free(ys, FALSE); + + } else if (!this->sp_event_context_knot_mouseover()) { + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); + m.preSnap(Inkscape::SnapCandidatePoint(motion_dt, Inkscape::SNAPSOURCE_OTHER_HANDLE)); + m.unSetup(); + } + break; + case GDK_BUTTON_RELEASE: + if (event->button.button == 1 && !this->space_panning) { + sp_event_context_discard_delayed_snap_event(this); + + Geom::Point p1 = desktop->w2d(Geom::Point(event->button.x, event->button.y)); + + SnapManager &m = desktop->namedview->snap_manager; + m.setup(desktop); + m.freeSnapReturnByRef(p1, Inkscape::SNAPSOURCE_NODE_HANDLE); + m.unSetup(); + + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed, GDK_CURRENT_TIME); + this->grabbed = NULL; + } + + Inkscape::Rubberband::get(desktop)->stop(); + + if (this->creating && this->within_tolerance) { + /* Button 1, set X & Y & new item */ + sp_desktop_selection(desktop)->clear(); + this->pdoc = desktop->dt2doc(p1); + this->show = TRUE; + this->phase = 1; + this->nascent_object = 1; // new object was just created + + /* Cursor */ + sp_canvas_item_show(this->cursor); + // Cursor height is defined by the new text object's font size; it needs to be set + // artificially here, for the text object does not exist yet: + double cursor_height = sp_desktop_get_font_size_tool(desktop); + this->cursor->setCoords(p1, p1 + Geom::Point(0, cursor_height)); + if (this->imc) { + GdkRectangle im_cursor; + Geom::Point const top_left = SP_EVENT_CONTEXT(this)->desktop->get_display_area().corner(3); + Geom::Point const cursor_size(0, cursor_height); + Geom::Point const im_position = SP_EVENT_CONTEXT(this)->desktop->d2w(p1 + cursor_size - top_left); + im_cursor.x = (int) floor(im_position[Geom::X]); + im_cursor.y = (int) floor(im_position[Geom::Y]); + im_cursor.width = 0; + im_cursor.height = (int) -floor(SP_EVENT_CONTEXT(this)->desktop->d2w(cursor_size)[Geom::Y]); + gtk_im_context_set_cursor_location(this->imc, &im_cursor); + } + this->message_context->set(Inkscape::NORMAL_MESSAGE, _("Type text; <b>Enter</b> to start new line.")); // FIXME:: this is a copy of a string from _update_cursor below, do not desync + + this->within_tolerance = false; + } else if (this->creating) { + double cursor_height = sp_desktop_get_font_size_tool(desktop); + if (fabs(p1[Geom::Y] - this->p0[Geom::Y]) > cursor_height) { + // otherwise even one line won't fit; most probably a slip of hand (even if bigger than tolerance) + SPItem *ft = create_flowtext_with_internal_frame (desktop, this->p0, p1); + /* Set style */ + sp_desktop_apply_style_tool(desktop, ft->getRepr(), "/tools/text", true); + sp_desktop_selection(desktop)->set(ft); + desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Flowed text is created.")); + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT, _("Create flowed text")); + } else { + desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The frame is <b>too small</b> for the current font size. Flowed text not created.")); + } + } + this->creating = false; + return TRUE; + } + break; + case GDK_KEY_PRESS: { + guint const group0_keyval = get_group0_keyval(&event->key); + + if (group0_keyval == GDK_KEY_KP_Add || + group0_keyval == GDK_KEY_KP_Subtract) { + if (!(event->key.state & GDK_MOD2_MASK)) // mod2 is NumLock; if on, type +/- keys + break; // otherwise pass on keypad +/- so they can zoom + } + + if ((this->text) || (this->nascent_object)) { + // there is an active text object in this context, or a new object was just created + + if (this->unimode || !this->imc + || (MOD__CTRL(event) && MOD__SHIFT(event)) // input methods tend to steal this for unimode, + // but we have our own so make sure they don't swallow it + || !gtk_im_context_filter_keypress(this->imc, (GdkEventKey*) event)) { + //IM did not consume the key, or we're in unimode + + if (!MOD__CTRL_ONLY(event) && this->unimode) { + /* TODO: ISO 14755 (section 3 Definitions) says that we should also + accept the first 6 characters of alphabets other than the latin + alphabet "if the Latin alphabet is not used". The below is also + reasonable (viz. hope that the user's keyboard includes latin + characters and force latin interpretation -- just as we do for our + keyboard shortcuts), but differs from the ISO 14755 + recommendation. */ + switch (group0_keyval) { + case GDK_KEY_space: + case GDK_KEY_KP_Space: { + if (this->unipos) { + insert_uni_char(this); + } + /* Stay in unimode. */ + show_curr_uni_char(this); + return TRUE; + } + + case GDK_KEY_BackSpace: { + g_return_val_if_fail(this->unipos < sizeof(this->uni), TRUE); + if (this->unipos) { + this->uni[--this->unipos] = '\0'; + } + show_curr_uni_char(this); + return TRUE; + } + + case GDK_KEY_Return: + case GDK_KEY_KP_Enter: { + if (this->unipos) { + insert_uni_char(this); + } + /* Exit unimode. */ + this->unimode = false; + this->defaultMessageContext()->clear(); + return TRUE; + } + + case GDK_KEY_Escape: { + // Cancel unimode. + this->unimode = false; + gtk_im_context_reset(this->imc); + this->defaultMessageContext()->clear(); + return TRUE; + } + + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + break; + + default: { + if (g_ascii_isxdigit(group0_keyval)) { + g_return_val_if_fail(this->unipos < sizeof(this->uni) - 1, TRUE); + this->uni[this->unipos++] = group0_keyval; + this->uni[this->unipos] = '\0'; + if (this->unipos == 8) { + /* This behaviour is partly to allow us to continue to + use a fixed-length buffer for tc->uni. Reason for + choosing the number 8 is that it's the length of + ``canonical form'' mentioned in the ISO 14755 spec. + An advantage over choosing 6 is that it allows using + backspace for typos & misremembering when entering a + 6-digit number. */ + insert_uni_char(this); + } + show_curr_uni_char(this); + return TRUE; + } else { + /* The intent is to ignore but consume characters that could be + typos for hex digits. Gtk seems to ignore & consume all + non-hex-digits, and we do similar here. Though note that some + shortcuts (like keypad +/- for zoom) get processed before + reaching this code. */ + return TRUE; + } + } + } + } + + Inkscape::Text::Layout::iterator old_start = this->text_sel_start; + Inkscape::Text::Layout::iterator old_end = this->text_sel_end; + bool cursor_moved = false; + int screenlines = 1; + if (this->text) { + double spacing = sp_te_get_average_linespacing(this->text); + Geom::Rect const d = desktop->get_display_area(); + screenlines = (int) floor(fabs(d.min()[Geom::Y] - d.max()[Geom::Y])/spacing) - 1; + if (screenlines <= 0) + screenlines = 1; + } + + /* Neither unimode nor IM consumed key; process text tool shortcuts */ + switch (group0_keyval) { + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo ("altx-text"); + return TRUE; + } + break; + case GDK_KEY_space: + if (MOD__CTRL_ONLY(event)) { + /* No-break space */ + if (!this->text) { // printable key; create text if none (i.e. if nascent_object) + sp_text_context_setup_text(this); + this->nascent_object = 0; // we don't need it anymore, having created a real <text> + } + this->text_sel_start = this->text_sel_end = sp_te_replace(this->text, this->text_sel_start, this->text_sel_end, "\302\240"); + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("No-break space")); + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT, _("Insert no-break space")); + return TRUE; + } + break; + case GDK_KEY_U: + case GDK_KEY_u: + if (MOD__CTRL_ONLY(event) || (MOD__CTRL(event) && MOD__SHIFT(event))) { + if (this->unimode) { + this->unimode = false; + this->defaultMessageContext()->clear(); + } else { + this->unimode = true; + this->unipos = 0; + this->defaultMessageContext()->set(Inkscape::NORMAL_MESSAGE, _("Unicode (<b>Enter</b> to finish): ")); + } + if (this->imc) { + gtk_im_context_reset(this->imc); + } + return TRUE; + } + break; + case GDK_KEY_B: + case GDK_KEY_b: + if (MOD__CTRL_ONLY(event) && this->text) { + SPStyle const *style = sp_te_style_at_position(this->text, std::min(this->text_sel_start, this->text_sel_end)); + SPCSSAttr *css = sp_repr_css_attr_new(); + if (style->font_weight.computed == SP_CSS_FONT_WEIGHT_NORMAL + || style->font_weight.computed == SP_CSS_FONT_WEIGHT_100 + || style->font_weight.computed == SP_CSS_FONT_WEIGHT_200 + || style->font_weight.computed == SP_CSS_FONT_WEIGHT_300 + || style->font_weight.computed == SP_CSS_FONT_WEIGHT_400) + sp_repr_css_set_property(css, "font-weight", "bold"); + else + sp_repr_css_set_property(css, "font-weight", "normal"); + sp_te_apply_style(this->text, this->text_sel_start, this->text_sel_end, css); + sp_repr_css_attr_unref(css); + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT, _("Make bold")); + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + return TRUE; + } + break; + case GDK_KEY_I: + case GDK_KEY_i: + if (MOD__CTRL_ONLY(event) && this->text) { + SPStyle const *style = sp_te_style_at_position(this->text, std::min(this->text_sel_start, this->text_sel_end)); + SPCSSAttr *css = sp_repr_css_attr_new(); + if (style->font_style.computed != SP_CSS_FONT_STYLE_NORMAL) + sp_repr_css_set_property(css, "font-style", "normal"); + else + sp_repr_css_set_property(css, "font-style", "italic"); + sp_te_apply_style(this->text, this->text_sel_start, this->text_sel_end, css); + sp_repr_css_attr_unref(css); + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT, _("Make italic")); + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + return TRUE; + } + break; + + case GDK_KEY_A: + case GDK_KEY_a: + if (MOD__CTRL_ONLY(event) && this->text) { + Inkscape::Text::Layout const *layout = te_get_layout(this->text); + if (layout) { + this->text_sel_start = layout->begin(); + this->text_sel_end = layout->end(); + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + return TRUE; + } + } + break; + + case GDK_KEY_Return: + case GDK_KEY_KP_Enter: + { + if (!this->text) { // printable key; create text if none (i.e. if nascent_object) + sp_text_context_setup_text(this); + this->nascent_object = 0; // we don't need it anymore, having created a real <text> + } + + iterator_pair enter_pair; + bool success = sp_te_delete(this->text, this->text_sel_start, this->text_sel_end, enter_pair); + (void)success; // TODO cleanup + this->text_sel_start = this->text_sel_end = enter_pair.first; + + this->text_sel_start = this->text_sel_end = sp_te_insert_line(this->text, this->text_sel_start); + + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT, _("New line")); + return TRUE; + } + case GDK_KEY_BackSpace: + if (this->text) { // if nascent_object, do nothing, but return TRUE; same for all other delete and move keys + + bool noSelection = false; + + if (MOD__CTRL(event)) { + this->text_sel_start = this->text_sel_end; + } + + if (this->text_sel_start == this->text_sel_end) { + if (MOD__CTRL(event)) { + this->text_sel_start.prevStartOfWord(); + } else { + this->text_sel_start.prevCursorPosition(); + } + noSelection = true; + } + + iterator_pair bspace_pair; + bool success = sp_te_delete(this->text, this->text_sel_start, this->text_sel_end, bspace_pair); + + if (noSelection) { + if (success) { + this->text_sel_start = this->text_sel_end = bspace_pair.first; + } else { // nothing deleted + this->text_sel_start = this->text_sel_end = bspace_pair.second; + } + } else { + if (success) { + this->text_sel_start = this->text_sel_end = bspace_pair.first; + } else { // nothing deleted + this->text_sel_start = bspace_pair.first; + this->text_sel_end = bspace_pair.second; + } + } + + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT, _("Backspace")); + } + return TRUE; + case GDK_KEY_Delete: + case GDK_KEY_KP_Delete: + if (this->text) { + bool noSelection = false; + + if (MOD__CTRL(event)) { + this->text_sel_start = this->text_sel_end; + } + + if (this->text_sel_start == this->text_sel_end) { + if (MOD__CTRL(event)) { + this->text_sel_end.nextEndOfWord(); + } else { + this->text_sel_end.nextCursorPosition(); + } + noSelection = true; + } + + iterator_pair del_pair; + bool success = sp_te_delete(this->text, this->text_sel_start, this->text_sel_end, del_pair); + + if (noSelection) { + this->text_sel_start = this->text_sel_end = del_pair.first; + } else { + if (success) { + this->text_sel_start = this->text_sel_end = del_pair.first; + } else { // nothing deleted + this->text_sel_start = del_pair.first; + this->text_sel_end = del_pair.second; + } + } + + + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT, _("Delete")); + } + return TRUE; + case GDK_KEY_Left: + case GDK_KEY_KP_Left: + case GDK_KEY_KP_4: + if (this->text) { + if (MOD__ALT(event)) { + gint mul = 1 + gobble_key_events( + get_group0_keyval(&event->key), 0); // with any mask + if (MOD__SHIFT(event)) + sp_te_adjust_kerning_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, Geom::Point(mul*-10, 0)); + else + sp_te_adjust_kerning_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, Geom::Point(mul*-1, 0)); + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + DocumentUndo::maybeDone(sp_desktop_document(desktop), "kern:left", SP_VERB_CONTEXT_TEXT, _("Kern to the left")); + } else { + if (MOD__CTRL(event)) + this->text_sel_end.cursorLeftWithControl(); + else + this->text_sel_end.cursorLeft(); + cursor_moved = true; + break; + } + } + return TRUE; + case GDK_KEY_Right: + case GDK_KEY_KP_Right: + case GDK_KEY_KP_6: + if (this->text) { + if (MOD__ALT(event)) { + gint mul = 1 + gobble_key_events( + get_group0_keyval(&event->key), 0); // with any mask + if (MOD__SHIFT(event)) + sp_te_adjust_kerning_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, Geom::Point(mul*10, 0)); + else + sp_te_adjust_kerning_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, Geom::Point(mul*1, 0)); + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + DocumentUndo::maybeDone(sp_desktop_document(desktop), "kern:right", SP_VERB_CONTEXT_TEXT, _("Kern to the right")); + } else { + if (MOD__CTRL(event)) + this->text_sel_end.cursorRightWithControl(); + else + this->text_sel_end.cursorRight(); + cursor_moved = true; + break; + } + } + return TRUE; + case GDK_KEY_Up: + case GDK_KEY_KP_Up: + case GDK_KEY_KP_8: + if (this->text) { + if (MOD__ALT(event)) { + gint mul = 1 + gobble_key_events( + get_group0_keyval(&event->key), 0); // with any mask + if (MOD__SHIFT(event)) + sp_te_adjust_kerning_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, Geom::Point(0, mul*-10)); + else + sp_te_adjust_kerning_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, Geom::Point(0, mul*-1)); + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + DocumentUndo::maybeDone(sp_desktop_document(desktop), "kern:up", SP_VERB_CONTEXT_TEXT, _("Kern up")); + } else { + if (MOD__CTRL(event)) + this->text_sel_end.cursorUpWithControl(); + else + this->text_sel_end.cursorUp(); + cursor_moved = true; + break; + } + } + return TRUE; + case GDK_KEY_Down: + case GDK_KEY_KP_Down: + case GDK_KEY_KP_2: + if (this->text) { + if (MOD__ALT(event)) { + gint mul = 1 + gobble_key_events( + get_group0_keyval(&event->key), 0); // with any mask + if (MOD__SHIFT(event)) + sp_te_adjust_kerning_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, Geom::Point(0, mul*10)); + else + sp_te_adjust_kerning_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, Geom::Point(0, mul*1)); + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + DocumentUndo::maybeDone(sp_desktop_document(desktop), "kern:down", SP_VERB_CONTEXT_TEXT, _("Kern down")); + } else { + if (MOD__CTRL(event)) + this->text_sel_end.cursorDownWithControl(); + else + this->text_sel_end.cursorDown(); + cursor_moved = true; + break; + } + } + return TRUE; + case GDK_KEY_Home: + case GDK_KEY_KP_Home: + if (this->text) { + if (MOD__CTRL(event)) + this->text_sel_end.thisStartOfShape(); + else + this->text_sel_end.thisStartOfLine(); + cursor_moved = true; + break; + } + return TRUE; + case GDK_KEY_End: + case GDK_KEY_KP_End: + if (this->text) { + if (MOD__CTRL(event)) + this->text_sel_end.nextStartOfShape(); + else + this->text_sel_end.thisEndOfLine(); + cursor_moved = true; + break; + } + return TRUE; + case GDK_KEY_Page_Down: + case GDK_KEY_KP_Page_Down: + if (this->text) { + this->text_sel_end.cursorDown(screenlines); + cursor_moved = true; + break; + } + return TRUE; + case GDK_KEY_Page_Up: + case GDK_KEY_KP_Page_Up: + if (this->text) { + this->text_sel_end.cursorUp(screenlines); + cursor_moved = true; + break; + } + return TRUE; + case GDK_KEY_Escape: + if (this->creating) { + this->creating = 0; + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed, GDK_CURRENT_TIME); + this->grabbed = NULL; + } + Inkscape::Rubberband::get(desktop)->stop(); + } else { + sp_desktop_selection(desktop)->clear(); + } + this->nascent_object = FALSE; + return TRUE; + case GDK_KEY_bracketleft: + if (this->text) { + if (MOD__ALT(event) || MOD__CTRL(event)) { + if (MOD__ALT(event)) { + if (MOD__SHIFT(event)) { + // FIXME: alt+shift+[] does not work, don't know why + sp_te_adjust_rotation_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, -10); + } else { + sp_te_adjust_rotation_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, -1); + } + } else { + sp_te_adjust_rotation(this->text, this->text_sel_start, this->text_sel_end, desktop, -90); + } + DocumentUndo::maybeDone(sp_desktop_document(desktop), "textrot:ccw", SP_VERB_CONTEXT_TEXT, _("Rotate counterclockwise")); + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + return TRUE; + } + } + break; + case GDK_KEY_bracketright: + if (this->text) { + if (MOD__ALT(event) || MOD__CTRL(event)) { + if (MOD__ALT(event)) { + if (MOD__SHIFT(event)) { + // FIXME: alt+shift+[] does not work, don't know why + sp_te_adjust_rotation_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, 10); + } else { + sp_te_adjust_rotation_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, 1); + } + } else { + sp_te_adjust_rotation(this->text, this->text_sel_start, this->text_sel_end, desktop, 90); + } + DocumentUndo::maybeDone(sp_desktop_document(desktop), "textrot:cw", SP_VERB_CONTEXT_TEXT, _("Rotate clockwise")); + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + return TRUE; + } + } + break; + case GDK_KEY_less: + case GDK_KEY_comma: + if (this->text) { + if (MOD__ALT(event)) { + if (MOD__CTRL(event)) { + if (MOD__SHIFT(event)) + sp_te_adjust_linespacing_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, -10); + else + sp_te_adjust_linespacing_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, -1); + DocumentUndo::maybeDone(sp_desktop_document(desktop), "linespacing:dec", SP_VERB_CONTEXT_TEXT, _("Contract line spacing")); + } else { + if (MOD__SHIFT(event)) + sp_te_adjust_tspan_letterspacing_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, -10); + else + sp_te_adjust_tspan_letterspacing_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, -1); + DocumentUndo::maybeDone(sp_desktop_document(desktop), "letterspacing:dec", SP_VERB_CONTEXT_TEXT, _("Contract letter spacing")); + } + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + return TRUE; + } + } + break; + case GDK_KEY_greater: + case GDK_KEY_period: + if (this->text) { + if (MOD__ALT(event)) { + if (MOD__CTRL(event)) { + if (MOD__SHIFT(event)) + sp_te_adjust_linespacing_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, 10); + else + sp_te_adjust_linespacing_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, 1); + DocumentUndo::maybeDone(sp_desktop_document(desktop), "linespacing:inc", SP_VERB_CONTEXT_TEXT, _("Expand line spacing")); + } else { + if (MOD__SHIFT(event)) + sp_te_adjust_tspan_letterspacing_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, 10); + else + sp_te_adjust_tspan_letterspacing_screen(this->text, this->text_sel_start, this->text_sel_end, desktop, 1); + DocumentUndo::maybeDone(sp_desktop_document(desktop), "letterspacing:inc", SP_VERB_CONTEXT_TEXT, _("Expand letter spacing"));\ + } + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + return TRUE; + } + } + break; + default: + break; + } + + if (cursor_moved) { + if (!MOD__SHIFT(event)) + this->text_sel_start = this->text_sel_end; + if (old_start != this->text_sel_start || old_end != this->text_sel_end) { + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + } + return TRUE; + } + + } else return TRUE; // return the "I took care of it" value if it was consumed by the IM + } else { // do nothing if there's no object to type in - the key will be sent to parent context, + // except up/down that are swallowed to prevent the zoom field from activation + if ((group0_keyval == GDK_KEY_Up || + group0_keyval == GDK_KEY_Down || + group0_keyval == GDK_KEY_KP_Up || + group0_keyval == GDK_KEY_KP_Down ) + && !MOD__CTRL_ONLY(event)) { + return TRUE; + } else if (group0_keyval == GDK_KEY_Escape) { // cancel rubberband + if (this->creating) { + this->creating = 0; + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed, GDK_CURRENT_TIME); + this->grabbed = NULL; + } + Inkscape::Rubberband::get(desktop)->stop(); + } + } else if ((group0_keyval == GDK_KEY_x || group0_keyval == GDK_KEY_X) && MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo ("altx-text"); + return TRUE; + } + } + break; + } + + case GDK_KEY_RELEASE: + if (!this->unimode && this->imc && gtk_im_context_filter_keypress(this->imc, (GdkEventKey*) event)) { + return TRUE; + } + break; + default: + break; + } + + // if nobody consumed it so far +// if ((SP_EVENT_CONTEXT_CLASS(sp_text_context_parent_class))->root_handler) { // and there's a handler in parent context, +// return (SP_EVENT_CONTEXT_CLASS(sp_text_context_parent_class))->root_handler(event_context, event); // send event to parent +// } else { +// return FALSE; // return "I did nothing" value so that global shortcuts can be activated +// } + return ToolBase::root_handler(event); + +} + +/** + Attempts to paste system clipboard into the currently edited text, returns true on success + */ +bool sp_text_paste_inline(ToolBase *ec) +{ + if (!SP_IS_TEXT_CONTEXT(ec)) + return false; + + TextTool *tc = SP_TEXT_CONTEXT(ec); + + if ((tc->text) || (tc->nascent_object)) { + // there is an active text object in this context, or a new object was just created + + Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get(); + Glib::ustring const clip_text = refClipboard->wait_for_text(); + + if (!clip_text.empty()) { + // Fix for 244940 + // The XML standard defines the following as valid characters + // (Extensible Markup Language (XML) 1.0 (Fourth Edition) paragraph 2.2) + // char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] + // Since what comes in off the paste buffer will go right into XML, clean + // the text here. + Glib::ustring text(clip_text); + Glib::ustring::iterator itr = text.begin(); + gunichar paste_string_uchar; + + while(itr != text.end()) + { + paste_string_uchar = *itr; + + // Make sure we don't have a control character. We should really check + // for the whole range above... Add the rest of the invalid cases from + // above if we find additional issues + if(paste_string_uchar >= 0x00000020 || + paste_string_uchar == 0x00000009 || + paste_string_uchar == 0x0000000A || + paste_string_uchar == 0x0000000D) { + ++itr; + } else { + itr = text.erase(itr); + } + } + + if (!tc->text) { // create text if none (i.e. if nascent_object) + sp_text_context_setup_text(tc); + tc->nascent_object = 0; // we don't need it anymore, having created a real <text> + } + + // using indices is slow in ustrings. Whatever. + Glib::ustring::size_type begin = 0; + for ( ; ; ) { + Glib::ustring::size_type end = text.find('\n', begin); + if (end == Glib::ustring::npos) { + if (begin != text.length()) + tc->text_sel_start = tc->text_sel_end = sp_te_replace(tc->text, tc->text_sel_start, tc->text_sel_end, text.substr(begin).c_str()); + break; + } + tc->text_sel_start = tc->text_sel_end = sp_te_replace(tc->text, tc->text_sel_start, tc->text_sel_end, text.substr(begin, end - begin).c_str()); + tc->text_sel_start = tc->text_sel_end = sp_te_insert_line(tc->text, tc->text_sel_start); + begin = end + 1; + } + DocumentUndo::done(sp_desktop_document(ec->desktop), SP_VERB_CONTEXT_TEXT, + _("Paste text")); + + return true; + } + } // FIXME: else create and select a new object under cursor! + + return false; +} + +/** + Gets the raw characters that comprise the currently selected text, converting line + breaks into lf characters. +*/ +Glib::ustring sp_text_get_selected_text(ToolBase const *ec) +{ + if (!SP_IS_TEXT_CONTEXT(ec)) + return ""; + TextTool const *tc = SP_TEXT_CONTEXT(ec); + if (tc->text == NULL) + return ""; + + return sp_te_get_string_multiline(tc->text, tc->text_sel_start, tc->text_sel_end); +} + +SPCSSAttr *sp_text_get_style_at_cursor(ToolBase const *ec) +{ + if (!SP_IS_TEXT_CONTEXT(ec)) + return NULL; + TextTool const *tc = SP_TEXT_CONTEXT(ec); + if (tc->text == NULL) + return NULL; + + SPObject const *obj = sp_te_object_at_position(tc->text, tc->text_sel_end); + + if (obj) { + return take_style_from_item(const_cast<SPObject*>(obj)); + } + + return NULL; +} + +/** + Deletes the currently selected characters. Returns false if there is no + text selection currently. +*/ +bool sp_text_delete_selection(ToolBase *ec) +{ + if (!SP_IS_TEXT_CONTEXT(ec)) + return false; + TextTool *tc = SP_TEXT_CONTEXT(ec); + if (tc->text == NULL) + return false; + + if (tc->text_sel_start == tc->text_sel_end) + return false; + + iterator_pair pair; + bool success = sp_te_delete(tc->text, tc->text_sel_start, tc->text_sel_end, pair); + + + if (success) { + tc->text_sel_start = tc->text_sel_end = pair.first; + } else { // nothing deleted + tc->text_sel_start = pair.first; + tc->text_sel_end = pair.second; + } + + sp_text_context_update_cursor(tc); + sp_text_context_update_text_selection(tc); + + return true; +} + +/** + * \param selection Should not be NULL. + */ +void TextTool::_selectionChanged(Inkscape::Selection *selection) +{ + g_assert(selection != NULL); + + ToolBase *ec = SP_EVENT_CONTEXT(this); + + ec->shape_editor->unset_item(SH_KNOTHOLDER); + SPItem *item = selection->singleItem(); + if (item && SP_IS_FLOWTEXT(item) && SP_FLOWTEXT(item)->has_internal_frame()) { + ec->shape_editor->set_item(item, SH_KNOTHOLDER); + } + + if (this->text && (item != this->text)) { + sp_text_context_forget_text(this); + } + this->text = NULL; + + if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item)) { + this->text = item; + Inkscape::Text::Layout const *layout = te_get_layout(this->text); + if (layout) + this->text_sel_start = this->text_sel_end = layout->end(); + } else { + this->text = NULL; + } + + // we update cursor without scrolling, because this position may not be final; + // item_handler moves cusros to the point of click immediately + sp_text_context_update_cursor(this, false); + sp_text_context_update_text_selection(this); +} + +void TextTool::_selectionModified(Inkscape::Selection */*selection*/, guint /*flags*/) +{ + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); +} + +bool TextTool::_styleSet(SPCSSAttr const *css) +{ + if (this->text == NULL) + return false; + if (this->text_sel_start == this->text_sel_end) + return false; // will get picked up by the parent and applied to the whole text object + + sp_te_apply_style(this->text, this->text_sel_start, this->text_sel_end, css); + DocumentUndo::done(sp_desktop_document(this->desktop), SP_VERB_CONTEXT_TEXT, + _("Set text style")); + sp_text_context_update_cursor(this); + sp_text_context_update_text_selection(this); + + return true; +} + +int TextTool::_styleQueried(SPStyle *style, int property) +{ + if (this->text == NULL) { + return QUERY_STYLE_NOTHING; + } + const Inkscape::Text::Layout *layout = te_get_layout(this->text); + if (layout == NULL) { + return QUERY_STYLE_NOTHING; + } + sp_text_context_validate_cursor_iterators(this); + + GSList *styles_list = NULL; + + Inkscape::Text::Layout::iterator begin_it, end_it; + if (this->text_sel_start < this->text_sel_end) { + begin_it = this->text_sel_start; + end_it = this->text_sel_end; + } else { + begin_it = this->text_sel_end; + end_it = this->text_sel_start; + } + if (begin_it == end_it) { + if (!begin_it.prevCharacter()) { + end_it.nextCharacter(); + } + } + for (Inkscape::Text::Layout::iterator it = begin_it ; it < end_it ; it.nextStartOfSpan()) { + SPObject const *pos_obj = 0; + void *rawptr = 0; + layout->getSourceOfCharacter(it, &rawptr); + if (!rawptr || !SP_IS_OBJECT(rawptr)) { + continue; + } + pos_obj = SP_OBJECT(rawptr); + while (SP_IS_STRING(pos_obj) && pos_obj->parent) { + pos_obj = pos_obj->parent; // SPStrings don't have style + } + styles_list = g_slist_prepend(styles_list, (gpointer)pos_obj); + } + + int result = sp_desktop_query_style_from_list (styles_list, style, property); + + g_slist_free(styles_list); + return result; +} + +static void sp_text_context_validate_cursor_iterators(TextTool *tc) +{ + if (tc->text == NULL) + return; + Inkscape::Text::Layout const *layout = te_get_layout(tc->text); + if (layout) { // undo can change the text length without us knowing it + layout->validateIterator(&tc->text_sel_start); + layout->validateIterator(&tc->text_sel_end); + } +} + +static void sp_text_context_update_cursor(TextTool *tc, bool scroll_to_see) +{ + // due to interruptible display, tc may already be destroyed during a display update before + // the cursor update (can't do both atomically, alas) + if (!tc->desktop) return; + + if (tc->text) { + Geom::Point p0, p1; + sp_te_get_cursor_coords(tc->text, tc->text_sel_end, p0, p1); + Geom::Point const d0 = p0 * tc->text->i2dt_affine(); + Geom::Point const d1 = p1 * tc->text->i2dt_affine(); + + // scroll to show cursor + if (scroll_to_see) { + Geom::Point const center = SP_EVENT_CONTEXT(tc)->desktop->get_display_area().midpoint(); + if (Geom::L2(d0 - center) > Geom::L2(d1 - center)) + // unlike mouse moves, here we must scroll all the way at first shot, so we override the autoscrollspeed + SP_EVENT_CONTEXT(tc)->desktop->scroll_to_point(d0, 1.0); + else + SP_EVENT_CONTEXT(tc)->desktop->scroll_to_point(d1, 1.0); + } + + sp_canvas_item_show(tc->cursor); + tc->cursor->setCoords(d0, d1); + + /* fixme: ... need another transformation to get canvas widget coordinate space? */ + if (tc->imc) { + GdkRectangle im_cursor = { 0, 0, 1, 1 }; + Geom::Point const top_left = SP_EVENT_CONTEXT(tc)->desktop->get_display_area().corner(3); + Geom::Point const im_d0 = SP_EVENT_CONTEXT(tc)->desktop->d2w(d0 - top_left); + Geom::Point const im_d1 = SP_EVENT_CONTEXT(tc)->desktop->d2w(d1 - top_left); + im_cursor.x = (int) floor(im_d0[Geom::X]); + im_cursor.y = (int) floor(im_d1[Geom::Y]); + im_cursor.width = (int) floor(im_d1[Geom::X]) - im_cursor.x; + im_cursor.height = (int) floor(im_d0[Geom::Y]) - im_cursor.y; + gtk_im_context_set_cursor_location(tc->imc, &im_cursor); + } + + tc->show = TRUE; + tc->phase = 1; + + Inkscape::Text::Layout const *layout = te_get_layout(tc->text); + int const nChars = layout->iteratorToCharIndex(layout->end()); + char const *trunc = ""; + bool truncated = false; + if (layout->inputTruncated()) { + truncated = true; + trunc = _(" [truncated]"); + } + if (SP_IS_FLOWTEXT(tc->text)) { + SPItem *frame = SP_FLOWTEXT(tc->text)->get_frame (NULL); // first frame only + if (frame) { + if (truncated) { + SP_CTRLRECT(tc->frame)->setColor(0xff0000ff, false, 0); + } else { + SP_CTRLRECT(tc->frame)->setColor(0x0000ff7f, false, 0); + } + sp_canvas_item_show(tc->frame); + Geom::OptRect frame_bbox = frame->desktopVisualBounds(); + if (frame_bbox) { + SP_CTRLRECT(tc->frame)->setRectangle(*frame_bbox); + } + } + + SP_EVENT_CONTEXT(tc)->message_context->setF(Inkscape::NORMAL_MESSAGE, ngettext("Type or edit flowed text (%d character%s); <b>Enter</b> to start new paragraph.", "Type or edit flowed text (%d characters%s); <b>Enter</b> to start new paragraph.", nChars), nChars, trunc); + } else { + SP_EVENT_CONTEXT(tc)->message_context->setF(Inkscape::NORMAL_MESSAGE, ngettext("Type or edit text (%d character%s); <b>Enter</b> to start new line.", "Type or edit text (%d characters%s); <b>Enter</b> to start new line.", nChars), nChars, trunc); + } + + } else { + sp_canvas_item_hide(tc->cursor); + sp_canvas_item_hide(tc->frame); + tc->show = FALSE; + if (!tc->nascent_object) { + SP_EVENT_CONTEXT(tc)->message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Click</b> to select or create text, <b>drag</b> to create flowed text; then type.")); // FIXME: this is a copy of string from tools-switch, do not desync + } + } + + SP_EVENT_CONTEXT(tc)->desktop->emitToolSubselectionChanged((gpointer)tc); +} + +static void sp_text_context_update_text_selection(TextTool *tc) +{ + // due to interruptible display, tc may already be destroyed during a display update before + // the selection update (can't do both atomically, alas) + if (!tc->desktop) return; + + for (std::vector<SPCanvasItem*>::iterator it = tc->text_selection_quads.begin() ; it != tc->text_selection_quads.end() ; ++it) { + sp_canvas_item_hide(*it); + sp_canvas_item_destroy(*it); + } + tc->text_selection_quads.clear(); + + std::vector<Geom::Point> quads; + if (tc->text != NULL) + quads = sp_te_create_selection_quads(tc->text, tc->text_sel_start, tc->text_sel_end, (tc->text)->i2dt_affine()); + for (unsigned i = 0 ; i < quads.size() ; i += 4) { + SPCanvasItem *quad_canvasitem; + quad_canvasitem = sp_canvas_item_new(sp_desktop_controls(tc->desktop), SP_TYPE_CTRLQUADR, NULL); + // FIXME: make the color settable in prefs + // for now, use semitrasparent blue, as cairo cannot do inversion :( + sp_ctrlquadr_set_rgba32(SP_CTRLQUADR(quad_canvasitem), 0x00777777); + sp_ctrlquadr_set_coords(SP_CTRLQUADR(quad_canvasitem), quads[i], quads[i+1], quads[i+2], quads[i+3]); + sp_canvas_item_show(quad_canvasitem); + tc->text_selection_quads.push_back(quad_canvasitem); + } +} + +static gint sp_text_context_timeout(TextTool *tc) +{ + if (tc->show) { + sp_canvas_item_show(tc->cursor); + if (tc->phase) { + tc->phase = 0; + tc->cursor->setRgba32(0x000000ff); + } else { + tc->phase = 1; + tc->cursor->setRgba32(0xffffffff); + } + } + + return TRUE; +} + +static void sp_text_context_forget_text(TextTool *tc) +{ + if (! tc->text) return; + SPItem *ti = tc->text; + (void)ti; + /* We have to set it to zero, + * or selection changed signal messes everything up */ + tc->text = NULL; + +/* FIXME: this automatic deletion when nothing is inputted crashes the XML edittor and also crashes when duplicating an empty flowtext. + So don't create an empty flowtext in the first place? Create it when first character is typed. + */ +/* + if ((SP_IS_TEXT(ti) || SP_IS_FLOWTEXT(ti)) && sp_te_input_is_empty(ti)) { + Inkscape::XML::Node *text_repr = ti->getRepr(); + // the repr may already have been unparented + // if we were called e.g. as the result of + // an undo or the element being removed from + // the XML editor + if ( text_repr && text_repr->parent() ) { + sp_repr_unparent(text_repr); + SPDocumentUndo::done(sp_desktop_document(tc->desktop), SP_VERB_CONTEXT_TEXT, + _("Remove empty text")); + } + } +*/ +} + +gint sptc_focus_in(GtkWidget */*widget*/, GdkEventFocus */*event*/, TextTool *tc) +{ + gtk_im_context_focus_in(tc->imc); + return FALSE; +} + +gint sptc_focus_out(GtkWidget */*widget*/, GdkEventFocus */*event*/, TextTool *tc) +{ + gtk_im_context_focus_out(tc->imc); + return FALSE; +} + +static void sptc_commit(GtkIMContext */*imc*/, gchar *string, TextTool *tc) +{ + if (!tc->text) { + sp_text_context_setup_text(tc); + tc->nascent_object = 0; // we don't need it anymore, having created a real <text> + } + + tc->text_sel_start = tc->text_sel_end = sp_te_replace(tc->text, tc->text_sel_start, tc->text_sel_end, string); + sp_text_context_update_cursor(tc); + sp_text_context_update_text_selection(tc); + + DocumentUndo::done(tc->text->document, SP_VERB_CONTEXT_TEXT, + _("Type text")); +} + +void sp_text_context_place_cursor (TextTool *tc, SPObject *text, Inkscape::Text::Layout::iterator where) +{ + tc->desktop->selection->set (text); + tc->text_sel_start = tc->text_sel_end = where; + sp_text_context_update_cursor(tc); + sp_text_context_update_text_selection(tc); +} + +void sp_text_context_place_cursor_at (TextTool *tc, SPObject *text, Geom::Point const p) +{ + tc->desktop->selection->set (text); + sp_text_context_place_cursor (tc, text, sp_te_get_position_by_coords(tc->text, p)); +} + +Inkscape::Text::Layout::iterator *sp_text_context_get_cursor_position(TextTool *tc, SPObject *text) +{ + if (text != tc->text) + return NULL; + return &(tc->text_sel_end); +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/text-tool.h b/src/ui/tools/text-tool.h new file mode 100644 index 000000000..ca2b3d19a --- /dev/null +++ b/src/ui/tools/text-tool.h @@ -0,0 +1,107 @@ +#ifndef __SP_TEXT_CONTEXT_H__ +#define __SP_TEXT_CONTEXT_H__ + +/* + * TextTool + * + * Authors: + * Lauris Kaplinski <lauris@kaplinski.com> + * bulia byak <buliabyak@users.sf.net> + * + * Copyright (C) 1999-2005 authors + * Copyright (C) 2001 Ximian, Inc. + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +/* #include <gdk/gdkic.h> */ +#include <stddef.h> +#include <sigc++/sigc++.h> +#include <gtk/gtk.h> + +#include "ui/tools/tool-base.h" +#include <2geom/point.h> +#include "libnrtype/Layout-TNG.h" + +#define SP_TEXT_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::TextTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_TEXT_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::TextTool*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +struct SPCtrlLine; + +namespace Inkscape { +namespace UI { +namespace Tools { + +class TextTool : public ToolBase { +public: + TextTool(); + virtual ~TextTool(); + + sigc::connection sel_changed_connection; + sigc::connection sel_modified_connection; + sigc::connection style_set_connection; + sigc::connection style_query_connection; + + GtkIMContext *imc; + + SPItem *text; // the text we're editing, or NULL if none selected + + /* Text item position in root coordinates */ + Geom::Point pdoc; + /* Insertion point position */ + Inkscape::Text::Layout::iterator text_sel_start; + Inkscape::Text::Layout::iterator text_sel_end; + + gchar uni[9]; + bool unimode; + guint unipos; + + SPCtrlLine *cursor; + SPCanvasItem *indicator; + SPCanvasItem *frame; // hiliting the first frame of flowtext; FIXME: make this a list to accommodate arbitrarily many chained shapes + std::vector<SPCanvasItem*> text_selection_quads; + gint timeout; + bool show; + bool phase; + bool nascent_object; // true if we're clicked on canvas to put cursor, but no text typed yet so ->text is still NULL + + bool over_text; // true if cursor is over a text object + + guint dragging : 2; // dragging selection over text + + bool creating; // dragging rubberband to create flowtext + SPCanvasItem *grabbed; // we grab while we are creating, to get events even if the mouse goes out of the window + Geom::Point p0; // initial point if the flowtext rect + + /* Preedit String */ + gchar* preedit_string; + + static const std::string prefsPath; + + virtual void setup(); + virtual void finish(); + virtual bool root_handler(GdkEvent* event); + virtual bool item_handler(SPItem* item, GdkEvent* event); + + virtual const std::string& getPrefsPath(); + +private: + void _selectionChanged(Inkscape::Selection *selection); + void _selectionModified(Inkscape::Selection *selection, guint flags); + bool _styleSet(SPCSSAttr const *css); + int _styleQueried(SPStyle *style, int property); +}; + +bool sp_text_paste_inline(ToolBase *ec); +Glib::ustring sp_text_get_selected_text(ToolBase const *ec); +SPCSSAttr *sp_text_get_style_at_cursor(ToolBase const *ec); +bool sp_text_delete_selection(ToolBase *ec); +void sp_text_context_place_cursor (TextTool *tc, SPObject *text, Inkscape::Text::Layout::iterator where); +void sp_text_context_place_cursor_at (TextTool *tc, SPObject *text, Geom::Point const p); +Inkscape::Text::Layout::iterator *sp_text_context_get_cursor_position(TextTool *tc, SPObject *text); + +} +} +} + +#endif diff --git a/src/ui/tools/tool-base.cpp b/src/ui/tools/tool-base.cpp new file mode 100644 index 000000000..752053be1 --- /dev/null +++ b/src/ui/tools/tool-base.cpp @@ -0,0 +1,1450 @@ +/* + * Main event handling, and related helper functions. + * + * Authors: + * Lauris Kaplinski <lauris@kaplinski.com> + * Frank Felfe <innerspace@iname.com> + * bulia byak <buliabyak@users.sf.net> + * Jon A. Cruz <jon@joncruz.org> + * Kris De Gussem <Kris.DeGussem@gmail.com> + * + * Copyright (C) 1999-2012 authors + * Copyright (C) 2001-2002 Ximian, Inc. + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + +#include "shortcuts.h" +#include "file.h" +#include "ui/tools/tool-base.h" + +#include <string.h> +#include <gdk/gdkkeysyms.h> +#include <gtk/gtk.h> +#include <glibmm/i18n.h> +#include <cstring> +#include <string> + +#include "display/sp-canvas.h" +#include "xml/node-event-vector.h" +#include "sp-cursor.h" +#include "desktop.h" +#include "desktop-handles.h" +#include "desktop-events.h" +#include "desktop-style.h" +#include "widgets/desktop-widget.h" +#include "sp-namedview.h" +#include "selection.h" +#include "interface.h" +#include "macros.h" +#include "tools-switch.h" +#include "preferences.h" +#include "message-context.h" +#include "gradient-drag.h" +#include "attributes.h" +#include "rubberband.h" +#include "selcue.h" +#include "ui/tools/lpe-tool.h" +#include "ui/tool/control-point.h" +#include "shape-editor.h" +#include "sp-guide.h" +#include "color.h" + +// globals for temporary switching to selector by space +static bool selector_toggled = FALSE; +static int switch_selector_to = 0; + +// globals for temporary switching to dropper by 'D' +static bool dropper_toggled = FALSE; +static int switch_dropper_to = 0; + +// globals for keeping track of keyboard scroll events in order to accelerate +static guint32 scroll_event_time = 0; +static gdouble scroll_multiply = 1; +static guint scroll_keyval = 0; + + +namespace Inkscape { +namespace UI { +namespace Tools { + +static void set_event_location(SPDesktop * desktop, GdkEvent * event); + + +void ToolBase::set(const Inkscape::Preferences::Entry& /*val*/) { +} + +void ToolBase::finish() { + this->enableSelectionCue(false); +} + +SPDesktop const& ToolBase::getDesktop() const { + return *desktop; +} + +ToolBase::ToolBase(gchar const *const *cursor_shape, gint hot_x, gint hot_y, bool uses_snap) + : pref_observer(NULL) + , cursor(NULL) + , xp(0) + , yp(0) + , tolerance(0) + , within_tolerance(false) + , item_to_select(NULL) + , message_context(NULL) + , _selcue(NULL) + , _grdrag(NULL) + , shape_editor(NULL) + , space_panning(false) + , _delayed_snap_event(NULL) + , _dse_callback_in_process(false) + , desktop(NULL) + , _uses_snap(uses_snap) + , cursor_shape(cursor_shape) + , hot_x(hot_x) + , hot_y(hot_y) +{ +} + +ToolBase::~ToolBase() { + if (this->message_context) { + delete this->message_context; + } + + if (this->cursor != NULL) { +#if GTK_CHECK_VERSION(3,0,0) + g_object_unref(this->cursor); +#else + gdk_cursor_unref(this->cursor); +#endif + this->cursor = NULL; + } + + if (this->desktop) { + this->desktop = NULL; + } + + if (this->pref_observer) { + delete this->pref_observer; + } + + if (this->_delayed_snap_event) { + delete this->_delayed_snap_event; + } +} + + +/** + * Set the cursor to a standard GDK cursor + */ +void ToolBase::sp_event_context_set_cursor(GdkCursorType cursor_type) { + + GtkWidget *w = GTK_WIDGET(sp_desktop_canvas(this->desktop)); + GdkDisplay *display = gdk_display_get_default(); + GdkCursor *cursor = gdk_cursor_new_for_display(display, cursor_type); + +#if WITH_GTKMM_3_0 + if (cursor) { + gdk_window_set_cursor (gtk_widget_get_window (w), cursor); + g_object_unref (cursor); + } +#else + gdk_window_set_cursor (gtk_widget_get_window (w), cursor); + gdk_cursor_unref (cursor); +#endif + +} + +/** + * Recreates and draws cursor on desktop related to ToolBase. + */ +void ToolBase::sp_event_context_update_cursor() { + GtkWidget *w = GTK_WIDGET(sp_desktop_canvas(this->desktop)); + if (gtk_widget_get_window (w)) { + + GtkStyle *style = gtk_widget_get_style(w); + + /* fixme: */ + if (this->cursor_shape) { + GdkDisplay *display = gdk_display_get_default(); + if (gdk_display_supports_cursor_alpha(display) && gdk_display_supports_cursor_color(display)) { + bool fillHasColor=false, strokeHasColor=false; + guint32 fillColor = sp_desktop_get_color_tool(this->desktop, this->getPrefsPath(), true, &fillHasColor); + guint32 strokeColor = sp_desktop_get_color_tool(this->desktop, this->getPrefsPath(), false, &strokeHasColor); + double fillOpacity = fillHasColor ? sp_desktop_get_opacity_tool(this->desktop, this->getPrefsPath(), true) : 0; + double strokeOpacity = strokeHasColor ? sp_desktop_get_opacity_tool(this->desktop, this->getPrefsPath(), false) : 0; + + GdkPixbuf *pixbuf = sp_cursor_pixbuf_from_xpm( + this->cursor_shape, + style->black, style->white, + SP_RGBA32_U_COMPOSE(SP_RGBA32_R_U(fillColor),SP_RGBA32_G_U(fillColor),SP_RGBA32_B_U(fillColor),SP_COLOR_F_TO_U(fillOpacity)), + SP_RGBA32_U_COMPOSE(SP_RGBA32_R_U(strokeColor),SP_RGBA32_G_U(strokeColor),SP_RGBA32_B_U(strokeColor),SP_COLOR_F_TO_U(strokeOpacity)) + ); + if (pixbuf != NULL) { + if (this->cursor) { +#if GTK_CHECK_VERSION(3,0,0) + g_object_unref(this->cursor); +#else + gdk_cursor_unref(this->cursor); +#endif + } + this->cursor = gdk_cursor_new_from_pixbuf(display, pixbuf, this->hot_x, this->hot_y); + g_object_unref(pixbuf); + } + } else { + GdkPixbuf *pixbuf = gdk_pixbuf_new_from_xpm_data((const gchar **)this->cursor_shape); + + if (pixbuf) { + if (this->cursor) { +#if GTK_CHECK_VERSION(3,0,0) + g_object_unref(this->cursor); +#else + gdk_cursor_unref(this->cursor); +#endif + } + this->cursor = gdk_cursor_new_from_pixbuf(display, + pixbuf, this->hot_x, this->hot_y); + g_object_unref(pixbuf); + } + } + } + gdk_window_set_cursor(gtk_widget_get_window (w), this->cursor); + gdk_flush(); + } + this->desktop->waiting_cursor = false; +} + +/** + * Callback that gets called on initialization of ToolBase object. + * Redraws mouse cursor, at the moment. + * + * When you override it, call this method first. + */ +void ToolBase::setup() { + this->pref_observer = new ToolPrefObserver(this->getPrefsPath(), this); + Inkscape::Preferences::get()->addObserver(*(this->pref_observer)); + + this->sp_event_context_update_cursor(); +} + +/** + * Gobbles next key events on the queue with the same keyval and mask. Returns the number of events consumed. + */ +gint gobble_key_events(guint keyval, gint mask) { + GdkEvent *event_next; + gint i = 0; + + event_next = gdk_event_get(); + // while the next event is also a key notify with the same keyval and mask, + while (event_next && (event_next->type == GDK_KEY_PRESS || event_next->type + == GDK_KEY_RELEASE) && event_next->key.keyval == keyval && (!mask + || (event_next->key.state & mask))) { + if (event_next->type == GDK_KEY_PRESS) + i++; + // kill it + gdk_event_free(event_next); + // get next + event_next = gdk_event_get(); + } + // otherwise, put it back onto the queue + if (event_next) + gdk_event_put(event_next); + + return i; +} + +/** + * Gobbles next motion notify events on the queue with the same mask. Returns the number of events consumed. + */ +gint gobble_motion_events(gint mask) { + GdkEvent *event_next; + gint i = 0; + + event_next = gdk_event_get(); + // while the next event is also a key notify with the same keyval and mask, + while (event_next && event_next->type == GDK_MOTION_NOTIFY + && (event_next->motion.state & mask)) { + // kill it + gdk_event_free(event_next); + // get next + event_next = gdk_event_get(); + i++; + } + // otherwise, put it back onto the queue + if (event_next) + gdk_event_put(event_next); + + return i; +} + +/** + * Toggles current tool between active tool and selector tool. + * Subroutine of sp_event_context_private_root_handler(). + */ +static void sp_toggle_selector(SPDesktop *dt) { + if (!dt->event_context) + return; + + if (tools_isactive(dt, TOOLS_SELECT)) { + if (selector_toggled) { + if (switch_selector_to) + tools_switch(dt, switch_selector_to); + selector_toggled = FALSE; + } else + return; + } else { + selector_toggled = TRUE; + switch_selector_to = tools_active(dt); + tools_switch(dt, TOOLS_SELECT); + } +} + +/** + * Toggles current tool between active tool and dropper tool. + * Subroutine of sp_event_context_private_root_handler(). + */ +void sp_toggle_dropper(SPDesktop *dt) { + if (!dt->event_context) + return; + + if (tools_isactive(dt, TOOLS_DROPPER)) { + if (dropper_toggled) { + if (switch_dropper_to) + tools_switch(dt, switch_dropper_to); + dropper_toggled = FALSE; + } else + return; + } else { + dropper_toggled = TRUE; + switch_dropper_to = tools_active(dt); + tools_switch(dt, TOOLS_DROPPER); + } +} + +/** + * Calculates and keeps track of scroll acceleration. + * Subroutine of sp_event_context_private_root_handler(). + */ +static gdouble accelerate_scroll(GdkEvent *event, gdouble acceleration, + SPCanvas */*canvas*/) { + guint32 time_diff = ((GdkEventKey *) event)->time - scroll_event_time; + + /* key pressed within 500ms ? (1/2 second) */ + if (time_diff > 500 || event->key.keyval != scroll_keyval) { + scroll_multiply = 1; // abort acceleration + } else { + scroll_multiply += acceleration; // continue acceleration + } + + scroll_event_time = ((GdkEventKey *) event)->time; + scroll_keyval = event->key.keyval; + + return scroll_multiply; +} + +bool ToolBase::root_handler(GdkEvent* event) { + static Geom::Point button_w; + static unsigned int panning = 0; + static unsigned int panning_cursor = 0; + static unsigned int zoom_rb = 0; + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + /// @todo REmove redundant /value in preference keys + tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + + gint ret = FALSE; + + switch (event->type) { + case GDK_2BUTTON_PRESS: + if (panning) { + panning = 0; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time); + ret = TRUE; + } else { + /* sp_desktop_dialog(); */ + } + break; + + case GDK_BUTTON_PRESS: + // save drag origin + xp = (gint) event->button.x; + yp = (gint) event->button.y; + within_tolerance = true; + + button_w = Geom::Point(event->button.x, event->button.y); + + switch (event->button.button) { + case 1: + if (this->space_panning) { + // When starting panning, make sure there are no snap events pending because these might disable the panning again + if (_uses_snap) { + sp_event_context_discard_delayed_snap_event(this); + } + panning = 1; + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + GDK_KEY_RELEASE_MASK | GDK_BUTTON_RELEASE_MASK + | GDK_POINTER_MOTION_MASK + | GDK_POINTER_MOTION_HINT_MASK, NULL, + event->button.time - 1); + + ret = TRUE; + } + break; + + case 2: + if (event->button.state & GDK_SHIFT_MASK) { + zoom_rb = 2; + } else { + // When starting panning, make sure there are no snap events pending because these might disable the panning again + if (_uses_snap) { + sp_event_context_discard_delayed_snap_event(this); + } + panning = 2; + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK + | GDK_POINTER_MOTION_HINT_MASK, NULL, + event->button.time - 1); + + } + + ret = TRUE; + break; + + case 3: + if ((event->button.state & GDK_SHIFT_MASK) || (event->button.state & GDK_CONTROL_MASK)) { + // When starting panning, make sure there are no snap events pending because these might disable the panning again + if (_uses_snap) { + sp_event_context_discard_delayed_snap_event(this); + } + panning = 3; + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK + | GDK_POINTER_MOTION_HINT_MASK, NULL, + event->button.time); + + ret = TRUE; + } else { + sp_event_root_menu_popup(desktop, NULL, event); + } + break; + + default: + break; + } + break; + + case GDK_MOTION_NOTIFY: + if (panning) { + if (panning == 4 && !xp && !yp ) { + // <Space> + mouse panning started, save location and grab canvas + xp = event->motion.x; + yp = event->motion.y; + button_w = Geom::Point(event->motion.x, event->motion.y); + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + GDK_KEY_RELEASE_MASK | GDK_BUTTON_RELEASE_MASK + | GDK_POINTER_MOTION_MASK + | GDK_POINTER_MOTION_HINT_MASK, NULL, + event->motion.time - 1); + } + + if ((panning == 2 && !(event->motion.state & GDK_BUTTON2_MASK)) + || (panning == 1 && !(event->motion.state & GDK_BUTTON1_MASK)) + || (panning == 3 && !(event->motion.state & GDK_BUTTON3_MASK))) { + /* Gdk seems to lose button release for us sometimes :-( */ + panning = 0; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time); + ret = TRUE; + } else { + if (within_tolerance && (abs((gint) event->motion.x - xp) + < tolerance) && (abs((gint) event->motion.y - yp) + < tolerance)) { + // do not drag if we're within tolerance from origin + break; + } + + // Once the user has moved farther than tolerance from + // the original location (indicating they intend to move + // the object, not click), then always process the motion + // notify coordinates as given (no snapping back to origin) + within_tolerance = false; + + // gobble subsequent motion events to prevent "sticking" + // when scrolling is slow + gobble_motion_events(panning == 2 ? GDK_BUTTON2_MASK : (panning + == 1 ? GDK_BUTTON1_MASK : GDK_BUTTON3_MASK)); + + if (panning_cursor == 0) { + panning_cursor = 1; + this->sp_event_context_set_cursor(GDK_FLEUR); + } + + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point const moved_w(motion_w - button_w); + this->desktop->scroll_world(moved_w, true); // we're still scrolling, do not redraw + ret = TRUE; + } + } else if (zoom_rb) { + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point const motion_dt(desktop->w2d(motion_w)); + + if (within_tolerance && (abs((gint) event->motion.x - xp) + < tolerance) && (abs((gint) event->motion.y - yp) + < tolerance)) { + break; // do not drag if we're within tolerance from origin + } + + // Once the user has moved farther than tolerance from the original location + // (indicating they intend to move the object, not click), then always process the + // motion notify coordinates as given (no snapping back to origin) + within_tolerance = false; + + if (Inkscape::Rubberband::get(desktop)->is_started()) { + Inkscape::Rubberband::get(desktop)->move(motion_dt); + } else { + Inkscape::Rubberband::get(desktop)->start(desktop, motion_dt); + } + + if (zoom_rb == 2) { + gobble_motion_events(GDK_BUTTON2_MASK); + } + } + break; + + case GDK_BUTTON_RELEASE: + xp = yp = 0; + + if (panning_cursor == 1) { + panning_cursor = 0; + GtkWidget *w = GTK_WIDGET(sp_desktop_canvas(this->desktop)); + gdk_window_set_cursor(gtk_widget_get_window (w), this->cursor); + } + + if (within_tolerance && (panning || zoom_rb)) { + zoom_rb = 0; + + if (panning) { + panning = 0; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), + event->button.time); + } + + Geom::Point const event_w(event->button.x, event->button.y); + Geom::Point const event_dt(desktop->w2d(event_w)); + + double const zoom_inc = prefs->getDoubleLimited( + "/options/zoomincrement/value", M_SQRT2, 1.01, 10); + + desktop->zoom_relative_keep_point(event_dt, (event->button.state + & GDK_SHIFT_MASK) ? 1 / zoom_inc : zoom_inc); + + desktop->updateNow(); + ret = TRUE; + } else if (panning == event->button.button) { + panning = 0; + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), + event->button.time); + + // in slow complex drawings, some of the motion events are lost; + // to make up for this, we scroll it once again to the button-up event coordinates + // (i.e. canvas will always get scrolled all the way to the mouse release point, + // even if few intermediate steps were visible) + Geom::Point const motion_w(event->button.x, event->button.y); + Geom::Point const moved_w(motion_w - button_w); + + this->desktop->scroll_world(moved_w); + desktop->updateNow(); + ret = TRUE; + } else if (zoom_rb == event->button.button) { + zoom_rb = 0; + + Geom::OptRect const b = Inkscape::Rubberband::get(desktop)->getRectangle(); + Inkscape::Rubberband::get(desktop)->stop(); + + if (b && !within_tolerance) { + desktop->set_display_area(*b, 10); + } + + ret = TRUE; + } + break; + + case GDK_KEY_PRESS: { + double const acceleration = prefs->getDoubleLimited( + "/options/scrollingacceleration/value", 0, 0, 6); + + int const key_scroll = prefs->getIntLimited("/options/keyscroll/value", + 10, 0, 1000); + + switch (get_group0_keyval(&event->key)) { + // GDK insists on stealing these keys (F1 for no idea what, tab for cycling widgets + // in the editing window). So we resteal them back and run our regular shortcut + // invoker on them. + unsigned int shortcut; + case GDK_KEY_Tab: + case GDK_KEY_ISO_Left_Tab: + case GDK_KEY_F1: + shortcut = get_group0_keyval(&event->key); + + if (event->key.state & GDK_SHIFT_MASK) { + shortcut |= SP_SHORTCUT_SHIFT_MASK; + } + + if (event->key.state & GDK_CONTROL_MASK) { + shortcut |= SP_SHORTCUT_CONTROL_MASK; + } + + if (event->key.state & GDK_MOD1_MASK) { + shortcut |= SP_SHORTCUT_ALT_MASK; + } + + ret = sp_shortcut_invoke(shortcut, desktop); + break; + + case GDK_KEY_Q: + case GDK_KEY_q: + if (desktop->quick_zoomed()) { + ret = TRUE; + } + if (!MOD__SHIFT(event) && !MOD__CTRL(event) && !MOD__ALT(event)) { + desktop->zoom_quick(true); + ret = TRUE; + } + break; + + case GDK_KEY_W: + case GDK_KEY_w: + case GDK_KEY_F4: + /* Close view */ + if (MOD__CTRL_ONLY(event)) { + sp_ui_close_view(NULL); + ret = TRUE; + } + break; + + case GDK_KEY_Left: // Ctrl Left + case GDK_KEY_KP_Left: + case GDK_KEY_KP_4: + if (MOD__CTRL_ONLY(event)) { + int i = (int) floor(key_scroll * accelerate_scroll(event, + acceleration, sp_desktop_canvas(desktop))); + + gobble_key_events(get_group0_keyval(&event->key), GDK_CONTROL_MASK); + this->desktop->scroll_world(i, 0); + ret = TRUE; + } + break; + + case GDK_KEY_Up: // Ctrl Up + case GDK_KEY_KP_Up: + case GDK_KEY_KP_8: + if (MOD__CTRL_ONLY(event)) { + int i = (int) floor(key_scroll * accelerate_scroll(event, + acceleration, sp_desktop_canvas(desktop))); + + gobble_key_events(get_group0_keyval(&event->key), GDK_CONTROL_MASK); + this->desktop->scroll_world(0, i); + ret = TRUE; + } + break; + + case GDK_KEY_Right: // Ctrl Right + case GDK_KEY_KP_Right: + case GDK_KEY_KP_6: + if (MOD__CTRL_ONLY(event)) { + int i = (int) floor(key_scroll * accelerate_scroll(event, + acceleration, sp_desktop_canvas(desktop))); + + gobble_key_events(get_group0_keyval(&event->key), GDK_CONTROL_MASK); + this->desktop->scroll_world(-i, 0); + ret = TRUE; + } + break; + + case GDK_KEY_Down: // Ctrl Down + case GDK_KEY_KP_Down: + case GDK_KEY_KP_2: + if (MOD__CTRL_ONLY(event)) { + int i = (int) floor(key_scroll * accelerate_scroll(event, + acceleration, sp_desktop_canvas(desktop))); + + gobble_key_events(get_group0_keyval(&event->key), GDK_CONTROL_MASK); + this->desktop->scroll_world(0, -i); + ret = TRUE; + } + break; + + case GDK_KEY_F10: + if (MOD__SHIFT_ONLY(event)) { + sp_event_root_menu_popup(desktop, NULL, event); + ret = TRUE; + } + break; + + case GDK_KEY_space: + xp = yp = 0; + within_tolerance = true; + panning = 4; + + this->space_panning = true; + this->message_context->set(Inkscape::INFORMATION_MESSAGE, + _("<b>Space+mouse move</b> to pan canvas")); + + ret = TRUE; + break; + + case GDK_KEY_z: + case GDK_KEY_Z: + if (MOD__ALT_ONLY(event)) { + desktop->zoom_grab_focus(); + ret = TRUE; + } + break; + + default: + break; + } + } + break; + + case GDK_KEY_RELEASE: + // Stop panning on any key release + if (this->space_panning) { + this->space_panning = false; + this->message_context->clear(); + } + + if (panning) { + panning = 0; + xp = yp = 0; + + sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), + event->key.time); + + desktop->updateNow(); + } + + if (panning_cursor == 1) { + panning_cursor = 0; + GtkWidget *w = GTK_WIDGET(sp_desktop_canvas(this->desktop)); + gdk_window_set_cursor(gtk_widget_get_window (w), this->cursor); + } + + switch (get_group0_keyval(&event->key)) { + case GDK_KEY_space: + if (within_tolerance == true) { + // Space was pressed, but not panned + sp_toggle_selector(desktop); + + // Be careful, sp_toggle_selector will delete ourselves. + // Thus, make sure we return immediately. + return true; + } + + break; + + case GDK_KEY_Q: + case GDK_KEY_q: + if (desktop->quick_zoomed()) { + desktop->zoom_quick(false); + ret = TRUE; + } + break; + + default: + break; + } + break; + + case GDK_SCROLL: { + bool ctrl = (event->scroll.state & GDK_CONTROL_MASK); + bool wheelzooms = prefs->getBool("/options/wheelzooms/value"); + + int const wheel_scroll = prefs->getIntLimited( + "/options/wheelscroll/value", 40, 0, 1000); + +#if GTK_CHECK_VERSION(3,0,0) + // Size of smooth-scrolls (only used in GTK+ 3) + gdouble delta_x = 0; + gdouble delta_y = 0; +#endif + + /* shift + wheel, pan left--right */ + if (event->scroll.state & GDK_SHIFT_MASK) { + switch (event->scroll.direction) { + case GDK_SCROLL_UP: + desktop->scroll_world(wheel_scroll, 0); + break; + + case GDK_SCROLL_DOWN: + desktop->scroll_world(-wheel_scroll, 0); + break; + + default: + break; + } + + /* ctrl + wheel, zoom in--out */ + } else if ((ctrl && !wheelzooms) || (!ctrl && wheelzooms)) { + double rel_zoom; + double const zoom_inc = prefs->getDoubleLimited( + "/options/zoomincrement/value", M_SQRT2, 1.01, 10); + + switch (event->scroll.direction) { + case GDK_SCROLL_UP: + rel_zoom = zoom_inc; + break; + + case GDK_SCROLL_DOWN: + rel_zoom = 1 / zoom_inc; + break; + + default: + rel_zoom = 0.0; + break; + } + + if (rel_zoom != 0.0) { + Geom::Point const scroll_dt = desktop->point(); + desktop->zoom_relative_keep_point(scroll_dt, rel_zoom); + } + + /* no modifier, pan up--down (left--right on multiwheel mice?) */ + } else { + switch (event->scroll.direction) { + case GDK_SCROLL_UP: + desktop->scroll_world(0, wheel_scroll); + break; + + case GDK_SCROLL_DOWN: + desktop->scroll_world(0, -wheel_scroll); + break; + + case GDK_SCROLL_LEFT: + desktop->scroll_world(wheel_scroll, 0); + break; + + case GDK_SCROLL_RIGHT: + desktop->scroll_world(-wheel_scroll, 0); + break; + +#if GTK_CHECK_VERSION(3,0,0) + case GDK_SCROLL_SMOOTH: + gdk_event_get_scroll_deltas(event, &delta_x, &delta_y); + desktop->scroll_world(delta_x, delta_y); + break; +#endif + } + } + break; + } + default: + break; + } + + return ret; +} + +/** + * Handles item specific events. Gets called from Gdk. + * + * Only reacts to right mouse button at the moment. + * \todo Fixme: do context sensitive popup menu on items. + */ +bool ToolBase::item_handler(SPItem* item, GdkEvent* event) { + int ret = FALSE; + + switch (event->type) { + case GDK_BUTTON_PRESS: + if ((event->button.button == 3) && !((event->button.state & GDK_SHIFT_MASK) || (event->button.state & GDK_CONTROL_MASK))) { + sp_event_root_menu_popup(this->desktop, item, event); + ret = TRUE; + } + break; + + default: + break; + } + + return ret; +} + +/** + * Returns true if we're hovering above a knot (needed because we don't want to pre-snap in that case). + */ +bool ToolBase::sp_event_context_knot_mouseover() const { + if (this->shape_editor) { + return this->shape_editor->knot_mouseover(); + } + + return false; +} + +/** + * Enables/disables the ToolBase's SelCue. + */ +void ToolBase::enableSelectionCue(bool enable) { + if (enable) { + if (!_selcue) { + _selcue = new Inkscape::SelCue(desktop); + } + } else { + delete _selcue; + _selcue = NULL; + } +} + +/** + * Enables/disables the ToolBase's GrDrag. + */ +void ToolBase::enableGrDrag(bool enable) { + if (enable) { + if (!_grdrag) { + _grdrag = new GrDrag(desktop); + } + } else { + if (_grdrag) { + delete _grdrag; + _grdrag = NULL; + } + } +} + +/** + * Delete a selected GrDrag point + */ +bool ToolBase::deleteSelectedDrag(bool just_one) { + + if (_grdrag && _grdrag->selected) { + _grdrag->deleteSelected(just_one); + return TRUE; + } + + return FALSE; +} + +/** + * Calls virtual set() function of ToolBase. + */ +void sp_event_context_read(ToolBase *ec, gchar const *key) { + g_return_if_fail(ec != NULL); + g_return_if_fail(SP_IS_EVENT_CONTEXT(ec)); + g_return_if_fail(key != NULL); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + Inkscape::Preferences::Entry val = prefs->getEntry(ec->pref_observer->observed_path + '/' + key); + ec->set(val); +} + +/** + * Calls virtual root_handler(), the main event handling function. + */ +gint sp_event_context_root_handler(ToolBase * event_context, + GdkEvent * event) +{ + if (!event_context->_uses_snap) { + return sp_event_context_virtual_root_handler(event_context, event); + } + + switch (event->type) { + case GDK_MOTION_NOTIFY: + sp_event_context_snap_delay_handler(event_context, NULL, NULL, + (GdkEventMotion *) event, + DelayedSnapEvent::EVENTCONTEXT_ROOT_HANDLER); + break; + case GDK_BUTTON_RELEASE: + if (event_context && event_context->_delayed_snap_event) { + // If we have any pending snapping action, then invoke it now + sp_event_context_snap_watchdog_callback( + event_context->_delayed_snap_event); + } + break; + case GDK_BUTTON_PRESS: + case GDK_2BUTTON_PRESS: + case GDK_3BUTTON_PRESS: + // Snapping will be on hold if we're moving the mouse at high speeds. When starting + // drawing a new shape we really should snap though. + event_context->desktop->namedview->snap_manager.snapprefs.setSnapPostponedGlobally( + false); + break; + default: + break; + } + + return sp_event_context_virtual_root_handler(event_context, event); +} + +gint sp_event_context_virtual_root_handler(ToolBase * event_context, GdkEvent * event) { + gint ret = false; + + if (event_context) { + // The root handler also handles pressing the space key. + // This will toggle the current tool and delete the current one. + // Thus, save a pointer to the desktop before calling it. + SPDesktop* desktop = event_context->desktop; + + ret = event_context->root_handler(event); + + set_event_location(desktop, event); + } + + return ret; +} + +/** + * Calls virtual item_handler(), the item event handling function. + */ +gint sp_event_context_item_handler(ToolBase * event_context, + SPItem * item, GdkEvent * event) +{ + if (!event_context->_uses_snap) { + return sp_event_context_virtual_item_handler(event_context, item, event); + } + + switch (event->type) { + case GDK_MOTION_NOTIFY: + sp_event_context_snap_delay_handler(event_context, (gpointer) item, NULL, (GdkEventMotion *) event, DelayedSnapEvent::EVENTCONTEXT_ITEM_HANDLER); + break; + case GDK_BUTTON_RELEASE: + if (event_context && event_context->_delayed_snap_event) { + // If we have any pending snapping action, then invoke it now + sp_event_context_snap_watchdog_callback(event_context->_delayed_snap_event); + } + break; + case GDK_BUTTON_PRESS: + case GDK_2BUTTON_PRESS: + case GDK_3BUTTON_PRESS: + // Snapping will be on hold if we're moving the mouse at high speeds. When starting + // drawing a new shape we really should snap though. + event_context->desktop->namedview->snap_manager.snapprefs.setSnapPostponedGlobally(false); + break; + default: + break; + } + + return sp_event_context_virtual_item_handler(event_context, item, event); +} + +gint sp_event_context_virtual_item_handler(ToolBase * event_context, SPItem * item, GdkEvent * event) { + gint ret = false; + if (event_context) { // If no event-context is available then do nothing, otherwise Inkscape would crash + // (see the comment in SPDesktop::set_event_context, and bug LP #622350) + //ret = (SP_EVENT_CONTEXT_CLASS(G_OBJECT_GET_CLASS(event_context)))->item_handler(event_context, item, event); + ret = event_context->item_handler(item, event); + + if (!ret) { + ret = sp_event_context_virtual_root_handler(event_context, event); + } else { + set_event_location(event_context->desktop, event); + } + } + + return ret; +} + +/** + * Shows coordinates on status bar. + */ +static void set_event_location(SPDesktop *desktop, GdkEvent *event) { + if (event->type != GDK_MOTION_NOTIFY) { + return; + } + + Geom::Point const button_w(event->button.x, event->button.y); + Geom::Point const button_dt(desktop->w2d(button_w)); + desktop->set_coordinate_status(button_dt); +} + +//------------------------------------------------------------------- +/** + * Create popup menu and tell Gtk to show it. + */ +void sp_event_root_menu_popup(SPDesktop *desktop, SPItem *item, GdkEvent *event) { + + // It seems the param item is the SPItem at the bottom of the z-order + // Using the same function call used on left click in sp_select_context_item_handler() to get top of z-order + // fixme: sp_canvas_arena should set the top z-order object as arena->active + item = sp_event_context_find_item (desktop, + Geom::Point(event->button.x, event->button.y), FALSE, FALSE); + + /* fixme: This is not what I want but works for now (Lauris) */ + if (event->type == GDK_KEY_PRESS) { + item = sp_desktop_selection(desktop)->singleItem(); + } + + ContextMenu* CM = new ContextMenu(desktop, item); + CM->show(); + + switch (event->type) { + case GDK_BUTTON_PRESS: + CM->popup(event->button.button, event->button.time); + break; + case GDK_KEY_PRESS: + CM->popup(0, event->key.time); + break; + default: + break; + } +} + +/** + * Show tool context specific modifier tip. + */ +void sp_event_show_modifier_tip(Inkscape::MessageContext *message_context, + GdkEvent *event, gchar const *ctrl_tip, gchar const *shift_tip, + gchar const *alt_tip) { + guint keyval = get_group0_keyval(&event->key); + + bool ctrl = ctrl_tip && (MOD__CTRL(event) || (keyval == GDK_KEY_Control_L) || (keyval + == GDK_KEY_Control_R)); + bool shift = shift_tip && (MOD__SHIFT(event) || (keyval == GDK_KEY_Shift_L) || (keyval + == GDK_KEY_Shift_R)); + bool alt = alt_tip && (MOD__ALT(event) || (keyval == GDK_KEY_Alt_L) || (keyval + == GDK_KEY_Alt_R) || (keyval == GDK_KEY_Meta_L) || (keyval == GDK_KEY_Meta_R)); + + gchar *tip = g_strdup_printf("%s%s%s%s%s", (ctrl ? ctrl_tip : ""), (ctrl + && (shift || alt) ? "; " : ""), (shift ? shift_tip : ""), ((ctrl + || shift) && alt ? "; " : ""), (alt ? alt_tip : "")); + + if (strlen(tip) > 0) { + message_context->flash(Inkscape::INFORMATION_MESSAGE, tip); + } + + g_free(tip); +} + +/** + * Return the keyval corresponding to the key event in group 0, i.e., + * in the main (English) layout. + * + * Use this instead of simply event->keyval, so that your keyboard shortcuts + * work regardless of layouts (e.g., in Cyrillic). + */ +guint get_group0_keyval(GdkEventKey *event) { + guint keyval = 0; + + gdk_keymap_translate_keyboard_state(gdk_keymap_get_for_display( + gdk_display_get_default()), event->hardware_keycode, + (GdkModifierType) event->state, 0 /*event->key.group*/, &keyval, + NULL, NULL, NULL); + + return keyval; +} + +/** + * Returns item at point p in desktop. + * + * If state includes alt key mask, cyclically selects under; honors + * into_groups. + */ +SPItem *sp_event_context_find_item(SPDesktop *desktop, Geom::Point const &p, + bool select_under, bool into_groups) +{ + SPItem *item = 0; + + if (select_under) { + SPItem *selected_at_point = desktop->getItemFromListAtPointBottom( + desktop->selection->itemList(), p); + item = desktop->getItemAtPoint(p, into_groups, selected_at_point); + if (item == NULL) { // we may have reached bottom, flip over to the top + item = desktop->getItemAtPoint(p, into_groups, NULL); + } + } else { + item = desktop->getItemAtPoint(p, into_groups, NULL); + } + + return item; +} + +/** + * Returns item if it is under point p in desktop, at any depth; otherwise returns NULL. + * + * Honors into_groups. + */ +SPItem * +sp_event_context_over_item(SPDesktop *desktop, SPItem *item, + Geom::Point const &p) { + GSList *temp = NULL; + temp = g_slist_prepend(temp, item); + SPItem *item_at_point = desktop->getItemFromListAtPointBottom(temp, p); + g_slist_free(temp); + + return item_at_point; +} + +ShapeEditor * +sp_event_context_get_shape_editor(ToolBase *ec) { + return ec->shape_editor; +} + +void event_context_print_event_info(GdkEvent *event, bool print_return) { + switch (event->type) { + case GDK_BUTTON_PRESS: + g_print("GDK_BUTTON_PRESS"); + break; + case GDK_2BUTTON_PRESS: + g_print("GDK_2BUTTON_PRESS"); + break; + case GDK_3BUTTON_PRESS: + g_print("GDK_3BUTTON_PRESS"); + break; + + case GDK_MOTION_NOTIFY: + g_print("GDK_MOTION_NOTIFY"); + break; + case GDK_ENTER_NOTIFY: + g_print("GDK_ENTER_NOTIFY"); + break; + + case GDK_LEAVE_NOTIFY: + g_print("GDK_LEAVE_NOTIFY"); + break; + case GDK_BUTTON_RELEASE: + g_print("GDK_BUTTON_RELEASE"); + break; + + case GDK_KEY_PRESS: + g_print("GDK_KEY_PRESS: %d", get_group0_keyval(&event->key)); + break; + case GDK_KEY_RELEASE: + g_print("GDK_KEY_RELEASE: %d", get_group0_keyval(&event->key)); + break; + default: + //g_print ("even type not recognized"); + break; + } + + if (print_return) { + g_print("\n"); + } +} + +/** + * Analyses the current event, calculates the mouse speed, turns snapping off (temporarily) if the + * mouse speed is above a threshold, and stores the current event such that it can be re-triggered when needed + * (re-triggering is controlled by a watchdog timer). + * + * @param ec Pointer to the event context. + * @param dse_item Pointer that store a reference to a canvas or to an item. + * @param dse_item2 Another pointer, storing a reference to a knot or controlpoint. + * @param event Pointer to the motion event. + * @param origin Identifier (enum) specifying where the delay (and the call to this method) were initiated. + */ +void sp_event_context_snap_delay_handler(ToolBase *ec, + gpointer const dse_item, gpointer const dse_item2, GdkEventMotion *event, + DelayedSnapEvent::DelayedSnapEventOrigin origin) +{ + static guint32 prev_time; + static boost::optional<Geom::Point> prev_pos; + + if (!ec->_uses_snap || ec->_dse_callback_in_process) { + return; + } + + // Snapping occurs when dragging with the left mouse button down, or when hovering e.g. in the pen tool with left mouse button up + bool const c1 = event->state & GDK_BUTTON2_MASK; // We shouldn't hold back any events when other mouse buttons have been + bool const c2 = event->state & GDK_BUTTON3_MASK; // pressed, e.g. when scrolling with the middle mouse button; if we do then + // Inkscape will get stuck in an unresponsive state + bool const c3 = tools_isactive(ec->desktop, TOOLS_CALLIGRAPHIC); + // The snap delay will repeat the last motion event, which will lead to + // erroneous points in the calligraphy context. And because we don't snap + // in this context, we might just as well disable the snap delay all together + + if (c1 || c2 || c3) { + // Make sure that we don't send any pending snap events to a context if we know in advance + // that we're not going to snap any way (e.g. while scrolling with middle mouse button) + // Any motion event might affect the state of the context, leading to unexpected behavior + sp_event_context_discard_delayed_snap_event(ec); + } else if (ec->desktop + && ec->desktop->namedview->snap_manager.snapprefs.getSnapEnabledGlobally()) { + // Snap when speed drops below e.g. 0.02 px/msec, or when no motion events have occurred for some period. + // i.e. snap when we're at stand still. A speed threshold enforces snapping for tablets, which might never + // be fully at stand still and might keep spitting out motion events. + ec->desktop->namedview->snap_manager.snapprefs.setSnapPostponedGlobally(true); // put snapping on hold + + Geom::Point event_pos(event->x, event->y); + guint32 event_t = gdk_event_get_time((GdkEvent *) event); + + if (prev_pos) { + Geom::Coord dist = Geom::L2(event_pos - *prev_pos); + guint32 delta_t = event_t - prev_time; + gdouble speed = delta_t > 0 ? dist / delta_t : 1000; + //std::cout << "Mouse speed = " << speed << " px/msec " << std::endl; + if (speed > 0.02) { // Jitter threshold, might be needed for tablets + // We're moving fast, so postpone any snapping until the next GDK_MOTION_NOTIFY event. We + // will keep on postponing the snapping as long as the speed is high. + // We must snap at some point in time though, so set a watchdog timer at some time from + // now, just in case there's no future motion event that drops under the speed limit (when + // stopping abruptly) + delete ec->_delayed_snap_event; + ec->_delayed_snap_event = new DelayedSnapEvent(ec, dse_item, dse_item2, + event, origin); // watchdog is reset, i.e. pushed forward in time + // If the watchdog expires before a new motion event is received, we will snap (as explained + // above). This means however that when the timer is too short, we will always snap and that the + // speed threshold is ineffective. In the extreme case the delay is set to zero, and snapping will + // be immediate, as it used to be in the old days ;-). + } else { // Speed is very low, so we're virtually at stand still + // But if we're really standing still, then we should snap now. We could use some low-pass filtering, + // otherwise snapping occurs for each jitter movement. For this filtering we'll leave the watchdog to expire, + // snap, and set a new watchdog again. + if (ec->_delayed_snap_event == NULL) { // no watchdog has been set + // it might have already expired, so we'll set a new one; the snapping frequency will be limited this way + ec->_delayed_snap_event = new DelayedSnapEvent(ec, dse_item, + dse_item2, event, origin); + } // else: watchdog has been set before and we'll wait for it to expire + } + } else { + // This is the first GDK_MOTION_NOTIFY event, so postpone snapping and set the watchdog + g_assert(ec->_delayed_snap_event == NULL); + ec->_delayed_snap_event = new DelayedSnapEvent(ec, dse_item, dse_item2, + event, origin); + } + + prev_pos = event_pos; + prev_time = event_t; + } +} + +/** + * When the snap delay watchdog timer barks, this method will be called and will re-inject the last motion + * event in an appropriate place, with snapping being turned on again. + */ +gboolean sp_event_context_snap_watchdog_callback(gpointer data) { + // Snap NOW! For this the "postponed" flag will be reset and the last motion event will be repeated + DelayedSnapEvent *dse = reinterpret_cast<DelayedSnapEvent*> (data); + + if (dse == NULL) { + // This might occur when this method is called directly, i.e. not through the timer + // E.g. on GDK_BUTTON_RELEASE in sp_event_context_root_handler() + return FALSE; + } + + ToolBase *ec = dse->getEventContext(); + if (ec == NULL) { + delete dse; + return false; + } + if (ec->desktop == NULL) { + ec->_delayed_snap_event = NULL; + delete dse; + return false; + } + + ec->_dse_callback_in_process = true; + + SPDesktop *dt = ec->desktop; + dt->namedview->snap_manager.snapprefs.setSnapPostponedGlobally(false); + + // Depending on where the delayed snap event originated from, we will inject it back at it's origin + // The switch below takes care of that and prepares the relevant parameters + switch (dse->getOrigin()) { + case DelayedSnapEvent::EVENTCONTEXT_ROOT_HANDLER: + sp_event_context_virtual_root_handler(ec, dse->getEvent()); + break; + case DelayedSnapEvent::EVENTCONTEXT_ITEM_HANDLER: { + gpointer item = dse->getItem(); + if (item && SP_IS_ITEM(item)) { + sp_event_context_virtual_item_handler(ec, SP_ITEM(item), dse->getEvent()); + } + } + break; + case DelayedSnapEvent::KNOT_HANDLER: { + gpointer knot = dse->getItem2(); + if (knot && SP_IS_KNOT(knot)) { + sp_knot_handler_request_position(dse->getEvent(), SP_KNOT(knot)); + } + } + break; + case DelayedSnapEvent::CONTROL_POINT_HANDLER: { + using Inkscape::UI::ControlPoint; + gpointer pitem2 = dse->getItem2(); + if (!pitem2) + { + ec->_delayed_snap_event = NULL; + delete dse; + return false; + } + ControlPoint *point = reinterpret_cast<ControlPoint*> (pitem2); + if (point) { + if (point->position().isFinite() && (dt == point->_desktop)) { + point->_eventHandler(ec, dse->getEvent()); + } + else { + //workaround: + //[Bug 781893] Crash after moving a Bezier node after Knot path effect? + // --> at some time, some point with X = 0 and Y = nan (not a number) is created ... + // even so, the desktop pointer is invalid and equal to 0xff + g_warning ("encountered non finite point when evaluating snapping callback"); + } + } + } + break; + case DelayedSnapEvent::GUIDE_HANDLER: { + gpointer item = dse->getItem(); + gpointer item2 = dse->getItem2(); + if (item && item2) { + g_assert(SP_IS_CANVAS_ITEM(item)); + g_assert(SP_IS_GUIDE(item2)); + sp_dt_guide_event(SP_CANVAS_ITEM(item), dse->getEvent(), item2); + } + } + break; + case DelayedSnapEvent::GUIDE_HRULER: + case DelayedSnapEvent::GUIDE_VRULER: { + gpointer item = dse->getItem(); + gpointer item2 = dse->getItem2(); + if (item && item2) { + g_assert(GTK_IS_WIDGET(item)); + g_assert(SP_IS_DESKTOP_WIDGET(item2)); + if (dse->getOrigin() == DelayedSnapEvent::GUIDE_HRULER) { + sp_dt_hruler_event(GTK_WIDGET(item), dse->getEvent(), SP_DESKTOP_WIDGET(item2)); + } else { + sp_dt_vruler_event(GTK_WIDGET(item), dse->getEvent(), SP_DESKTOP_WIDGET(item2)); + } + } + } + break; + default: + g_warning("Origin of snap-delay event has not been defined!;"); + break; + } + + ec->_delayed_snap_event = NULL; + delete dse; + + ec->_dse_callback_in_process = false; + + return FALSE; //Kills the timer and stops it from executing this callback over and over again. +} + +void sp_event_context_discard_delayed_snap_event(ToolBase *ec) { + delete ec->_delayed_snap_event; + ec->_delayed_snap_event = NULL; + ec->desktop->namedview->snap_manager.snapprefs.setSnapPostponedGlobally(false); +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: + */ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/tool-base.h b/src/ui/tools/tool-base.h new file mode 100644 index 000000000..def6e3d91 --- /dev/null +++ b/src/ui/tools/tool-base.h @@ -0,0 +1,266 @@ +#ifndef SEEN_SP_EVENT_CONTEXT_H +#define SEEN_SP_EVENT_CONTEXT_H + +/* + * Authors: + * Lauris Kaplinski <lauris@kaplinski.com> + * Frank Felfe <innerspace@iname.com> + * + * Copyright (C) 1999-2002 authors + * Copyright (C) 2001-2002 Ximian, Inc. + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include <glib-object.h> +#include <gdk/gdk.h> +#include <sigc++/trackable.h> +#include "knot.h" + +#include "2geom/forward.h" +#include "preferences.h" + +class GrDrag; +class SPDesktop; +class SPItem; +class ShapeEditor; + +namespace Inkscape { + class MessageContext; + class SelCue; + namespace XML { + class Node; + } +} + +#define SP_EVENT_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::ToolBase*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_EVENT_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::ToolBase*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +namespace Inkscape { +namespace UI { +namespace Tools { + +class ToolBase; + +gboolean sp_event_context_snap_watchdog_callback(gpointer data); +void sp_event_context_discard_delayed_snap_event(ToolBase *ec); + +class DelayedSnapEvent +{ +public: + enum DelayedSnapEventOrigin { + UNDEFINED_HANDLER = 0, + EVENTCONTEXT_ROOT_HANDLER, + EVENTCONTEXT_ITEM_HANDLER, + KNOT_HANDLER, + CONTROL_POINT_HANDLER, + GUIDE_HANDLER, + GUIDE_HRULER, + GUIDE_VRULER + }; + + DelayedSnapEvent(ToolBase *event_context, gpointer const dse_item, gpointer dse_item2, GdkEventMotion const *event, DelayedSnapEvent::DelayedSnapEventOrigin const origin) + : _timer_id(0), _event(NULL), _item(dse_item), _item2(dse_item2), _origin(origin), _event_context(event_context) + { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + double value = prefs->getDoubleLimited("/options/snapdelay/value", 0, 0, 1000); + _timer_id = g_timeout_add(value, &sp_event_context_snap_watchdog_callback, this); + _event = gdk_event_copy((GdkEvent*) event); + ((GdkEventMotion *)_event)->time = GDK_CURRENT_TIME; + } + + ~DelayedSnapEvent() { + if (_timer_id > 0) g_source_remove(_timer_id); // Kill the watchdog + if (_event != NULL) gdk_event_free(_event); // Remove the copy of the original event + } + + ToolBase* getEventContext() {return _event_context;} + DelayedSnapEventOrigin getOrigin() {return _origin;} + GdkEvent* getEvent() {return _event;} + gpointer getItem() {return _item;} + gpointer getItem2() {return _item2;} + +private: + guint _timer_id; + GdkEvent* _event; + gpointer _item; + gpointer _item2; + DelayedSnapEventOrigin _origin; + ToolBase* _event_context; +}; + +void sp_event_context_snap_delay_handler(ToolBase *ec, gpointer const dse_item, gpointer const dse_item2, GdkEventMotion *event, DelayedSnapEvent::DelayedSnapEventOrigin origin); + + +/** + * Base class for Event processors. + * + * This is per desktop object, which (its derivatives) implements + * different actions bound to mouse events. + * + * ToolBase is an abstract base class of all tools. As the name + * indicates, event context implementations process UI events (mouse + * movements and keypresses) and take actions (like creating or modifying + * objects). There is one event context implementation for each tool, + * plus few abstract base classes. Writing a new tool involves + * subclassing ToolBase. + */ +class ToolBase + : public sigc::trackable +{ +public: + void enableSelectionCue (bool enable=true); + void enableGrDrag (bool enable=true); + bool deleteSelectedDrag(bool just_one); + + ToolBase(gchar const *const *cursor_shape, gint hot_x, gint hot_y, bool uses_snap = true); + + virtual ~ToolBase(); + + Inkscape::Preferences::Observer *pref_observer; + GdkCursor *cursor; + + gint xp, yp; ///< where drag started + gint tolerance; + + bool within_tolerance; ///< are we still within tolerance of origin + + SPItem *item_to_select; ///< the item where mouse_press occurred, to + ///< be selected if this is a click not drag + + Inkscape::MessageContext *defaultMessageContext() { + return message_context; + } + + Inkscape::MessageContext *message_context; + + Inkscape::SelCue *_selcue; + + GrDrag *_grdrag; + GrDrag *get_drag () {return _grdrag;} + + ShapeEditor* shape_editor; + + bool space_panning; + + DelayedSnapEvent *_delayed_snap_event; + bool _dse_callback_in_process; + + virtual void setup(); + virtual void finish(); + + // Is called by our pref_observer if a preference has been changed. + virtual void set(const Inkscape::Preferences::Entry& val); + + virtual bool root_handler(GdkEvent* event); + virtual bool item_handler(SPItem* item, GdkEvent* event); + + virtual const std::string& getPrefsPath() = 0; + + /** + * An observer that relays pref changes to the derived classes. + */ + class ToolPrefObserver: public Inkscape::Preferences::Observer { + public: + ToolPrefObserver(Glib::ustring const &path, ToolBase *ec) : + Inkscape::Preferences::Observer(path), ec(ec) { + } + + virtual void notify(Inkscape::Preferences::Entry const &val) { + ec->set(val); + } + + private: + ToolBase * const ec; + }; + + SPDesktop const& getDesktop() const; + + +//protected: + void sp_event_context_update_cursor(); + + SPDesktop *desktop; + bool _uses_snap; // TODO: make protected or private + +protected: + /// An xpm containing the shape of the tool's cursor. + gchar const *const *cursor_shape; + + /// The cursor's hot spot + gint hot_x, hot_y; + /// Whether the tool should receive delayed snap events + + bool sp_event_context_knot_mouseover() const; + +private: + ToolBase(const ToolBase&); + ToolBase& operator=(const ToolBase&); + + void sp_event_context_set_cursor(GdkCursorType cursor_type); + +}; + +void sp_event_context_read(ToolBase *ec, gchar const *key); + +gint sp_event_context_root_handler(ToolBase *ec, GdkEvent *event); +gint sp_event_context_virtual_root_handler(ToolBase *ec, GdkEvent *event); +gint sp_event_context_item_handler(ToolBase *ec, SPItem *item, GdkEvent *event); +gint sp_event_context_virtual_item_handler(ToolBase *ec, SPItem *item, GdkEvent *event); + +void sp_event_root_menu_popup(SPDesktop *desktop, SPItem *item, GdkEvent *event); + +gint gobble_key_events(guint keyval, gint mask); +gint gobble_motion_events(gint mask); + +void sp_event_show_modifier_tip(Inkscape::MessageContext *message_context, GdkEvent *event, + gchar const *ctrl_tip, gchar const *shift_tip, gchar const *alt_tip); + +guint get_group0_keyval(GdkEventKey *event); + +SPItem *sp_event_context_find_item (SPDesktop *desktop, Geom::Point const &p, bool select_under, bool into_groups); +SPItem *sp_event_context_over_item (SPDesktop *desktop, SPItem *item, Geom::Point const &p); + +void sp_toggle_dropper(SPDesktop *dt); + +bool sp_event_context_knot_mouseover(ToolBase *ec); + +} // namespace Tools + +//#include <type_traits> + +namespace Tool { + +template<class Derived, typename T> +bool is_a(const T* t) { + //static_assert(std::is_base_of<Tools::ToolBase, Derived>(), "Destination type not derived from ToolBase."); + //static_assert(std::is_convertible<const Tools::ToolBase*, const T*>(), "Cannot cast passed pointer to ToolBase*."); + + return dynamic_cast<const Derived*>(static_cast<const Tools::ToolBase*>(t)) != NULL; +} + +template<class Derived, typename T> +Derived* to(T* t) { + //static_assert(std::is_base_of<Tools::ToolBase, Derived>(), "Destination type not derived from ToolBase."); + //static_assert(std::is_convertible<Tools::ToolBase*, T*>(), "Cannot cast passed pointer to ToolBase*."); + + return dynamic_cast<Derived*>(static_cast<Tools::ToolBase*>(t)); +} + +} // namespace Tool +} // namespace UI +} // namespace Inkscape + +#endif // SEEN_SP_EVENT_CONTEXT_H + + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/tweak-tool.cpp b/src/ui/tools/tweak-tool.cpp new file mode 100644 index 000000000..75650d3af --- /dev/null +++ b/src/ui/tools/tweak-tool.cpp @@ -0,0 +1,1517 @@ +/* + * tweaking paths without node editing + * + * Authors: + * bulia byak + * Jon A. Cruz <jon@joncruz.org> + * Abhishek Sharma + * + * Copyright (C) 2007 authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "config.h" + +#include <gtk/gtk.h> +#include <gdk/gdkkeysyms.h> +#include <glibmm/i18n.h> + +#include <numeric> + +#include "svg/svg.h" + +#include <glib.h> +#include "macros.h" +#include "document.h" +#include "document-undo.h" +#include "selection.h" +#include "desktop.h" +#include "desktop-events.h" +#include "desktop-handles.h" +#include "desktop-style.h" +#include "message-context.h" +#include "pixmaps/cursor-tweak-move.xpm" +#include "pixmaps/cursor-tweak-move-in.xpm" +#include "pixmaps/cursor-tweak-move-out.xpm" +#include "pixmaps/cursor-tweak-move-jitter.xpm" +#include "pixmaps/cursor-tweak-scale-up.xpm" +#include "pixmaps/cursor-tweak-scale-down.xpm" +#include "pixmaps/cursor-tweak-rotate-clockwise.xpm" +#include "pixmaps/cursor-tweak-rotate-counterclockwise.xpm" +#include "pixmaps/cursor-tweak-more.xpm" +#include "pixmaps/cursor-tweak-less.xpm" +#include "pixmaps/cursor-thin.xpm" +#include "pixmaps/cursor-thicken.xpm" +#include "pixmaps/cursor-attract.xpm" +#include "pixmaps/cursor-repel.xpm" +#include "pixmaps/cursor-push.xpm" +#include "pixmaps/cursor-roughen.xpm" +#include "pixmaps/cursor-color.xpm" +#include <boost/optional.hpp> +#include "xml/repr.h" +#include "context-fns.h" +#include "sp-item.h" +#include "inkscape.h" +#include "color.h" +#include "svg/svg-color.h" +#include "splivarot.h" +#include "sp-item-group.h" +#include "sp-shape.h" +#include "sp-path.h" +#include "path-chemistry.h" +#include "sp-gradient.h" +#include "sp-stop.h" +#include "sp-gradient-reference.h" +#include "sp-linear-gradient.h" +#include "sp-radial-gradient.h" +#include "gradient-chemistry.h" +#include "sp-text.h" +#include "sp-flowtext.h" +#include "display/sp-canvas.h" +#include "display/canvas-bpath.h" +#include "display/canvas-arena.h" +#include "display/curve.h" +#include "livarot/Shape.h" +#include <2geom/transforms.h> +#include <2geom/circle.h> +#include "preferences.h" +#include "style.h" +#include "box3d.h" +#include "sp-item-transform.h" +#include "filter-chemistry.h" +#include "filters/gaussian-blur.h" +#include "verbs.h" + +#include "ui/tools/tweak-tool.h" + +using Inkscape::DocumentUndo; + +#define DDC_RED_RGBA 0xff0000ff + +#define DYNA_MIN_WIDTH 1.0e-6 + +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +namespace { + ToolBase* createTweakContext() { + return new TweakTool(); + } + + bool tweakContextRegistered = ToolFactory::instance().registerObject("/tools/tweak", createTweakContext); +} + +const std::string& TweakTool::getPrefsPath() { + return TweakTool::prefsPath; +} + +const std::string TweakTool::prefsPath = "/tools/tweak"; + +TweakTool::TweakTool() + : ToolBase(cursor_push_xpm, 4, 4) + , pressure(TC_DEFAULT_PRESSURE) + , dragging(false) + , usepressure(false) + , usetilt(false) + , width(0.2) + , force(0.2) + , fidelity(0) + , mode(0) + , is_drawing(false) + , is_dilating(false) + , has_dilated(false) + , dilate_area(NULL) + , do_h(true) + , do_s(true) + , do_l(true) + , do_o(false) +{ +} + +TweakTool::~TweakTool() { + this->enableGrDrag(false); + + this->style_set_connection.disconnect(); + + if (this->dilate_area) { + sp_canvas_item_destroy(this->dilate_area); + this->dilate_area = NULL; + } +} + +static bool is_transform_mode (gint mode) +{ + return (mode == TWEAK_MODE_MOVE || + mode == TWEAK_MODE_MOVE_IN_OUT || + mode == TWEAK_MODE_MOVE_JITTER || + mode == TWEAK_MODE_SCALE || + mode == TWEAK_MODE_ROTATE || + mode == TWEAK_MODE_MORELESS); +} + +static bool is_color_mode (gint mode) +{ + return (mode == TWEAK_MODE_COLORPAINT || mode == TWEAK_MODE_COLORJITTER || mode == TWEAK_MODE_BLUR); +} + +void TweakTool::update_cursor (bool with_shift) { + guint num = 0; + gchar *sel_message = NULL; + + if (!desktop->selection->isEmpty()) { + num = g_slist_length(const_cast<GSList *>(desktop->selection->itemList())); + sel_message = g_strdup_printf(ngettext("<b>%i</b> object selected","<b>%i</b> objects selected",num), num); + } else { + sel_message = g_strdup_printf("%s", _("<b>Nothing</b> selected")); + } + + switch (this->mode) { + case TWEAK_MODE_MOVE: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag to <b>move</b>."), sel_message); + this->cursor_shape = cursor_tweak_move_xpm; + break; + case TWEAK_MODE_MOVE_IN_OUT: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag or click to <b>move in</b>; with Shift to <b>move out</b>."), sel_message); + if (with_shift) { + this->cursor_shape = cursor_tweak_move_out_xpm; + } else { + this->cursor_shape = cursor_tweak_move_in_xpm; + } + break; + case TWEAK_MODE_MOVE_JITTER: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag or click to <b>move randomly</b>."), sel_message); + this->cursor_shape = cursor_tweak_move_jitter_xpm; + break; + case TWEAK_MODE_SCALE: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag or click to <b>scale down</b>; with Shift to <b>scale up</b>."), sel_message); + if (with_shift) { + this->cursor_shape = cursor_tweak_scale_up_xpm; + } else { + this->cursor_shape = cursor_tweak_scale_down_xpm; + } + break; + case TWEAK_MODE_ROTATE: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag or click to <b>rotate clockwise</b>; with Shift, <b>counterclockwise</b>."), sel_message); + if (with_shift) { + this->cursor_shape = cursor_tweak_rotate_counterclockwise_xpm; + } else { + this->cursor_shape = cursor_tweak_rotate_clockwise_xpm; + } + break; + case TWEAK_MODE_MORELESS: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag or click to <b>duplicate</b>; with Shift, <b>delete</b>."), sel_message); + if (with_shift) { + this->cursor_shape = cursor_tweak_less_xpm; + } else { + this->cursor_shape = cursor_tweak_more_xpm; + } + break; + case TWEAK_MODE_PUSH: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag to <b>push paths</b>."), sel_message); + this->cursor_shape = cursor_push_xpm; + break; + case TWEAK_MODE_SHRINK_GROW: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag or click to <b>inset paths</b>; with Shift to <b>outset</b>."), sel_message); + if (with_shift) { + this->cursor_shape = cursor_thicken_xpm; + } else { + this->cursor_shape = cursor_thin_xpm; + } + break; + case TWEAK_MODE_ATTRACT_REPEL: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag or click to <b>attract paths</b>; with Shift to <b>repel</b>."), sel_message); + if (with_shift) { + this->cursor_shape = cursor_repel_xpm; + } else { + this->cursor_shape = cursor_attract_xpm; + } + break; + case TWEAK_MODE_ROUGHEN: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag or click to <b>roughen paths</b>."), sel_message); + this->cursor_shape = cursor_roughen_xpm; + break; + case TWEAK_MODE_COLORPAINT: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag or click to <b>paint objects</b> with color."), sel_message); + this->cursor_shape = cursor_color_xpm; + break; + case TWEAK_MODE_COLORJITTER: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag or click to <b>randomize colors</b>."), sel_message); + this->cursor_shape = cursor_color_xpm; + break; + case TWEAK_MODE_BLUR: + this->message_context->setF(Inkscape::NORMAL_MESSAGE, _("%s. Drag or click to <b>increase blur</b>; with Shift to <b>decrease</b>."), sel_message); + this->cursor_shape = cursor_color_xpm; + break; + } + + this->sp_event_context_update_cursor(); + g_free(sel_message); +} + +bool TweakTool::set_style(const SPCSSAttr* css) { + if (this->mode == TWEAK_MODE_COLORPAINT) { // intercept color setting only in this mode + // we cannot store properties with uris + css = sp_css_attr_unset_uris(const_cast<SPCSSAttr *>(css)); + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + prefs->setStyle("/tools/tweak/style", const_cast<SPCSSAttr *>(css)); + return true; + } + + return false; +} + +void TweakTool::setup() { + ToolBase::setup(); + + { + /* TODO: have a look at sp_dyna_draw_context_setup where the same is done.. generalize? at least make it an arcto! */ + Geom::PathVector path; + Geom::Circle(0, 0, 1).getPath(path); + + SPCurve *c = new SPCurve(path); + + this->dilate_area = sp_canvas_bpath_new(sp_desktop_controls(this->desktop), c); + c->unref(); + sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(this->dilate_area), 0x00000000,(SPWindRule)0); + sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(this->dilate_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); + sp_canvas_item_hide(this->dilate_area); + } + + this->is_drawing = false; + + sp_event_context_read(this, "width"); + sp_event_context_read(this, "mode"); + sp_event_context_read(this, "fidelity"); + sp_event_context_read(this, "force"); + sp_event_context_read(this, "usepressure"); + sp_event_context_read(this, "doh"); + sp_event_context_read(this, "dol"); + sp_event_context_read(this, "dos"); + sp_event_context_read(this, "doo"); + + this->style_set_connection = this->desktop->connectSetStyle( // catch style-setting signal in this tool + //sigc::bind(sigc::ptr_fun(&sp_tweak_context_style_set), this) + sigc::mem_fun(this, &TweakTool::set_style) + ); + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (prefs->getBool("/tools/tweak/selcue")) { + this->enableSelectionCue(); + } + if (prefs->getBool("/tools/tweak/gradientdrag")) { + this->enableGrDrag(); + } +} + +void TweakTool::set(const Inkscape::Preferences::Entry& val) { + Glib::ustring path = val.getEntryName(); + + if (path == "width") { + this->width = CLAMP(val.getDouble(0.1), -1000.0, 1000.0); + } else if (path == "mode") { + this->mode = val.getInt(); + this->update_cursor(false); + } else if (path == "fidelity") { + this->fidelity = CLAMP(val.getDouble(), 0.0, 1.0); + } else if (path == "force") { + this->force = CLAMP(val.getDouble(1.0), 0, 1.0); + } else if (path == "usepressure") { + this->usepressure = val.getBool(); + } else if (path == "doh") { + this->do_h = val.getBool(); + } else if (path == "dos") { + this->do_s = val.getBool(); + } else if (path == "dol") { + this->do_l = val.getBool(); + } else if (path == "doo") { + this->do_o = val.getBool(); + } +} + +static void +sp_tweak_extinput(TweakTool *tc, GdkEvent *event) +{ + if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &tc->pressure)) { + tc->pressure = CLAMP (tc->pressure, TC_MIN_PRESSURE, TC_MAX_PRESSURE); + } else { + tc->pressure = TC_DEFAULT_PRESSURE; + } +} + +static double +get_dilate_radius (TweakTool *tc) +{ + // 10 times the pen width: + return 500 * tc->width/SP_EVENT_CONTEXT(tc)->desktop->current_zoom(); +} + +static double +get_path_force (TweakTool *tc) +{ + double force = 8 * (tc->usepressure? tc->pressure : TC_DEFAULT_PRESSURE) + /sqrt(SP_EVENT_CONTEXT(tc)->desktop->current_zoom()); + if (force > 3) { + force += 4 * (force - 3); + } + return force * tc->force; +} + +static double +get_move_force (TweakTool *tc) +{ + double force = (tc->usepressure? tc->pressure : TC_DEFAULT_PRESSURE); + return force * tc->force; +} + +static bool +sp_tweak_dilate_recursive (Inkscape::Selection *selection, SPItem *item, Geom::Point p, Geom::Point vector, gint mode, double radius, double force, double fidelity, bool reverse) +{ + bool did = false; + + if (SP_IS_BOX3D(item) && !is_transform_mode(mode) && !is_color_mode(mode)) { + // convert 3D boxes to ordinary groups before tweaking their shapes + item = box3d_convert_to_group(SP_BOX3D(item)); + selection->add(item); + } + + if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item)) { + GSList *items = g_slist_prepend (NULL, item); + GSList *selected = NULL; + GSList *to_select = NULL; + SPDocument *doc = item->document; + sp_item_list_to_curves (items, &selected, &to_select); + g_slist_free (items); + SPObject* newObj = doc->getObjectByRepr(static_cast<Inkscape::XML::Node *>(to_select->data)); + g_slist_free (to_select); + item = SP_ITEM(newObj); + selection->add(item); + } + + if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item)) { + GSList *children = NULL; + for (SPObject *child = item->firstChild() ; child; child = child->getNext() ) { + if (SP_IS_ITEM(child)) { + children = g_slist_prepend(children, child); + } + } + + for (GSList *i = children; i; i = i->next) { + SPItem *child = SP_ITEM(i->data); + if (sp_tweak_dilate_recursive (selection, SP_ITEM(child), p, vector, mode, radius, force, fidelity, reverse)) + did = true; + } + + g_slist_free(children); + + } else { + if (mode == TWEAK_MODE_MOVE) { + + Geom::OptRect a = item->documentVisualBounds(); + if (a) { + double x = Geom::L2(a->midpoint() - p)/radius; + if (a->contains(p)) x = 0; + if (x < 1) { + Geom::Point move = force * 0.5 * (cos(M_PI * x) + 1) * vector; + sp_item_move_rel(item, Geom::Translate(move[Geom::X], -move[Geom::Y])); + did = true; + } + } + + } else if (mode == TWEAK_MODE_MOVE_IN_OUT) { + + Geom::OptRect a = item->documentVisualBounds(); + if (a) { + double x = Geom::L2(a->midpoint() - p)/radius; + if (a->contains(p)) x = 0; + if (x < 1) { + Geom::Point move = force * 0.5 * (cos(M_PI * x) + 1) * + (reverse? (a->midpoint() - p) : (p - a->midpoint())); + sp_item_move_rel(item, Geom::Translate(move[Geom::X], -move[Geom::Y])); + did = true; + } + } + + } else if (mode == TWEAK_MODE_MOVE_JITTER) { + + Geom::OptRect a = item->documentVisualBounds(); + if (a) { + double dp = g_random_double_range(0, M_PI*2); + double dr = g_random_double_range(0, radius); + double x = Geom::L2(a->midpoint() - p)/radius; + if (a->contains(p)) x = 0; + if (x < 1) { + Geom::Point move = force * 0.5 * (cos(M_PI * x) + 1) * Geom::Point(cos(dp)*dr, sin(dp)*dr); + sp_item_move_rel(item, Geom::Translate(move[Geom::X], -move[Geom::Y])); + did = true; + } + } + + } else if (mode == TWEAK_MODE_SCALE) { + + Geom::OptRect a = item->documentVisualBounds(); + if (a) { + double x = Geom::L2(a->midpoint() - p)/radius; + if (a->contains(p)) x = 0; + if (x < 1) { + double scale = 1 + (reverse? force : -force) * 0.05 * (cos(M_PI * x) + 1); + sp_item_scale_rel(item, Geom::Scale(scale, scale)); + did = true; + } + } + + } else if (mode == TWEAK_MODE_ROTATE) { + + Geom::OptRect a = item->documentVisualBounds(); + if (a) { + double x = Geom::L2(a->midpoint() - p)/radius; + if (a->contains(p)) x = 0; + if (x < 1) { + double angle = (reverse? force : -force) * 0.05 * (cos(M_PI * x) + 1) * M_PI; + sp_item_rotate_rel(item, Geom::Rotate(angle)); + did = true; + } + } + + } else if (mode == TWEAK_MODE_MORELESS) { + + Geom::OptRect a = item->documentVisualBounds(); + if (a) { + double x = Geom::L2(a->midpoint() - p)/radius; + if (a->contains(p)) x = 0; + if (x < 1) { + double prob = force * 0.5 * (cos(M_PI * x) + 1); + double chance = g_random_double_range(0, 1); + if (chance <= prob) { + if (reverse) { // delete + sp_object_ref(item, NULL); + item->deleteObject(true, true); + sp_object_unref(item, NULL); + } else { // duplicate + SPDocument *doc = item->document; + Inkscape::XML::Document* xml_doc = doc->getReprDoc(); + Inkscape::XML::Node *old_repr = item->getRepr(); + SPObject *old_obj = doc->getObjectByRepr(old_repr); + Inkscape::XML::Node *parent = old_repr->parent(); + Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc); + parent->appendChild(copy); + SPObject *new_obj = doc->getObjectByRepr(copy); + if (selection->includes(old_obj)) { + selection->add(new_obj); + } + Inkscape::GC::release(copy); + } + did = true; + } + } + } + + } else if (SP_IS_PATH(item) || SP_IS_SHAPE(item)) { + + Inkscape::XML::Node *newrepr = NULL; + gint pos = 0; + Inkscape::XML::Node *parent = NULL; + char const *id = NULL; + if (!SP_IS_PATH(item)) { + newrepr = sp_selected_item_to_curved_repr(item, 0); + if (!newrepr) { + return false; + } + + // remember the position of the item + pos = item->getRepr()->position(); + // remember parent + parent = item->getRepr()->parent(); + // remember id + id = item->getRepr()->attribute("id"); + } + + // skip those paths whose bboxes are entirely out of reach with our radius + Geom::OptRect bbox = item->documentVisualBounds(); + if (bbox) { + bbox->expandBy(radius); + if (!bbox->contains(p)) { + return false; + } + } + + Path *orig = Path_for_item(item, false); + if (orig == NULL) { + return false; + } + + Path *res = new Path; + res->SetBackData(false); + + Shape *theShape = new Shape; + Shape *theRes = new Shape; + Geom::Affine i2doc(item->i2doc_affine()); + + orig->ConvertWithBackData((0.08 - (0.07 * fidelity)) / i2doc.descrim()); // default 0.059 + orig->Fill(theShape, 0); + + SPCSSAttr *css = sp_repr_css_attr(item->getRepr(), "style"); + gchar const *val = sp_repr_css_property(css, "fill-rule", NULL); + if (val && strcmp(val, "nonzero") == 0) { + theRes->ConvertToShape(theShape, fill_nonZero); + } else if (val && strcmp(val, "evenodd") == 0) { + theRes->ConvertToShape(theShape, fill_oddEven); + } else { + theRes->ConvertToShape(theShape, fill_nonZero); + } + + if (Geom::L2(vector) != 0) { + vector = 1/Geom::L2(vector) * vector; + } + + bool did_this = false; + if (mode == TWEAK_MODE_SHRINK_GROW) { + if (theShape->MakeTweak(tweak_mode_grow, theRes, + reverse? force : -force, + join_straight, 4.0, + true, p, Geom::Point(0,0), radius, &i2doc) == 0) // 0 means the shape was actually changed + did_this = true; + } else if (mode == TWEAK_MODE_ATTRACT_REPEL) { + if (theShape->MakeTweak(tweak_mode_repel, theRes, + reverse? force : -force, + join_straight, 4.0, + true, p, Geom::Point(0,0), radius, &i2doc) == 0) + did_this = true; + } else if (mode == TWEAK_MODE_PUSH) { + if (theShape->MakeTweak(tweak_mode_push, theRes, + 1.0, + join_straight, 4.0, + true, p, force*2*vector, radius, &i2doc) == 0) + did_this = true; + } else if (mode == TWEAK_MODE_ROUGHEN) { + if (theShape->MakeTweak(tweak_mode_roughen, theRes, + force, + join_straight, 4.0, + true, p, Geom::Point(0,0), radius, &i2doc) == 0) + did_this = true; + } + + // the rest only makes sense if we actually changed the path + if (did_this) { + theRes->ConvertToShape(theShape, fill_positive); + + res->Reset(); + theRes->ConvertToForme(res); + + double th_max = (0.6 - 0.59*sqrt(fidelity)) / i2doc.descrim(); + double threshold = MAX(th_max, th_max*force); + res->ConvertEvenLines(threshold); + res->Simplify(threshold / (selection->desktop()->current_zoom())); + + if (newrepr) { // converting to path, need to replace the repr + bool is_selected = selection->includes(item); + if (is_selected) { + selection->remove(item); + } + + // It's going to resurrect, so we delete without notifying listeners. + item->deleteObject(false); + + // restore id + newrepr->setAttribute("id", id); + // add the new repr to the parent + parent->appendChild(newrepr); + // move to the saved position + newrepr->setPosition(pos > 0 ? pos : 0); + + if (is_selected) + selection->add(newrepr); + } + + if (res->descr_cmd.size() > 1) { + gchar *str = res->svg_dump_path(); + if (newrepr) { + newrepr->setAttribute("d", str); + } else { + if (SP_IS_LPE_ITEM(item) && SP_LPE_ITEM(item)->hasPathEffectRecursive()) { + item->getRepr()->setAttribute("inkscape:original-d", str); + } else { + item->getRepr()->setAttribute("d", str); + } + } + g_free(str); + } else { + // TODO: if there's 0 or 1 node left, delete this path altogether + } + + if (newrepr) { + Inkscape::GC::release(newrepr); + newrepr = NULL; + } + } + + delete theShape; + delete theRes; + delete orig; + delete res; + + if (did_this) { + did = true; + } + } + + } + + return did; +} + +static void +tweak_colorpaint (float *color, guint32 goal, double force, bool do_h, bool do_s, bool do_l) +{ + float rgb_g[3]; + + if (!do_h || !do_s || !do_l) { + float hsl_g[3]; + sp_color_rgb_to_hsl_floatv (hsl_g, SP_RGBA32_R_F(goal), SP_RGBA32_G_F(goal), SP_RGBA32_B_F(goal)); + float hsl_c[3]; + sp_color_rgb_to_hsl_floatv (hsl_c, color[0], color[1], color[2]); + if (!do_h) { + hsl_g[0] = hsl_c[0]; + } + if (!do_s) { + hsl_g[1] = hsl_c[1]; + } + if (!do_l) { + hsl_g[2] = hsl_c[2]; + } + sp_color_hsl_to_rgb_floatv (rgb_g, hsl_g[0], hsl_g[1], hsl_g[2]); + } else { + rgb_g[0] = SP_RGBA32_R_F(goal); + rgb_g[1] = SP_RGBA32_G_F(goal); + rgb_g[2] = SP_RGBA32_B_F(goal); + } + + for (int i = 0; i < 3; i++) { + double d = rgb_g[i] - color[i]; + color[i] += d * force; + } +} + +static void +tweak_colorjitter (float *color, double force, bool do_h, bool do_s, bool do_l) +{ + float hsl_c[3]; + sp_color_rgb_to_hsl_floatv (hsl_c, color[0], color[1], color[2]); + + if (do_h) { + hsl_c[0] += g_random_double_range(-0.5, 0.5) * force; + if (hsl_c[0] > 1) { + hsl_c[0] -= 1; + } + if (hsl_c[0] < 0) { + hsl_c[0] += 1; + } + } + if (do_s) { + hsl_c[1] += g_random_double_range(-hsl_c[1], 1 - hsl_c[1]) * force; + } + if (do_l) { + hsl_c[2] += g_random_double_range(-hsl_c[2], 1 - hsl_c[2]) * force; + } + + sp_color_hsl_to_rgb_floatv (color, hsl_c[0], hsl_c[1], hsl_c[2]); +} + +static void +tweak_color (guint mode, float *color, guint32 goal, double force, bool do_h, bool do_s, bool do_l) +{ + if (mode == TWEAK_MODE_COLORPAINT) { + tweak_colorpaint (color, goal, force, do_h, do_s, do_l); + } else if (mode == TWEAK_MODE_COLORJITTER) { + tweak_colorjitter (color, force, do_h, do_s, do_l); + } +} + +static void +tweak_opacity (guint mode, SPIScale24 *style_opacity, double opacity_goal, double force) +{ + double opacity = SP_SCALE24_TO_FLOAT (style_opacity->value); + + if (mode == TWEAK_MODE_COLORPAINT) { + double d = opacity_goal - opacity; + opacity += d * force; + } else if (mode == TWEAK_MODE_COLORJITTER) { + opacity += g_random_double_range(-opacity, 1 - opacity) * force; + } + + style_opacity->value = SP_SCALE24_FROM_FLOAT(opacity); +} + + +static double +tweak_profile (double dist, double radius) +{ + if (radius == 0) { + return 0; + } + double x = dist / radius; + double alpha = 1; + if (x >= 1) { + return 0; + } else if (x <= 0) { + return 1; + } else { + return (0.5 * cos (M_PI * (pow(x, alpha))) + 0.5); + } +} + +static void tweak_colors_in_gradient(SPItem *item, Inkscape::PaintTarget fill_or_stroke, + guint32 const rgb_goal, Geom::Point p_w, double radius, double force, guint mode, + bool do_h, bool do_s, bool do_l, bool /*do_o*/) +{ + SPGradient *gradient = getGradient(item, fill_or_stroke); + + if (!gradient || !SP_IS_GRADIENT(gradient)) { + return; + } + + Geom::Affine i2d (item->i2doc_affine ()); + Geom::Point p = p_w * i2d.inverse(); + p *= (gradient->gradientTransform).inverse(); + // now p is in gradient's original coordinates + + double pos = 0; + double r = 0; + if (SP_IS_LINEARGRADIENT(gradient)) { + SPLinearGradient *lg = SP_LINEARGRADIENT(gradient); + + Geom::Point p1(lg->x1.computed, lg->y1.computed); + Geom::Point p2(lg->x2.computed, lg->y2.computed); + Geom::Point pdiff(p2 - p1); + double vl = Geom::L2(pdiff); + + // This is the matrix which moves and rotates the gradient line + // so it's oriented along the X axis: + Geom::Affine norm = Geom::Affine(Geom::Translate(-p1)) * Geom::Affine(Geom::Rotate(-atan2(pdiff[Geom::Y], pdiff[Geom::X]))); + + // Transform the mouse point by it to find out its projection onto the gradient line: + Geom::Point pnorm = p * norm; + + // Scale its X coordinate to match the length of the gradient line: + pos = pnorm[Geom::X] / vl; + // Calculate radius in lenfth-of-gradient-line units + r = radius / vl; + + } else if (SP_IS_RADIALGRADIENT(gradient)) { + SPRadialGradient *rg = SP_RADIALGRADIENT(gradient); + Geom::Point c (rg->cx.computed, rg->cy.computed); + pos = Geom::L2(p - c) / rg->r.computed; + r = radius / rg->r.computed; + } + + // Normalize pos to 0..1, taking into accound gradient spread: + double pos_e = pos; + if (gradient->getSpread() == SP_GRADIENT_SPREAD_PAD) { + if (pos > 1) { + pos_e = 1; + } + if (pos < 0) { + pos_e = 0; + } + } else if (gradient->getSpread() == SP_GRADIENT_SPREAD_REPEAT) { + if (pos > 1 || pos < 0) { + pos_e = pos - floor(pos); + } + } else if (gradient->getSpread() == SP_GRADIENT_SPREAD_REFLECT) { + if (pos > 1 || pos < 0) { + bool odd = ((int)(floor(pos)) % 2 == 1); + pos_e = pos - floor(pos); + if (odd) { + pos_e = 1 - pos_e; + } + } + } + + SPGradient *vector = sp_gradient_get_forked_vector_if_necessary(gradient, false); + + double offset_l = 0; + double offset_h = 0; + SPObject *child_prev = NULL; + for (SPObject *child = vector->firstChild(); child; child = child->getNext()) { + if (!SP_IS_STOP(child)) { + continue; + } + SPStop *stop = SP_STOP (child); + + offset_h = stop->offset; + + if (child_prev) { + + if (offset_h - offset_l > r && pos_e >= offset_l && pos_e <= offset_h) { + // the summit falls in this interstop, and the radius is small, + // so it only affects the ends of this interstop; + // distribute the force between the two endstops so that they + // get all the painting even if they are not touched by the brush + tweak_color (mode, stop->specified_color.v.c, rgb_goal, + force * (pos_e - offset_l) / (offset_h - offset_l), + do_h, do_s, do_l); + tweak_color (mode, SP_STOP(child_prev)->specified_color.v.c, rgb_goal, + force * (offset_h - pos_e) / (offset_h - offset_l), + do_h, do_s, do_l); + stop->updateRepr(); + child_prev->updateRepr(); + break; + } else { + // wide brush, may affect more than 2 stops, + // paint each stop by the force from the profile curve + if (offset_l <= pos_e && offset_l > pos_e - r) { + tweak_color (mode, SP_STOP(child_prev)->specified_color.v.c, rgb_goal, + force * tweak_profile (fabs (pos_e - offset_l), r), + do_h, do_s, do_l); + child_prev->updateRepr(); + } + + if (offset_h >= pos_e && offset_h < pos_e + r) { + tweak_color (mode, stop->specified_color.v.c, rgb_goal, + force * tweak_profile (fabs (pos_e - offset_h), r), + do_h, do_s, do_l); + stop->updateRepr(); + } + } + } + + offset_l = offset_h; + child_prev = child; + } +} + +static bool +sp_tweak_color_recursive (guint mode, SPItem *item, SPItem *item_at_point, + guint32 fill_goal, bool do_fill, + guint32 stroke_goal, bool do_stroke, + float opacity_goal, bool do_opacity, + bool do_blur, bool reverse, + Geom::Point p, double radius, double force, + bool do_h, bool do_s, bool do_l, bool do_o) +{ + bool did = false; + + if (SP_IS_GROUP(item)) { + for (SPObject *child = item->firstChild() ; child; child = child->getNext() ) { + if (SP_IS_ITEM(child)) { + if (sp_tweak_color_recursive (mode, SP_ITEM(child), item_at_point, + fill_goal, do_fill, + stroke_goal, do_stroke, + opacity_goal, do_opacity, + do_blur, reverse, + p, radius, force, do_h, do_s, do_l, do_o)) { + did = true; + } + } + } + + } else { + SPStyle *style = item->style; + if (!style) { + return false; + } + Geom::OptRect bbox = item->documentGeometricBounds(); + if (!bbox) { + return false; + } + + Geom::Rect brush(p - Geom::Point(radius, radius), p + Geom::Point(radius, radius)); + + Geom::Point center = bbox->midpoint(); + double this_force; + +// if item == item_at_point, use max force + if (item == item_at_point) { + this_force = force; +// else if no overlap of bbox and brush box, skip: + } else if (!bbox->intersects(brush)) { + return false; +//TODO: +// else if object > 1.5 brush: test 4/8/16 points in the brush on hitting the object, choose max + //} else if (bbox->maxExtent() > 3 * radius) { + //} +// else if object > 0.5 brush: test 4 corners of bbox and center on being in the brush, choose max +// else if still smaller, then check only the object center: + } else { + this_force = force * tweak_profile (Geom::L2 (p - center), radius); + } + + if (this_force > 0.002) { + + if (do_blur) { + Geom::OptRect bbox = item->documentGeometricBounds(); + if (!bbox) { + return did; + } + + double blur_now = 0; + Geom::Affine i2dt = item->i2dt_affine (); + if (style->filter.set && style->getFilter()) { + //cycle through filter primitives + SPObject *primitive_obj = style->getFilter()->children; + while (primitive_obj) { + if (SP_IS_FILTER_PRIMITIVE(primitive_obj)) { + SPFilterPrimitive *primitive = SP_FILTER_PRIMITIVE(primitive_obj); + //if primitive is gaussianblur + if(SP_IS_GAUSSIANBLUR(primitive)) { + SPGaussianBlur * spblur = SP_GAUSSIANBLUR(primitive); + float num = spblur->stdDeviation.getNumber(); + blur_now += num * i2dt.descrim(); // sum all blurs in the filter + } + } + primitive_obj = primitive_obj->next; + } + } + double perimeter = bbox->dimensions()[Geom::X] + bbox->dimensions()[Geom::Y]; + blur_now = blur_now / perimeter; + + double blur_new; + if (reverse) { + blur_new = blur_now - 0.06 * force; + } else { + blur_new = blur_now + 0.06 * force; + } + if (blur_new < 0.0005 && blur_new < blur_now) { + blur_new = 0; + } + if (blur_new == 0) { + remove_filter(item, false); + } else { + double radius = blur_new * perimeter; + SPFilter *filter = modify_filter_gaussian_blur_from_item(item->document, item, radius); + sp_style_set_property_url(item, "filter", filter, false); + } + return true; // do not do colors, blur is a separate mode + } + + if (do_fill) { + if (style->fill.isPaintserver()) { + tweak_colors_in_gradient(item, Inkscape::FOR_FILL, fill_goal, p, radius, this_force, mode, do_h, do_s, do_l, do_o); + did = true; + } else if (style->fill.isColor()) { + tweak_color (mode, style->fill.value.color.v.c, fill_goal, this_force, do_h, do_s, do_l); + item->updateRepr(); + did = true; + } + } + if (do_stroke) { + if (style->stroke.isPaintserver()) { + tweak_colors_in_gradient(item, Inkscape::FOR_STROKE, stroke_goal, p, radius, this_force, mode, do_h, do_s, do_l, do_o); + did = true; + } else if (style->stroke.isColor()) { + tweak_color (mode, style->stroke.value.color.v.c, stroke_goal, this_force, do_h, do_s, do_l); + item->updateRepr(); + did = true; + } + } + if (do_opacity && do_o) { + tweak_opacity (mode, &style->opacity, opacity_goal, this_force); + } + } + } + + return did; +} + + +static bool +sp_tweak_dilate (TweakTool *tc, Geom::Point event_p, Geom::Point p, Geom::Point vector, bool reverse) +{ + Inkscape::Selection *selection = sp_desktop_selection(SP_EVENT_CONTEXT(tc)->desktop); + SPDesktop *desktop = SP_EVENT_CONTEXT(tc)->desktop; + + if (selection->isEmpty()) { + return false; + } + + bool did = false; + double radius = get_dilate_radius(tc); + + SPItem *item_at_point = SP_EVENT_CONTEXT(tc)->desktop->getItemAtPoint(event_p, TRUE); + + bool do_fill = false, do_stroke = false, do_opacity = false; + guint32 fill_goal = sp_desktop_get_color_tool(desktop, "/tools/tweak", true, &do_fill); + guint32 stroke_goal = sp_desktop_get_color_tool(desktop, "/tools/tweak", false, &do_stroke); + double opacity_goal = sp_desktop_get_master_opacity_tool(desktop, "/tools/tweak", &do_opacity); + if (reverse) { +#if 0 + // HSL inversion + float hsv[3]; + float rgb[3]; + sp_color_rgb_to_hsv_floatv (hsv, + SP_RGBA32_R_F(fill_goal), + SP_RGBA32_G_F(fill_goal), + SP_RGBA32_B_F(fill_goal)); + sp_color_hsv_to_rgb_floatv (rgb, hsv[0]<.5? hsv[0]+.5 : hsv[0]-.5, 1 - hsv[1], 1 - hsv[2]); + fill_goal = SP_RGBA32_F_COMPOSE(rgb[0], rgb[1], rgb[2], 1); + sp_color_rgb_to_hsv_floatv (hsv, + SP_RGBA32_R_F(stroke_goal), + SP_RGBA32_G_F(stroke_goal), + SP_RGBA32_B_F(stroke_goal)); + sp_color_hsv_to_rgb_floatv (rgb, hsv[0]<.5? hsv[0]+.5 : hsv[0]-.5, 1 - hsv[1], 1 - hsv[2]); + stroke_goal = SP_RGBA32_F_COMPOSE(rgb[0], rgb[1], rgb[2], 1); +#else + // RGB inversion + fill_goal = SP_RGBA32_U_COMPOSE( + (255 - SP_RGBA32_R_U(fill_goal)), + (255 - SP_RGBA32_G_U(fill_goal)), + (255 - SP_RGBA32_B_U(fill_goal)), + (255 - SP_RGBA32_A_U(fill_goal))); + stroke_goal = SP_RGBA32_U_COMPOSE( + (255 - SP_RGBA32_R_U(stroke_goal)), + (255 - SP_RGBA32_G_U(stroke_goal)), + (255 - SP_RGBA32_B_U(stroke_goal)), + (255 - SP_RGBA32_A_U(stroke_goal))); +#endif + opacity_goal = 1 - opacity_goal; + } + + double path_force = get_path_force(tc); + if (radius == 0 || path_force == 0) { + return false; + } + double move_force = get_move_force(tc); + double color_force = MIN(sqrt(path_force)/20.0, 1); + + for (GSList *items = g_slist_copy(const_cast<GSList *>(selection->itemList())); + items != NULL; + items = items->next) { + + SPItem *item = SP_ITEM(items->data); + + if (is_color_mode (tc->mode)) { + if (do_fill || do_stroke || do_opacity) { + if (sp_tweak_color_recursive (tc->mode, item, item_at_point, + fill_goal, do_fill, + stroke_goal, do_stroke, + opacity_goal, do_opacity, + tc->mode == TWEAK_MODE_BLUR, reverse, + p, radius, color_force, tc->do_h, tc->do_s, tc->do_l, tc->do_o)) { + did = true; + } + } + } else if (is_transform_mode(tc->mode)) { + if (sp_tweak_dilate_recursive (selection, item, p, vector, tc->mode, radius, move_force, tc->fidelity, reverse)) { + did = true; + } + } else { + if (sp_tweak_dilate_recursive (selection, item, p, vector, tc->mode, radius, path_force, tc->fidelity, reverse)) { + did = true; + } + } + } + + return did; +} + +static void +sp_tweak_update_area (TweakTool *tc) +{ + double radius = get_dilate_radius(tc); + Geom::Affine const sm (Geom::Scale(radius, radius) * Geom::Translate(SP_EVENT_CONTEXT(tc)->desktop->point())); + sp_canvas_item_affine_absolute(tc->dilate_area, sm); + sp_canvas_item_show(tc->dilate_area); +} + +static void +sp_tweak_switch_mode (TweakTool *tc, gint mode, bool with_shift) +{ + SP_EVENT_CONTEXT(tc)->desktop->setToolboxSelectOneValue ("tweak_tool_mode", mode); + // need to set explicitly, because the prefs may not have changed by the previous + tc->mode = mode; + tc->update_cursor(with_shift); +} + +static void +sp_tweak_switch_mode_temporarily (TweakTool *tc, gint mode, bool with_shift) +{ + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + // Juggling about so that prefs have the old value but tc->mode and the button show new mode: + gint now_mode = prefs->getInt("/tools/tweak/mode", 0); + SP_EVENT_CONTEXT(tc)->desktop->setToolboxSelectOneValue ("tweak_tool_mode", mode); + // button has changed prefs, restore + prefs->setInt("/tools/tweak/mode", now_mode); + // changing prefs changed tc->mode, restore back :) + tc->mode = mode; + tc->update_cursor(with_shift); +} + +bool TweakTool::root_handler(GdkEvent* event) { + gint ret = FALSE; + + switch (event->type) { + case GDK_ENTER_NOTIFY: + sp_canvas_item_show(this->dilate_area); + break; + case GDK_LEAVE_NOTIFY: + sp_canvas_item_hide(this->dilate_area); + break; + case GDK_BUTTON_PRESS: + if (event->button.button == 1 && !this->space_panning) { + + if (Inkscape::have_viable_layer(desktop, this->message_context) == false) { + return TRUE; + } + + Geom::Point const button_w(event->button.x, + event->button.y); + Geom::Point const button_dt(desktop->w2d(button_w)); + this->last_push = desktop->dt2doc(button_dt); + + sp_tweak_extinput(this, event); + + desktop->canvas->forceFullRedrawAfterInterruptions(3); + this->is_drawing = true; + this->is_dilating = true; + this->has_dilated = false; + + ret = TRUE; + } + break; + case GDK_MOTION_NOTIFY: + { + Geom::Point const motion_w(event->motion.x, + event->motion.y); + Geom::Point motion_dt(desktop->w2d(motion_w)); + Geom::Point motion_doc(desktop->dt2doc(motion_dt)); + sp_tweak_extinput(this, event); + + // draw the dilating cursor + double radius = get_dilate_radius(this); + Geom::Affine const sm (Geom::Scale(radius, radius) * Geom::Translate(desktop->w2d(motion_w))); + sp_canvas_item_affine_absolute(this->dilate_area, sm); + sp_canvas_item_show(this->dilate_area); + + guint num = 0; + if (!desktop->selection->isEmpty()) { + num = g_slist_length(const_cast<GSList *>(desktop->selection->itemList())); + } + if (num == 0) { + this->message_context->flash(Inkscape::ERROR_MESSAGE, _("<b>Nothing selected!</b> Select objects to tweak.")); + } + + // dilating: + if (this->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK )) { + sp_tweak_dilate (this, motion_w, motion_doc, motion_doc - this->last_push, event->button.state & GDK_SHIFT_MASK? true : false); + //this->last_push = motion_doc; + this->has_dilated = true; + // it's slow, so prevent clogging up with events + gobble_motion_events(GDK_BUTTON1_MASK); + return TRUE; + } + + } + break; + case GDK_BUTTON_RELEASE: + { + Geom::Point const motion_w(event->button.x, event->button.y); + Geom::Point const motion_dt(desktop->w2d(motion_w)); + + desktop->canvas->endForcedFullRedraws(); + this->is_drawing = false; + + if (this->is_dilating && event->button.button == 1 && !this->space_panning) { + if (!this->has_dilated) { + // if we did not rub, do a light tap + this->pressure = 0.03; + sp_tweak_dilate (this, motion_w, desktop->dt2doc(motion_dt), Geom::Point(0,0), MOD__SHIFT(event)); + } + this->is_dilating = false; + this->has_dilated = false; + switch (this->mode) { + case TWEAK_MODE_MOVE: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_TWEAK, _("Move tweak")); + break; + case TWEAK_MODE_MOVE_IN_OUT: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_TWEAK, _("Move in/out tweak")); + break; + case TWEAK_MODE_MOVE_JITTER: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_TWEAK, _("Move jitter tweak")); + break; + case TWEAK_MODE_SCALE: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_TWEAK, _("Scale tweak")); + break; + case TWEAK_MODE_ROTATE: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_TWEAK, _("Rotate tweak")); + break; + case TWEAK_MODE_MORELESS: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_TWEAK, _("Duplicate/delete tweak")); + break; + case TWEAK_MODE_PUSH: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_TWEAK, _("Push path tweak")); + break; + case TWEAK_MODE_SHRINK_GROW: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_TWEAK, _("Shrink/grow path tweak")); + break; + case TWEAK_MODE_ATTRACT_REPEL: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_TWEAK, _("Attract/repel path tweak")); + break; + case TWEAK_MODE_ROUGHEN: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_TWEAK, _("Roughen path tweak")); + break; + case TWEAK_MODE_COLORPAINT: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_TWEAK, _("Color paint tweak")); + break; + case TWEAK_MODE_COLORJITTER: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_TWEAK, _("Color jitter tweak")); + break; + case TWEAK_MODE_BLUR: + DocumentUndo::done(sp_desktop_document(SP_EVENT_CONTEXT(this)->desktop), + SP_VERB_CONTEXT_TWEAK, _("Blur tweak")); + break; + } + } + break; + } + case GDK_KEY_PRESS: + { + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_m: + case GDK_KEY_M: + case GDK_KEY_0: + if (MOD__SHIFT_ONLY(event)) { + sp_tweak_switch_mode(this, TWEAK_MODE_MOVE, MOD__SHIFT(event)); + ret = TRUE; + } + break; + case GDK_KEY_i: + case GDK_KEY_I: + case GDK_KEY_1: + if (MOD__SHIFT_ONLY(event)) { + sp_tweak_switch_mode(this, TWEAK_MODE_MOVE_IN_OUT, MOD__SHIFT(event)); + ret = TRUE; + } + break; + case GDK_KEY_z: + case GDK_KEY_Z: + case GDK_KEY_2: + if (MOD__SHIFT_ONLY(event)) { + sp_tweak_switch_mode(this, TWEAK_MODE_MOVE_JITTER, MOD__SHIFT(event)); + ret = TRUE; + } + break; + case GDK_KEY_less: + case GDK_KEY_comma: + case GDK_KEY_greater: + case GDK_KEY_period: + case GDK_KEY_3: + if (MOD__SHIFT_ONLY(event)) { + sp_tweak_switch_mode(this, TWEAK_MODE_SCALE, MOD__SHIFT(event)); + ret = TRUE; + } + break; + case GDK_KEY_bracketright: + case GDK_KEY_bracketleft: + case GDK_KEY_4: + if (MOD__SHIFT_ONLY(event)) { + sp_tweak_switch_mode(this, TWEAK_MODE_ROTATE, MOD__SHIFT(event)); + ret = TRUE; + } + break; + case GDK_KEY_d: + case GDK_KEY_D: + case GDK_KEY_5: + if (MOD__SHIFT_ONLY(event)) { + sp_tweak_switch_mode(this, TWEAK_MODE_MORELESS, MOD__SHIFT(event)); + ret = TRUE; + } + break; + case GDK_KEY_p: + case GDK_KEY_P: + case GDK_KEY_6: + if (MOD__SHIFT_ONLY(event)) { + sp_tweak_switch_mode(this, TWEAK_MODE_PUSH, MOD__SHIFT(event)); + ret = TRUE; + } + break; + case GDK_KEY_s: + case GDK_KEY_S: + case GDK_KEY_7: + if (MOD__SHIFT_ONLY(event)) { + sp_tweak_switch_mode(this, TWEAK_MODE_SHRINK_GROW, MOD__SHIFT(event)); + ret = TRUE; + } + break; + case GDK_KEY_a: + case GDK_KEY_A: + case GDK_KEY_8: + if (MOD__SHIFT_ONLY(event)) { + sp_tweak_switch_mode(this, TWEAK_MODE_ATTRACT_REPEL, MOD__SHIFT(event)); + ret = TRUE; + } + break; + case GDK_KEY_r: + case GDK_KEY_R: + case GDK_KEY_9: + if (MOD__SHIFT_ONLY(event)) { + sp_tweak_switch_mode(this, TWEAK_MODE_ROUGHEN, MOD__SHIFT(event)); + ret = TRUE; + } + break; + case GDK_KEY_c: + case GDK_KEY_C: + if (MOD__SHIFT_ONLY(event)) { + sp_tweak_switch_mode(this, TWEAK_MODE_COLORPAINT, MOD__SHIFT(event)); + ret = TRUE; + } + break; + case GDK_KEY_j: + case GDK_KEY_J: + if (MOD__SHIFT_ONLY(event)) { + sp_tweak_switch_mode(this, TWEAK_MODE_COLORJITTER, MOD__SHIFT(event)); + ret = TRUE; + } + break; + case GDK_KEY_b: + case GDK_KEY_B: + if (MOD__SHIFT_ONLY(event)) { + sp_tweak_switch_mode(this, TWEAK_MODE_BLUR, MOD__SHIFT(event)); + ret = TRUE; + } + break; + + case GDK_KEY_Up: + case GDK_KEY_KP_Up: + if (!MOD__CTRL_ONLY(event)) { + this->force += 0.05; + if (this->force > 1.0) { + this->force = 1.0; + } + desktop->setToolboxAdjustmentValue ("tweak-force", this->force * 100); + ret = TRUE; + } + break; + case GDK_KEY_Down: + case GDK_KEY_KP_Down: + if (!MOD__CTRL_ONLY(event)) { + this->force -= 0.05; + if (this->force < 0.0) { + this->force = 0.0; + } + desktop->setToolboxAdjustmentValue ("tweak-force", this->force * 100); + ret = TRUE; + } + break; + case GDK_KEY_Right: + case GDK_KEY_KP_Right: + if (!MOD__CTRL_ONLY(event)) { + this->width += 0.01; + if (this->width > 1.0) { + this->width = 1.0; + } + desktop->setToolboxAdjustmentValue ("altx-tweak", this->width * 100); // the same spinbutton is for alt+x + sp_tweak_update_area(this); + ret = TRUE; + } + break; + case GDK_KEY_Left: + case GDK_KEY_KP_Left: + if (!MOD__CTRL_ONLY(event)) { + this->width -= 0.01; + if (this->width < 0.01) { + this->width = 0.01; + } + desktop->setToolboxAdjustmentValue ("altx-tweak", this->width * 100); + sp_tweak_update_area(this); + ret = TRUE; + } + break; + case GDK_KEY_Home: + case GDK_KEY_KP_Home: + this->width = 0.01; + desktop->setToolboxAdjustmentValue ("altx-tweak", this->width * 100); + sp_tweak_update_area(this); + ret = TRUE; + break; + case GDK_KEY_End: + case GDK_KEY_KP_End: + this->width = 1.0; + desktop->setToolboxAdjustmentValue ("altx-tweak", this->width * 100); + sp_tweak_update_area(this); + ret = TRUE; + break; + case GDK_KEY_x: + case GDK_KEY_X: + if (MOD__ALT_ONLY(event)) { + desktop->setToolboxFocusTo ("altx-tweak"); + ret = TRUE; + } + break; + + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + this->update_cursor(true); + break; + + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + sp_tweak_switch_mode_temporarily(this, TWEAK_MODE_SHRINK_GROW, MOD__SHIFT(event)); + break; + case GDK_KEY_Delete: + case GDK_KEY_KP_Delete: + case GDK_KEY_BackSpace: + ret = this->deleteSelectedDrag(MOD__CTRL_ONLY(event)); + break; + + default: + break; + } + break; + } + case GDK_KEY_RELEASE: { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + switch (get_group0_keyval(&event->key)) { + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + this->update_cursor(false); + break; + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + sp_tweak_switch_mode (this, prefs->getInt("/tools/tweak/mode"), MOD__SHIFT(event)); + this->message_context->clear(); + break; + default: + sp_tweak_switch_mode (this, prefs->getInt("/tools/tweak/mode"), MOD__SHIFT(event)); + break; + } + } + default: + break; + } + + if (!ret) { + ret = ToolBase::root_handler(event); + } + + return ret; +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/tweak-tool.h b/src/ui/tools/tweak-tool.h new file mode 100644 index 000000000..7fe4b1856 --- /dev/null +++ b/src/ui/tools/tweak-tool.h @@ -0,0 +1,106 @@ +#ifndef __SP_TWEAK_CONTEXT_H__ +#define __SP_TWEAK_CONTEXT_H__ + +/* + * tweaking paths without node editing + * + * Authors: + * bulia byak + * + * Copyright (C) 2007 authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "ui/tools/tool-base.h" +#include <2geom/point.h> + +#define SAMPLING_SIZE 8 /* fixme: ?? */ + +#define TC_MIN_PRESSURE 0.0 +#define TC_MAX_PRESSURE 1.0 +#define TC_DEFAULT_PRESSURE 0.35 + +namespace Inkscape { +namespace UI { +namespace Tools { + +enum { + TWEAK_MODE_MOVE, + TWEAK_MODE_MOVE_IN_OUT, + TWEAK_MODE_MOVE_JITTER, + TWEAK_MODE_SCALE, + TWEAK_MODE_ROTATE, + TWEAK_MODE_MORELESS, + TWEAK_MODE_PUSH, + TWEAK_MODE_SHRINK_GROW, + TWEAK_MODE_ATTRACT_REPEL, + TWEAK_MODE_ROUGHEN, + TWEAK_MODE_COLORPAINT, + TWEAK_MODE_COLORJITTER, + TWEAK_MODE_BLUR +}; + +class TweakTool : public ToolBase { +public: + TweakTool(); + virtual ~TweakTool(); + + /* extended input data */ + gdouble pressure; + + /* attributes */ + bool dragging; /* mouse state: mouse is dragging */ + bool usepressure; + bool usetilt; + + double width; + double force; + double fidelity; + + gint mode; + + bool is_drawing; + + bool is_dilating; + bool has_dilated; + Geom::Point last_push; + SPCanvasItem *dilate_area; + + bool do_h; + bool do_s; + bool do_l; + bool do_o; + + sigc::connection style_set_connection; + + static const std::string prefsPath; + + virtual void setup(); + virtual void set(const Inkscape::Preferences::Entry& val); + virtual bool root_handler(GdkEvent* event); + + virtual const std::string& getPrefsPath(); + + void update_cursor(bool with_shift); + +private: + bool set_style(const SPCSSAttr* css); +}; + +} +} +} + +#endif + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/tools/zoom-tool.cpp b/src/ui/tools/zoom-tool.cpp new file mode 100644 index 000000000..9f99cfe2e --- /dev/null +++ b/src/ui/tools/zoom-tool.cpp @@ -0,0 +1,251 @@ +/* + * Handy zooming tool + * + * Authors: + * Lauris Kaplinski <lauris@kaplinski.com> + * Frank Felfe <innerspace@iname.com> + * bulia byak <buliabyak@users.sf.net> + * + * Copyright (C) 1999-2002 Authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + + +#include <gdk/gdkkeysyms.h> + +#include "macros.h" +#include "rubberband.h" +#include "display/sp-canvas-item.h" +#include "display/sp-canvas-util.h" +#include "desktop.h" +#include "pixmaps/cursor-zoom.xpm" +#include "pixmaps/cursor-zoom-out.xpm" +#include "preferences.h" +#include "selection-chemistry.h" + +#include "ui/tools/zoom-tool.h" +#include "tool-factory.h" + +namespace Inkscape { +namespace UI { +namespace Tools { + +namespace { + ToolBase* createZoomContext() { + return new ZoomTool(); + } + + bool zoomContextRegistered = ToolFactory::instance().registerObject("/tools/zoom", createZoomContext); +} + +const std::string& ZoomTool::getPrefsPath() { + return ZoomTool::prefsPath; +} + +const std::string ZoomTool::prefsPath = "/tools/zoom"; + +ZoomTool::ZoomTool() + : ToolBase(cursor_zoom_xpm, 6, 6) + , grabbed(NULL) + , escaped(false) +{ +} + +ZoomTool::~ZoomTool() { +} + +void ZoomTool::finish() { + this->enableGrDrag(false); + + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed, GDK_CURRENT_TIME); + this->grabbed = NULL; + } + + ToolBase::finish(); +} + +void ZoomTool::setup() { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + if (prefs->getBool("/tools/zoom/selcue")) { + this->enableSelectionCue(); + } + + if (prefs->getBool("/tools/zoom/gradientdrag")) { + this->enableGrDrag(); + } + + ToolBase::setup(); +} + +bool ZoomTool::root_handler(GdkEvent* event) { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + + tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100); + double const zoom_inc = prefs->getDoubleLimited("/options/zoomincrement/value", M_SQRT2, 1.01, 10); + + bool ret = false; + + switch (event->type) { + case GDK_BUTTON_PRESS: + { + Geom::Point const button_w(event->button.x, event->button.y); + Geom::Point const button_dt(desktop->w2d(button_w)); + + if (event->button.button == 1 && !this->space_panning) { + // save drag origin + xp = (gint) event->button.x; + yp = (gint) event->button.y; + within_tolerance = true; + + Inkscape::Rubberband::get(desktop)->start(desktop, button_dt); + + escaped = false; + + ret = true; + } else if (event->button.button == 3) { + double const zoom_rel( (event->button.state & GDK_SHIFT_MASK) + ? zoom_inc + : 1 / zoom_inc ); + + desktop->zoom_relative_keep_point(button_dt, zoom_rel); + ret = true; + } + + sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate), + GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK, + NULL, event->button.time); + + this->grabbed = SP_CANVAS_ITEM(desktop->acetate); + break; + } + + case GDK_MOTION_NOTIFY: + if ((event->motion.state & GDK_BUTTON1_MASK) && !this->space_panning) { + ret = true; + + if ( within_tolerance + && ( abs( (gint) event->motion.x - xp ) < tolerance ) + && ( abs( (gint) event->motion.y - yp ) < tolerance ) ) { + break; // do not drag if we're within tolerance from origin + } + // Once the user has moved farther than tolerance from the original location + // (indicating they intend to move the object, not click), then always process the + // motion notify coordinates as given (no snapping back to origin) + within_tolerance = false; + + Geom::Point const motion_w(event->motion.x, event->motion.y); + Geom::Point const motion_dt(desktop->w2d(motion_w)); + Inkscape::Rubberband::get(desktop)->move(motion_dt); + gobble_motion_events(GDK_BUTTON1_MASK); + } + break; + + case GDK_BUTTON_RELEASE: + { + Geom::Point const button_w(event->button.x, event->button.y); + Geom::Point const button_dt(desktop->w2d(button_w)); + + if ( event->button.button == 1 && !this->space_panning) { + Geom::OptRect const b = Inkscape::Rubberband::get(desktop)->getRectangle(); + + if (b && !within_tolerance) { + desktop->set_display_area(*b, 10); + } else if (!escaped) { + double const zoom_rel( (event->button.state & GDK_SHIFT_MASK) + ? 1 / zoom_inc + : zoom_inc ); + + desktop->zoom_relative_keep_point(button_dt, zoom_rel); + } + + ret = true; + } + + Inkscape::Rubberband::get(desktop)->stop(); + + if (this->grabbed) { + sp_canvas_item_ungrab(this->grabbed, event->button.time); + this->grabbed = NULL; + } + + xp = yp = 0; + escaped = false; + break; + } + case GDK_KEY_PRESS: + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Escape: + if (!Inkscape::Rubberband::get(desktop)->is_started()) { + Inkscape::SelectionHelper::selectNone(desktop); + } + + Inkscape::Rubberband::get(desktop)->stop(); + xp = yp = 0; + escaped = true; + ret = true; + break; + + case GDK_KEY_Up: + case GDK_KEY_Down: + case GDK_KEY_KP_Up: + case GDK_KEY_KP_Down: + // prevent the zoom field from activation + if (!MOD__CTRL_ONLY(event)) + ret = true; + break; + + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + this->cursor_shape = cursor_zoom_out_xpm; + this->sp_event_context_update_cursor(); + break; + + case GDK_KEY_Delete: + case GDK_KEY_KP_Delete: + case GDK_KEY_BackSpace: + ret = this->deleteSelectedDrag(MOD__CTRL_ONLY(event)); + break; + + default: + break; + } + break; + case GDK_KEY_RELEASE: + switch (get_group0_keyval (&event->key)) { + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + this->cursor_shape = cursor_zoom_xpm; + this->sp_event_context_update_cursor(); + break; + default: + break; + } + break; + default: + break; + } + + if (!ret) { + ret = ToolBase::root_handler(event); + } + + return ret; +} + +} +} +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/tools/zoom-tool.h b/src/ui/tools/zoom-tool.h new file mode 100644 index 000000000..6e5cca7aa --- /dev/null +++ b/src/ui/tools/zoom-tool.h @@ -0,0 +1,47 @@ +#ifndef __SP_ZOOM_CONTEXT_H__ +#define __SP_ZOOM_CONTEXT_H__ + +/* + * Handy zooming tool + * + * Authors: + * Lauris Kaplinski <lauris@kaplinski.com> + * Frank Felfe <innerspace@iname.com> + * + * Copyright (C) 1999-2002 Authors + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "ui/tools/tool-base.h" + +#define SP_ZOOM_CONTEXT(obj) (dynamic_cast<Inkscape::UI::Tools::ZoomTool*>((Inkscape::UI::Tools::ToolBase*)obj)) +#define SP_IS_ZOOM_CONTEXT(obj) (dynamic_cast<const Inkscape::UI::Tools::ZoomTool*>((const Inkscape::UI::Tools::ToolBase*)obj) != NULL) + +namespace Inkscape { +namespace UI { +namespace Tools { + +class ZoomTool : public ToolBase { +public: + ZoomTool(); + virtual ~ZoomTool(); + + static const std::string prefsPath; + + virtual void setup(); + virtual void finish(); + virtual bool root_handler(GdkEvent* event); + + virtual const std::string& getPrefsPath(); + +private: + SPCanvasItem *grabbed; + bool escaped; +}; + +} +} +} + +#endif diff --git a/src/ui/uxmanager.h b/src/ui/uxmanager.h index 5fef08f11..711703192 100644 --- a/src/ui/uxmanager.h +++ b/src/ui/uxmanager.h @@ -11,20 +11,13 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ -#include <glib.h> #include <vector> +#include <glib.h> -extern "C" -{ - typedef struct _GObject GObject; - typedef struct _GtkWidget GtkWidget; -} - +extern "C" typedef struct _GtkWidget GtkWidget; class SPDesktop; - struct SPDesktopWidget; - namespace Inkscape { namespace UI { diff --git a/src/ui/view/edit-widget-interface.h b/src/ui/view/edit-widget-interface.h index 2426fa5b1..55683871d 100644 --- a/src/ui/view/edit-widget-interface.h +++ b/src/ui/view/edit-widget-interface.h @@ -101,9 +101,6 @@ struct EditWidgetInterface /// Update the "inactive desktop" indicator virtual void deactivateDesktop() = 0; - /// Set rulers to position - virtual void viewSetPosition (Geom::Point p) = 0; - /// Update rulers from current values virtual void updateRulers() = 0; @@ -119,6 +116,9 @@ struct EditWidgetInterface /// Toggle CMS on/off and set preference value accordingly virtual void toggleColorProfAdjust() = 0; + /// Is CMS on/off + virtual bool colorProfAdjustEnabled() = 0; + /// Temporarily block signals and update zoom display virtual void updateZoom() = 0; @@ -148,7 +148,7 @@ struct EditWidgetInterface virtual bool showInfoDialog( Glib::ustring const &message ) = 0; /// Open yes/no dialog with warning text and confirmation question. - virtual bool warnDialog (gchar*) = 0; + virtual bool warnDialog (Glib::ustring const &) = 0; virtual Inkscape::UI::Widget::Dock* getDock () = 0; }; diff --git a/src/ui/view/view-widget.cpp b/src/ui/view/view-widget.cpp index 7876928f7..5cb0df215 100644 --- a/src/ui/view/view-widget.cpp +++ b/src/ui/view/view-widget.cpp @@ -18,7 +18,7 @@ static void sp_view_widget_class_init(SPViewWidgetClass *vwc); static void sp_view_widget_init(SPViewWidget *widget); -static void sp_view_widget_destroy(GtkObject *object); +static void sp_view_widget_dispose(GObject *object); static GtkEventBoxClass *widget_parent_class; @@ -47,11 +47,11 @@ GType sp_view_widget_get_type(void) */ static void sp_view_widget_class_init(SPViewWidgetClass *vwc) { - GtkObjectClass *object_class = GTK_OBJECT_CLASS(vwc); + GObjectClass *object_class = G_OBJECT_CLASS(vwc); widget_parent_class = (GtkEventBoxClass*) g_type_class_peek_parent(vwc); - object_class->destroy = sp_view_widget_destroy; + object_class->dispose = sp_view_widget_dispose; } /** @@ -67,7 +67,7 @@ static void sp_view_widget_init(SPViewWidget *vw) * * Apparently, this gets only called when a desktop is closed, but then twice! */ -static void sp_view_widget_destroy(GtkObject *object) +static void sp_view_widget_dispose(GObject *object) { SPViewWidget *vw = SP_VIEW_WIDGET(object); @@ -77,8 +77,8 @@ static void sp_view_widget_destroy(GtkObject *object) vw->view = NULL; } - if (((GtkObjectClass *) (widget_parent_class))->destroy) { - (* ((GtkObjectClass *) (widget_parent_class))->destroy)(object); + if (((GObjectClass *) (widget_parent_class))->dispose) { + (* ((GObjectClass *) (widget_parent_class))->dispose)(object); } Inkscape::GC::request_early_collection(); diff --git a/src/ui/view/view.cpp b/src/ui/view/view.cpp index e13976cc4..72548e213 100644 --- a/src/ui/view/view.cpp +++ b/src/ui/view/view.cpp @@ -27,12 +27,6 @@ namespace UI { namespace View { static void -_onPositionSet (double x, double y, View* v) -{ - v->onPositionSet (x,y); -} - -static void _onResized (double x, double y, View* v) { v->onResized (x,y); @@ -69,7 +63,6 @@ View::View() _message_stack = GC::release(new Inkscape::MessageStack()); _tips_message_context = new Inkscape::MessageContext(_message_stack); - _position_set_connection = _position_set_signal.connect (sigc::bind (sigc::ptr_fun (&_onPositionSet), this)); _resized_connection = _resized_signal.connect (sigc::bind (sigc::ptr_fun (&_onResized), this)); _redraw_requested_connection = _redraw_requested_signal.connect (sigc::bind (sigc::ptr_fun (&_onRedrawRequested), this)); @@ -102,16 +95,6 @@ void View::_close() { Inkscape::Verb::delete_all_view (this); } -void View::setPosition (double x, double y) -{ - _position_set_signal.emit (x,y); -} - -void View::setPosition(Geom::Point const &p) -{ - setPosition (double(p[Geom::X]), double(p[Geom::Y])); -} - void View::emitResized (double width, double height) { _resized_signal.emit (width, height); diff --git a/src/ui/view/view.h b/src/ui/view/view.h index 6ed9f476c..48f4d2549 100644 --- a/src/ui/view/view.h +++ b/src/ui/view/view.h @@ -90,8 +90,6 @@ public: Inkscape::MessageContext *tipsMessageContext() const { return _tips_message_context; } - void setPosition(gdouble x, gdouble y); - void setPosition(Geom::Point const &p); void emitResized(gdouble width, gdouble height); void requestRedraw(); @@ -101,7 +99,6 @@ public: virtual void mouseover() = 0; virtual void mouseout() = 0; - virtual void onPositionSet (double, double) = 0; virtual void onResized (double, double) = 0; virtual void onRedrawRequested() = 0; virtual void onStatusMessage (Inkscape::MessageType type, gchar const *message) = 0; @@ -126,13 +123,11 @@ protected: */ virtual void setDocument(SPDocument *doc); - sigc::signal<void,double,double> _position_set_signal; sigc::signal<void,double,double> _resized_signal; sigc::signal<void,gchar const*> _document_uri_set_signal; sigc::signal<void> _redraw_requested_signal; private: - sigc::connection _position_set_connection; sigc::connection _resized_connection; sigc::connection _redraw_requested_connection; sigc::connection _message_changed_connection; // foreign diff --git a/src/ui/widget/Makefile_insert b/src/ui/widget/Makefile_insert index f36ffbf56..608dd5334 100644 --- a/src/ui/widget/Makefile_insert +++ b/src/ui/widget/Makefile_insert @@ -21,12 +21,12 @@ ink_common_sources += \ ui/widget/entry.h \ ui/widget/filter-effect-chooser.h \ ui/widget/filter-effect-chooser.cpp \ + ui/widget/gimpspinscale.c \ + ui/widget/gimpspinscale.h \ + ui/widget/gimpcolorwheel.c \ + ui/widget/gimpcolorwheel.h \ ui/widget/frame.cpp \ ui/widget/frame.h \ - ui/widget/handlebox.cpp \ - ui/widget/handlebox.h \ - ui/widget/icon-widget.cpp \ - ui/widget/icon-widget.h \ ui/widget/imageicon.cpp \ ui/widget/imageicon.h \ ui/widget/imagetoggler.cpp \ @@ -60,8 +60,6 @@ ink_common_sources += \ ui/widget/rendering-options.h \ ui/widget/rotateable.h \ ui/widget/rotateable.cpp \ - ui/widget/ruler.cpp \ - ui/widget/ruler.h \ ui/widget/scalar-unit.cpp \ ui/widget/scalar-unit.h \ ui/widget/scalar.cpp \ @@ -70,22 +68,20 @@ ink_common_sources += \ ui/widget/selected-style.cpp \ ui/widget/spinbutton.h \ ui/widget/spinbutton.cpp \ + ui/widget/spin-scale.h \ + ui/widget/spin-scale.cpp \ ui/widget/spin-slider.h \ ui/widget/spin-slider.cpp \ ui/widget/style-subject.h \ ui/widget/style-subject.cpp \ ui/widget/style-swatch.h \ ui/widget/style-swatch.cpp \ - ui/widget/svg-canvas.cpp \ - ui/widget/svg-canvas.h \ ui/widget/text.cpp \ ui/widget/text.h \ ui/widget/tolerance-slider.cpp \ ui/widget/tolerance-slider.h \ - ui/widget/toolbox.cpp \ - ui/widget/toolbox.h \ ui/widget/unit-menu.cpp \ - ui/widget/unit-menu.h \ - ui/widget/zoom-status.h \ - ui/widget/zoom-status.cpp + ui/widget/unit-menu.h \ + ui/widget/unit-tracker.h \ + ui/widget/unit-tracker.cpp diff --git a/src/ui/widget/attr-widget.h b/src/ui/widget/attr-widget.h index 7c7235386..1238798ef 100644 --- a/src/ui/widget/attr-widget.h +++ b/src/ui/widget/attr-widget.h @@ -122,7 +122,12 @@ public: : _attr(a), _default(value) {} - + + AttrWidget(const SPAttributeEnum a, char* value) + : _attr(a), + _default(value) + {} + AttrWidget(const SPAttributeEnum a) : _attr(a), _default() diff --git a/src/ui/widget/button.h b/src/ui/widget/button.h index b219fc3db..a214dd881 100644 --- a/src/ui/widget/button.h +++ b/src/ui/widget/button.h @@ -10,6 +10,14 @@ #ifndef INKSCAPE_UI_WIDGET_BUTTON_H #define INKSCAPE_UI_WIDGET_BUTTON_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/checkbutton.h> #include <gtkmm/radiobutton.h> @@ -19,6 +27,7 @@ namespace Widget { /** * Button widget. + * @deprecated - no need for an explicit subclass... just perhaps a helper function. */ class Button : public Gtk::Button { @@ -29,6 +38,7 @@ public: /** * CheckButton widget. + * @deprecated - no need for an explicit subclass... just perhaps a helper function. */ class CheckButton : public Gtk::CheckButton { @@ -41,6 +51,7 @@ public: /** * RadioButton widget. + * @deprecated - no need for an explicit subclass... just perhaps a helper function. */ class RadioButton : public Gtk::RadioButton { diff --git a/src/ui/widget/color-picker.cpp b/src/ui/widget/color-picker.cpp index e5c542a7c..5585f2db4 100644 --- a/src/ui/widget/color-picker.cpp +++ b/src/ui/widget/color-picker.cpp @@ -55,9 +55,15 @@ void ColorPicker::setupDialog(const Glib::ustring &title) _colorSelectorDialog.hide(); _colorSelectorDialog.set_title (title); _colorSelectorDialog.set_border_width (4); - _colorSelector = (SPColorSelector*)sp_color_selector_new(SP_TYPE_COLOR_NOTEBOOK); + _colorSelector = SP_COLOR_SELECTOR(sp_color_selector_new(SP_TYPE_COLOR_NOTEBOOK)); + +#if WITH_GTKMM_3_0 + _colorSelectorDialog.get_content_area()->pack_start ( + *Glib::wrap(&_colorSelector->vbox), true, true, 0); +#else _colorSelectorDialog.get_vbox()->pack_start ( *Glib::wrap(&_colorSelector->vbox), true, true, 0); +#endif g_signal_connect(G_OBJECT(_colorSelector), "dragged", G_CALLBACK(sp_color_picker_color_mod), (void *)this); diff --git a/src/ui/widget/color-picker.h b/src/ui/widget/color-picker.h index e20212615..b4da5dbf2 100644 --- a/src/ui/widget/color-picker.h +++ b/src/ui/widget/color-picker.h @@ -13,7 +13,16 @@ #ifndef __COLOR_PICKER_H__ #define __COLOR_PICKER_H__ +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + #include <stddef.h> + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/dialog.h> #include <gtkmm/button.h> #include <sigc++/sigc++.h> diff --git a/src/ui/widget/color-preview.cpp b/src/ui/widget/color-preview.cpp index 244e2b4e3..5bcd16528 100644 --- a/src/ui/widget/color-preview.cpp +++ b/src/ui/widget/color-preview.cpp @@ -26,13 +26,6 @@ ColorPreview::ColorPreview (guint32 rgba) } void -ColorPreview::on_size_request (Gtk::Requisition *req) -{ - req->width = SPCP_DEFAULT_WIDTH; - req->height = SPCP_DEFAULT_HEIGHT; -} - -void ColorPreview::on_size_allocate (Gtk::Allocation &all) { set_allocation (all); @@ -40,14 +33,55 @@ ColorPreview::on_size_allocate (Gtk::Allocation &all) queue_draw(); } +#if WITH_GTKMM_3_0 +void +ColorPreview::get_preferred_height_vfunc(int& minimum_height, int& natural_height) const +{ + minimum_height = natural_height = SPCP_DEFAULT_HEIGHT; +} + +void +ColorPreview::get_preferred_height_for_width_vfunc(int /* width */, int& minimum_height, int& natural_height) const +{ + minimum_height = natural_height = SPCP_DEFAULT_HEIGHT; +} + +void +ColorPreview::get_preferred_width_vfunc(int& minimum_width, int& natural_width) const +{ + minimum_width = natural_width = SPCP_DEFAULT_WIDTH; +} + +void +ColorPreview::get_preferred_width_for_height_vfunc(int /* height */, int& minimum_width, int& natural_width) const +{ + minimum_width = natural_width = SPCP_DEFAULT_WIDTH; +} +#else +void +ColorPreview::on_size_request (Gtk::Requisition *req) +{ + req->width = SPCP_DEFAULT_WIDTH; + req->height = SPCP_DEFAULT_HEIGHT; +} + bool ColorPreview::on_expose_event (GdkEventExpose *event) { + bool result = true; + if (get_is_drawable()) - paint (&event->area); + { + Cairo::RefPtr<Cairo::Context> cr = get_window()->create_cairo_context(); + cr->rectangle(event->area.x, event->area.y, + event->area.width, event->area.height); + cr->clip(); + result = on_draw(cr); + } - return true; + return result; } +#endif void ColorPreview::setRgba32 (guint32 rgba) @@ -58,11 +92,10 @@ ColorPreview::setRgba32 (guint32 rgba) queue_draw(); } -void -ColorPreview::paint (GdkRectangle *area) +bool +ColorPreview::on_draw(const Cairo::RefPtr<Cairo::Context>& cr) { GdkRectangle warea, carea; - GdkRectangle wpaint, cpaint; gint w2; const Gtk::Allocation& allocation = get_allocation(); @@ -71,12 +104,6 @@ ColorPreview::paint (GdkRectangle *area) warea.width = allocation.get_width(); warea.height = allocation.get_height(); - if (!gdk_rectangle_intersect (area, &warea, &wpaint)) - return; - - GtkWidget *widget = GTK_WIDGET(this->gobj()); - cairo_t *ct = gdk_cairo_create(widget->window); - /* Transparent area */ w2 = warea.width / 2; @@ -86,17 +113,15 @@ ColorPreview::paint (GdkRectangle *area) carea.width = w2; carea.height = warea.height; - if (gdk_rectangle_intersect (area, &carea, &cpaint)) { - cairo_pattern_t *checkers = ink_cairo_pattern_create_checkerboard(); + cairo_pattern_t *checkers = ink_cairo_pattern_create_checkerboard(); - cairo_rectangle(ct, carea.x, carea.y, carea.width, carea.height); - cairo_set_source(ct, checkers); - cairo_fill_preserve(ct); - ink_cairo_set_source_rgba32(ct, _rgba); - cairo_fill(ct); + cr->rectangle(carea.x, carea.y, carea.width, carea.height); + cairo_set_source(cr->cobj(), checkers); + cr->fill_preserve(); + ink_cairo_set_source_rgba32(cr->cobj(), _rgba); + cr->fill(); - cairo_pattern_destroy(checkers); - } + cairo_pattern_destroy(checkers); /* Solid area */ @@ -105,13 +130,11 @@ ColorPreview::paint (GdkRectangle *area) carea.width = warea.width - w2; carea.height = warea.height; - if (gdk_rectangle_intersect (area, &carea, &cpaint)) { - cairo_rectangle(ct, carea.x, carea.y, carea.width, carea.height); - ink_cairo_set_source_rgba32(ct, _rgba | 0xff); - cairo_fill(ct); - } + cr->rectangle(carea.x, carea.y, carea.width, carea.height); + ink_cairo_set_source_rgba32(cr->cobj(), _rgba | 0xff); + cr->fill(); - cairo_destroy(ct); + return true; } GdkPixbuf* @@ -153,12 +176,7 @@ ColorPreview::toPixbuf (int width, int height) cairo_destroy(ct); cairo_surface_flush(s); - GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data( cairo_image_surface_get_data(s), - GDK_COLORSPACE_RGB, TRUE, 8, - width, height, cairo_image_surface_get_stride(s), - ink_cairo_pixbuf_cleanup, s); - convert_pixbuf_argb32_to_normal(pixbuf); - + GdkPixbuf* pixbuf = ink_pixbuf_create_from_cairo_surface(s); return pixbuf; } @@ -173,3 +191,4 @@ ColorPreview::toPixbuf (int width, int height) fill-column:99 End: */ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/widget/color-preview.h b/src/ui/widget/color-preview.h index d6d3da01c..959b5e09b 100644 --- a/src/ui/widget/color-preview.h +++ b/src/ui/widget/color-preview.h @@ -11,6 +11,14 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/widget.h> namespace Inkscape { @@ -27,10 +35,19 @@ public: GdkPixbuf* toPixbuf (int width, int height); protected: - virtual void on_size_request (Gtk::Requisition *req); virtual void on_size_allocate (Gtk::Allocation &all); - virtual bool on_expose_event (GdkEventExpose *event); - void paint (GdkRectangle *area); + +#if WITH_GTKMM_3_0 + virtual void get_preferred_height_vfunc(int& minimum_height, int& natural_height) const; + virtual void get_preferred_height_for_width_vfunc(int width, int& minimum_height, int& natural_height) const; + virtual void get_preferred_width_vfunc(int& minimum_width, int& natural_width) const; + virtual void get_preferred_width_for_height_vfunc(int height, int& minimum_width, int& natural_width) const; +#else + virtual void on_size_request (Gtk::Requisition *req); + virtual bool on_expose_event(GdkEventExpose *event); +#endif + + virtual bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr); guint32 _rgba; }; diff --git a/src/ui/widget/dock-item.cpp b/src/ui/widget/dock-item.cpp index 238e93b0b..8d960ddc3 100644 --- a/src/ui/widget/dock-item.cpp +++ b/src/ui/widget/dock-item.cpp @@ -18,6 +18,7 @@ #include <gtkmm/icontheme.h> #include <gtkmm/stockitem.h> +#include <glibmm/exceptionhandler.h> namespace Inkscape { namespace UI { @@ -58,7 +59,11 @@ DockItem::DockItem(Dock& dock, const Glib::ustring& name, const Glib::ustring& l Gtk::StockItem item; Gtk::StockID stockId(icon_name); if ( Gtk::StockItem::lookup(stockId, item) ) { +#if WITH_GTKMM_3_0 + _icon_pixbuf = _dock.getWidget().render_icon_pixbuf( stockId, Gtk::ICON_SIZE_MENU ); +#else _icon_pixbuf = _dock.getWidget().render_icon( stockId, Gtk::ICON_SIZE_MENU ); +#endif } } } @@ -168,10 +173,14 @@ DockItem::set_size_request(int width, int height) getWidget().set_size_request(width, height); } -void -DockItem::size_request(Gtk::Requisition& requisition) +void DockItem::size_request(Gtk::Requisition& requisition) { +#if WITH_GTKMM_3_0 + Gtk::Requisition req_natural; + getWidget().get_preferred_size(req_natural, requisition); +#else requisition = getWidget().size_request(); +#endif } void diff --git a/src/ui/widget/dock-item.h b/src/ui/widget/dock-item.h index 608badb62..cc0c13eea 100644 --- a/src/ui/widget/dock-item.h +++ b/src/ui/widget/dock-item.h @@ -11,6 +11,14 @@ #ifndef INKSCAPE_UI_WIGET_DOCK_ITEM_H #define INKSCAPE_UI_WIGET_DOCK_ITEM_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> #include <gtkmm/frame.h> #include <gtkmm/window.h> diff --git a/src/ui/widget/dock.cpp b/src/ui/widget/dock.cpp index ab3a8adca..52e9ea605 100644 --- a/src/ui/widget/dock.cpp +++ b/src/ui/widget/dock.cpp @@ -25,7 +25,7 @@ namespace Widget { namespace { -void hideCallback(GtkObject */*object*/, gpointer dock_ptr) +void hideCallback(GObject * /*object*/, gpointer dock_ptr) { g_return_if_fail( dock_ptr != NULL ); @@ -33,7 +33,7 @@ void hideCallback(GtkObject */*object*/, gpointer dock_ptr) dock->hide(); } -void unhideCallback(GtkObject */*object*/, gpointer dock_ptr) +void unhideCallback(GObject * /*object*/, gpointer dock_ptr) { g_return_if_fail( dock_ptr != NULL ); @@ -48,12 +48,33 @@ const int Dock::_default_dock_bar_width = 36; Dock::Dock(Gtk::Orientation orientation) - : _gdl_dock (GDL_DOCK (gdl_dock_new())), - _gdl_dock_bar (GDL_DOCK_BAR (gdl_dock_bar_new(GDL_DOCK(_gdl_dock)))), + : _gdl_dock(gdl_dock_new()), +#if WITH_GDL_3_6 + _gdl_dock_bar(GDL_DOCK_BAR(gdl_dock_bar_new(G_OBJECT(_gdl_dock)))), +#else + _gdl_dock_bar(GDL_DOCK_BAR(gdl_dock_bar_new(GDL_DOCK(_gdl_dock)))), +#endif _scrolled_window (Gtk::manage(new Gtk::ScrolledWindow)) { - gdl_dock_bar_set_orientation(_gdl_dock_bar, static_cast<GtkOrientation>(orientation)); - +#if WITH_GDL_3_6 + gtk_orientable_set_orientation(GTK_ORIENTABLE(_gdl_dock_bar), + static_cast<GtkOrientation>(orientation)); +#else + gdl_dock_bar_set_orientation(_gdl_dock_bar, + static_cast<GtkOrientation>(orientation)); +#endif + +#if WITH_GTKMM_3_0 + switch(orientation) { + case Gtk::ORIENTATION_VERTICAL: + _dock_box = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL)); + break; + case Gtk::ORIENTATION_HORIZONTAL: + _dock_box = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_VERTICAL)); + } + + _paned = Gtk::manage(new Gtk::Paned(orientation)); +#else switch (orientation) { case Gtk::ORIENTATION_VERTICAL: _dock_box = Gtk::manage(new Gtk::HBox()); @@ -63,6 +84,7 @@ Dock::Dock(Gtk::Orientation orientation) _dock_box = Gtk::manage(new Gtk::VBox()); _paned = Gtk::manage(new Gtk::HPaned()); } +#endif _scrolled_window->add(*_dock_box); _scrolled_window->set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); @@ -81,9 +103,15 @@ Dock::Dock(Gtk::Orientation orientation) static_cast<GdlSwitcherStyle>(prefs->getIntLimited("/options/dock/switcherstyle", GDL_SWITCHER_STYLE_BOTH, 0, 4)); - g_object_set (GDL_DOCK_OBJECT(_gdl_dock)->master, - "switcher-style", gdl_switcher_style, - NULL); + GdlDockMaster* master = NULL; + + g_object_get(GDL_DOCK_OBJECT(_gdl_dock), + "master", &master, + NULL); + + g_object_set(master, + "switcher-style", gdl_switcher_style, + NULL); GdlDockBarStyle gdl_dock_bar_style = static_cast<GdlDockBarStyle>(prefs->getIntLimited("/options/dock/dockbarstyle", @@ -109,7 +137,9 @@ Dock::~Dock() void Dock::addItem(DockItem& item, DockItem::Placement placement) { _dock_items.push_back(&item); - gdl_dock_add_item(_gdl_dock, GDL_DOCK_ITEM(item.gobj()), (GdlDockPlacement)placement); + gdl_dock_add_item(GDL_DOCK(_gdl_dock), + GDL_DOCK_ITEM(item.gobj()), + (GdlDockPlacement)placement); // FIXME: This is a hack to prevent the dock from expanding the main window, this can't be done // initially as the paned doesn't exist. diff --git a/src/ui/widget/dock.h b/src/ui/widget/dock.h index 28ab42740..33e60b836 100644 --- a/src/ui/widget/dock.h +++ b/src/ui/widget/dock.h @@ -12,6 +12,14 @@ #ifndef INKSCAPE_UI_WIDGET_DOCK_H #define INKSCAPE_UI_WIDGET_DOCK_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> #include <list> #include "ui/widget/dock-item.h" @@ -66,11 +74,11 @@ protected: /** Interface widgets, will be packed like * _scrolled_window -> (_dock_box -> (_paned -> (_dock -> _filler) | _dock_bar)) */ - Gtk::Box *_dock_box; - Gtk::Paned* _paned; - GdlDock *_gdl_dock; - GdlDockBar *_gdl_dock_bar; - Gtk::VBox _filler; + Gtk::Box *_dock_box; + Gtk::Paned *_paned; + GtkWidget *_gdl_dock; + GdlDockBar *_gdl_dock_bar; + Gtk::VBox _filler; Gtk::ScrolledWindow *_scrolled_window; /** Internal signal handlers */ diff --git a/src/ui/widget/entity-entry.cpp b/src/ui/widget/entity-entry.cpp index be43e4fda..0f526f77a 100644 --- a/src/ui/widget/entity-entry.cpp +++ b/src/ui/widget/entity-entry.cpp @@ -17,6 +17,10 @@ # include <config.h> #endif +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/scrolledwindow.h> #include <gtkmm/entry.h> @@ -26,6 +30,8 @@ #include "ui/widget/registry.h" #include "sp-root.h" #include "document-undo.h" +#include "document-private.h" +#include "preferences.h" #include "verbs.h" #include "entity-entry.h" @@ -71,6 +77,13 @@ EntityEntry::~EntityEntry() _changed_connection.disconnect(); } +void EntityEntry::save_to_preferences(SPDocument *doc) +{ + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + const gchar *text = rdf_get_work_entity (doc, _entity); + prefs->setString(PREFS_METADATA + Glib::ustring(_entity->name), Glib::ustring(text ? text : "")); +} + EntityLineEntry::EntityLineEntry (rdf_work_entity_t* ent, Registry& wr) : EntityEntry (ent, wr) { @@ -96,6 +109,16 @@ void EntityLineEntry::update(SPDocument *doc) static_cast<Gtk::Entry*>(_packable)->set_text (text ? text : ""); } + +void EntityLineEntry::load_from_preferences() +{ + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + Glib::ustring text = prefs->getString(PREFS_METADATA + Glib::ustring(_entity->name)); + if (text.length() > 0) { + static_cast<Gtk::Entry*>(_packable)->set_text (text.c_str()); + } +} + void EntityLineEntry::on_changed() { @@ -105,8 +128,9 @@ EntityLineEntry::on_changed() SPDocument *doc = SP_ACTIVE_DOCUMENT; Glib::ustring text = static_cast<Gtk::Entry*>(_packable)->get_text(); if (rdf_set_work_entity (doc, _entity, text.c_str())) { - DocumentUndo::done(doc, SP_VERB_NONE, - /* TODO: annotate */ "entity-entry.cpp:101"); + if (doc->priv->sensitive) { + DocumentUndo::done(doc, SP_VERB_NONE, "Document metadata updated"); + } } _wr->setUpdating (false); } @@ -144,6 +168,19 @@ void EntityMultiLineEntry::update(SPDocument *doc) tv->get_buffer()->set_text (text ? text : ""); } + +void EntityMultiLineEntry::load_from_preferences() +{ + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + Glib::ustring text = prefs->getString(PREFS_METADATA + Glib::ustring(_entity->name)); + if (text.length() > 0) { + Gtk::ScrolledWindow *s = static_cast<Gtk::ScrolledWindow*>(_packable); + Gtk::TextView *tv = static_cast<Gtk::TextView*>(s->get_child()); + tv->get_buffer()->set_text (text.c_str()); + } +} + + void EntityMultiLineEntry::on_changed() { @@ -155,7 +192,7 @@ EntityMultiLineEntry::on_changed() Gtk::TextView *tv = static_cast<Gtk::TextView*>(s->get_child()); Glib::ustring text = tv->get_buffer()->get_text(); if (rdf_set_work_entity (doc, _entity, text.c_str())) { - DocumentUndo::done(doc, SP_VERB_NONE, + DocumentUndo::done(doc, SP_VERB_NONE, /* TODO: annotate */ "entity-entry.cpp:146"); } _wr->setUpdating (false); diff --git a/src/ui/widget/entity-entry.h b/src/ui/widget/entity-entry.h index 0e031bb0a..09289496d 100644 --- a/src/ui/widget/entity-entry.h +++ b/src/ui/widget/entity-entry.h @@ -31,6 +31,8 @@ public: virtual ~EntityEntry() = 0; virtual void update (SPDocument *doc) = 0; virtual void on_changed() = 0; + virtual void load_from_preferences() = 0; + void save_to_preferences(SPDocument *doc); Gtk::Label _label; Gtk::Widget *_packable; @@ -46,6 +48,7 @@ public: EntityLineEntry (rdf_work_entity_t* ent, Registry& wr); ~EntityLineEntry(); void update (SPDocument *doc); + void load_from_preferences(); protected: virtual void on_changed(); @@ -56,6 +59,7 @@ public: EntityMultiLineEntry (rdf_work_entity_t* ent, Registry& wr); ~EntityMultiLineEntry(); void update (SPDocument *doc); + void load_from_preferences(); protected: virtual void on_changed(); diff --git a/src/ui/widget/entry.cpp b/src/ui/widget/entry.cpp index 173e014d9..64d28119a 100644 --- a/src/ui/widget/entry.cpp +++ b/src/ui/widget/entry.cpp @@ -13,6 +13,8 @@ #include "entry.h" +#include <gtkmm/entry.h> + namespace Inkscape { namespace UI { namespace Widget { diff --git a/src/ui/widget/entry.h b/src/ui/widget/entry.h index 53b848fc9..de5cceadd 100644 --- a/src/ui/widget/entry.h +++ b/src/ui/widget/entry.h @@ -11,10 +11,10 @@ #define INKSCAPE_UI_WIDGET_ENTRY__H #include "labelled.h" -#include <gtkmm.h> -#include <gtkmm/entry.h> -#include <gtkmm/comboboxtext.h> +namespace Gtk { +class Entry; +} namespace Inkscape { namespace UI { diff --git a/src/ui/widget/filter-effect-chooser.cpp b/src/ui/widget/filter-effect-chooser.cpp index cb9d3e7e0..65706a9dc 100644 --- a/src/ui/widget/filter-effect-chooser.cpp +++ b/src/ui/widget/filter-effect-chooser.cpp @@ -22,11 +22,9 @@ namespace UI { namespace Widget { SimpleFilterModifier::SimpleFilterModifier(int flags) - : _hb_blur(false, 0), - _lb_blend(_("Blend mode:")), - _lb_blur(_("_Blur:")), + : _lb_blend(_("Blend mode:")), _blend(BlendModeConverter, SP_ATTR_INVALID, false), - _blur(0, 0, 100, 1, 0.01, 1) + _blur(_("Blur (%)"), 0, 0, 100, 1, 0.01, 1) { _flags = flags; @@ -36,14 +34,7 @@ SimpleFilterModifier::SimpleFilterModifier(int flags) _hb_blend.pack_start(_blend); } if (flags & BLUR) { - add(_hb_blur); - #if WITH_GTKMM_2_22 - _lb_blur.set_alignment(Gtk::ALIGN_END, Gtk::ALIGN_CENTER); - #else - _lb_blur.set_alignment(Gtk::ALIGN_RIGHT, Gtk::ALIGN_CENTER); - #endif - _hb_blur.pack_start(_lb_blur, false, false, 0); - _hb_blur.pack_start(_blur, true, true, 0); + add(_blur); } show_all_children(); @@ -51,8 +42,6 @@ SimpleFilterModifier::SimpleFilterModifier(int flags) _hb_blend.set_spacing(12); _lb_blend.set_use_underline(); _lb_blend.set_mnemonic_widget(_blend); - _lb_blur.set_use_underline(); - _lb_blur.set_mnemonic_widget(_blur.get_scale()); _blend.signal_changed().connect(signal_blend_blur_changed()); _blur.signal_value_changed().connect(signal_blend_blur_changed()); } diff --git a/src/ui/widget/filter-effect-chooser.h b/src/ui/widget/filter-effect-chooser.h index 2d5f04007..8d2389b15 100644 --- a/src/ui/widget/filter-effect-chooser.h +++ b/src/ui/widget/filter-effect-chooser.h @@ -12,12 +12,20 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> #include <gtkmm/combobox.h> #include "combo-enums.h" #include "filter-enums.h" -#include "spin-slider.h" +#include "spin-scale.h" namespace Inkscape { namespace UI { @@ -45,17 +53,14 @@ public: double get_blur_value() const; void set_blur_value(const double); void set_blur_sensitive(const bool); - Gtk::Label *get_blur_label() { return &_lb_blur; }; - private: int _flags; Gtk::HBox _hb_blend; - Gtk::HBox _hb_blur; - Gtk::Label _lb_blend, _lb_blur; + Gtk::Label _lb_blend; ComboBoxEnum<Inkscape::Filters::FilterBlendMode> _blend; - SpinSlider _blur; + SpinScale _blur; sigc::signal<void> _signal_blend_blur_changed; }; diff --git a/src/ui/widget/frame.cpp b/src/ui/widget/frame.cpp index b2968f806..eaa4336bb 100644 --- a/src/ui/widget/frame.cpp +++ b/src/ui/widget/frame.cpp @@ -56,9 +56,7 @@ Frame::set_label(const Glib::ustring &label_text, gboolean label_bold /*= TRUE*/ void Frame::set_padding (guint padding_top, guint padding_bottom, guint padding_left, guint padding_right) { -#if WITH_GTKMM_2_24 _alignment.set_padding(padding_top, padding_bottom, padding_left, padding_right); -#endif } Gtk::Label const * diff --git a/src/ui/widget/frame.h b/src/ui/widget/frame.h index cf736d8a1..55638ad40 100644 --- a/src/ui/widget/frame.h +++ b/src/ui/widget/frame.h @@ -10,11 +10,17 @@ #ifndef INKSCAPE_UI_WIDGET_FRAME_H #define INKSCAPE_UI_WIDGET_FRAME_H -#include <gtkmm.h> +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif -namespace Gtk { -class Frame; -} +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + +#include <gtkmm/alignment.h> +#include <gtkmm/frame.h> +#include <gtkmm/label.h> namespace Inkscape { namespace UI { diff --git a/src/ui/widget/gimpcolorwheel.c b/src/ui/widget/gimpcolorwheel.c new file mode 100644 index 000000000..f632331d8 --- /dev/null +++ b/src/ui/widget/gimpcolorwheel.c @@ -0,0 +1,1598 @@ +/* HSV color selector for GTK+ + * + * Copyright (C) 1999 The Free Software Foundation + * + * Authors: Simon Budig <Simon.Budig@unix-ag.org> (original code) + * Federico Mena-Quintero <federico@gimp.org> (cleanup for GTK+) + * Jonathan Blandford <jrb@redhat.com> (cleanup for GTK+) + * Michael Natterer <mitch@gimp.org> (ported back to GIMP) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +/* + * Modified by the GTK+ Team and others 1997-2000. See the AUTHORS + * file for a list of people on the GTK+ Team. See the ChangeLog + * files for a list of changes. These files are distributed with + * GTK+ at ftp://ftp.gtk.org/pub/gtk/. + */ + +/* + * This widget was adopted by Inkscape by Alex Valavanis <valavanisalex@gmail.com> + * on 2013-01-08. Last merges with GIMP code were applied using the following + * commits from the GIMP git repository at + * http://git.gnome.org/browse/gimp/tree/modules/gimpcolorwheel.c + * + * Gtk+ 2 code merge: commit 632c5 (2013-01-06) + * Gtk+ 3 code merge: commit bcfc6, gtk3-port branch (2013-01-06) + */ + +#include "config.h" + +#include <gtk/gtk.h> +#include <gdk/gdkkeysyms.h> + +#include "gimpcolorwheel.h" +#include <math.h> + + +/* Default ring fraction */ +#define DEFAULT_FRACTION 0.1 + +/* Default width/height */ +#define DEFAULT_SIZE 100 + +/* Default ring width */ +#define DEFAULT_RING_WIDTH 10 + + +/* Dragging modes */ +typedef enum +{ + DRAG_NONE, + DRAG_H, + DRAG_SV +} DragMode; + +/* Private part of the GimpColorWheel structure */ +typedef struct +{ + /* Color value */ + gdouble h; + gdouble s; + gdouble v; + + /* ring_width is this fraction of size */ + gdouble ring_fraction; + + /* Size and ring width */ + gint size; + gint ring_width; + + /* Window for capturing events */ + GdkWindow *window; + + /* Dragging mode */ + DragMode mode; + + guint focus_on_ring : 1; +} GimpColorWheelPrivate; + +enum +{ + CHANGED, + MOVE, + LAST_SIGNAL +}; + +static void gimp_color_wheel_map (GtkWidget *widget); +static void gimp_color_wheel_unmap (GtkWidget *widget); +static void gimp_color_wheel_realize (GtkWidget *widget); +static void gimp_color_wheel_unrealize (GtkWidget *widget); +static void gimp_color_wheel_size_allocate (GtkWidget *widget, + GtkAllocation *allocation); +static gboolean gimp_color_wheel_button_press (GtkWidget *widget, + GdkEventButton *event); +static gboolean gimp_color_wheel_button_release (GtkWidget *widget, + GdkEventButton *event); +static gboolean gimp_color_wheel_motion (GtkWidget *widget, + GdkEventMotion *event); +#if GTK_CHECK_VERSION(3,0,0) +static gboolean gimp_color_wheel_draw (GtkWidget *widget, + cairo_t *cr); +static void gimp_color_wheel_get_preferred_width (GtkWidget *widget, + gint *minimum_width, + gint *natural_width); +static void gimp_color_wheel_get_preferred_height (GtkWidget *widget, + gint *minimum_height, + gint *natural_height); +#else +static gboolean gimp_color_wheel_expose (GtkWidget *widget, + GdkEventExpose *event); +static void gimp_color_wheel_size_request (GtkWidget *widget, + GtkRequisition *requisition); +#endif + +static gboolean gimp_color_wheel_grab_broken (GtkWidget *widget, + GdkEventGrabBroken *event); +static gboolean gimp_color_wheel_focus (GtkWidget *widget, + GtkDirectionType direction); +static void gimp_color_wheel_move (GimpColorWheel *wheel, + GtkDirectionType dir); + + +static guint wheel_signals[LAST_SIGNAL]; + +G_DEFINE_TYPE (GimpColorWheel, gimp_color_wheel, GTK_TYPE_WIDGET) + +#define parent_class gimp_color_wheel_parent_class + + +static void +gimp_color_wheel_class_init (GimpColorWheelClass *class) +{ + GObjectClass *object_class = G_OBJECT_CLASS (class); + GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class); + GimpColorWheelClass *wheel_class = GIMP_COLOR_WHEEL_CLASS (class); + GtkBindingSet *binding_set; + + widget_class->map = gimp_color_wheel_map; + widget_class->unmap = gimp_color_wheel_unmap; + widget_class->realize = gimp_color_wheel_realize; + widget_class->unrealize = gimp_color_wheel_unrealize; + widget_class->size_allocate = gimp_color_wheel_size_allocate; + widget_class->button_press_event = gimp_color_wheel_button_press; + widget_class->button_release_event = gimp_color_wheel_button_release; + widget_class->motion_notify_event = gimp_color_wheel_motion; + +#if GTK_CHECK_VERSION(3,0,0) + widget_class->get_preferred_width = gimp_color_wheel_get_preferred_width; + widget_class->get_preferred_height = gimp_color_wheel_get_preferred_height; + widget_class->draw = gimp_color_wheel_draw; +#else + widget_class->size_request = gimp_color_wheel_size_request; + widget_class->expose_event = gimp_color_wheel_expose; +#endif + + widget_class->focus = gimp_color_wheel_focus; + widget_class->grab_broken_event = gimp_color_wheel_grab_broken; + + wheel_class->move = gimp_color_wheel_move; + + wheel_signals[CHANGED] = + g_signal_new ("changed", + G_OBJECT_CLASS_TYPE (object_class), + G_SIGNAL_RUN_FIRST, + G_STRUCT_OFFSET (GimpColorWheelClass, changed), + NULL, NULL, + g_cclosure_marshal_VOID__VOID, + G_TYPE_NONE, 0); + + wheel_signals[MOVE] = + g_signal_new ("move", + G_OBJECT_CLASS_TYPE (object_class), + G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, + G_STRUCT_OFFSET (GimpColorWheelClass, move), + NULL, NULL, + g_cclosure_marshal_VOID__ENUM, + G_TYPE_NONE, 1, + GTK_TYPE_DIRECTION_TYPE); + + binding_set = gtk_binding_set_by_class (class); + + gtk_binding_entry_add_signal (binding_set, GDK_KEY_Up, 0, + "move", 1, + G_TYPE_ENUM, GTK_DIR_UP); + gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Up, 0, + "move", 1, + G_TYPE_ENUM, GTK_DIR_UP); + + gtk_binding_entry_add_signal (binding_set, GDK_KEY_Down, 0, + "move", 1, + G_TYPE_ENUM, GTK_DIR_DOWN); + gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Down, 0, + "move", 1, + G_TYPE_ENUM, GTK_DIR_DOWN); + + + gtk_binding_entry_add_signal (binding_set, GDK_KEY_Right, 0, + "move", 1, + G_TYPE_ENUM, GTK_DIR_RIGHT); + gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Right, 0, + "move", 1, + G_TYPE_ENUM, GTK_DIR_RIGHT); + + gtk_binding_entry_add_signal (binding_set, GDK_KEY_Left, 0, + "move", 1, + G_TYPE_ENUM, GTK_DIR_LEFT); + gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Left, 0, + "move", 1, + G_TYPE_ENUM, GTK_DIR_LEFT); + + g_type_class_add_private (object_class, sizeof (GimpColorWheelPrivate)); +} + +static void +gimp_color_wheel_init (GimpColorWheel *wheel) +{ + GimpColorWheelPrivate *priv; + + priv = G_TYPE_INSTANCE_GET_PRIVATE (wheel, GIMP_TYPE_COLOR_WHEEL, + GimpColorWheelPrivate); + + wheel->priv = priv; + + gtk_widget_set_has_window (GTK_WIDGET (wheel), FALSE); + gtk_widget_set_can_focus (GTK_WIDGET (wheel), TRUE); + + priv->ring_fraction = DEFAULT_FRACTION; + priv->size = DEFAULT_SIZE; + priv->ring_width = DEFAULT_RING_WIDTH; +} + +static void +gimp_color_wheel_map (GtkWidget *widget) +{ + GimpColorWheel *wheel = GIMP_COLOR_WHEEL (widget); + GimpColorWheelPrivate *priv = wheel->priv; + + GTK_WIDGET_CLASS (parent_class)->map (widget); + + gdk_window_show (priv->window); +} + +static void +gimp_color_wheel_unmap (GtkWidget *widget) +{ + GimpColorWheel *wheel = GIMP_COLOR_WHEEL (widget); + GimpColorWheelPrivate *priv = wheel->priv; + + gdk_window_hide (priv->window); + + GTK_WIDGET_CLASS (parent_class)->unmap (widget); +} + +static void +gimp_color_wheel_realize (GtkWidget *widget) +{ + GimpColorWheel *wheel = GIMP_COLOR_WHEEL (widget); + GimpColorWheelPrivate *priv = wheel->priv; + GtkAllocation allocation; + GdkWindowAttr attr; + gint attr_mask; + GdkWindow *parent_window; + + gtk_widget_get_allocation (widget, &allocation); + + gtk_widget_set_realized (widget, TRUE); + + attr.window_type = GDK_WINDOW_CHILD; + attr.x = allocation.x; + attr.y = allocation.y; + attr.width = allocation.width; + attr.height = allocation.height; + attr.wclass = GDK_INPUT_ONLY; + attr.event_mask = (gtk_widget_get_events (widget) | + GDK_KEY_PRESS_MASK | + GDK_BUTTON_PRESS_MASK | + GDK_BUTTON_RELEASE_MASK | + GDK_POINTER_MOTION_MASK | + GDK_ENTER_NOTIFY_MASK | + GDK_LEAVE_NOTIFY_MASK); + + attr_mask = GDK_WA_X | GDK_WA_Y; + + parent_window = gtk_widget_get_parent_window (widget); + + gtk_widget_set_window (widget, parent_window); + g_object_ref (parent_window); + + priv->window = gdk_window_new (parent_window, &attr, attr_mask); + gdk_window_set_user_data (priv->window, wheel); + + gtk_widget_style_attach (widget); +} + +static void +gimp_color_wheel_unrealize (GtkWidget *widget) +{ + GimpColorWheel *wheel = GIMP_COLOR_WHEEL (widget); + GimpColorWheelPrivate *priv = wheel->priv; + + gdk_window_set_user_data (priv->window, NULL); + gdk_window_destroy (priv->window); + priv->window = NULL; + + GTK_WIDGET_CLASS (parent_class)->unrealize (widget); +} + +#if GTK_CHECK_VERSION(3,0,0) +static void +gimp_color_wheel_get_preferred_width (GtkWidget *widget, + gint *minimum_width, + gint *natural_width) +{ + gint focus_width; + gint focus_pad; + + gtk_widget_style_get (widget, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, + NULL); + + *minimum_width = *natural_width = DEFAULT_SIZE + 2 * (focus_width + focus_pad); +} + +static void +gimp_color_wheel_get_preferred_height (GtkWidget *widget, + gint *minimum_height, + gint *natural_height) +{ + gint focus_width; + gint focus_pad; + + gtk_widget_style_get (widget, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, + NULL); + + *minimum_height = *natural_height = DEFAULT_SIZE + 2 * (focus_width + focus_pad); +} +#else +static void +gimp_color_wheel_size_request (GtkWidget *widget, + GtkRequisition *requisition) +{ + gint focus_width; + gint focus_pad; + + gtk_widget_style_get (widget, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, + NULL); + + requisition->width = DEFAULT_SIZE + 2 * (focus_width + focus_pad); + requisition->height = DEFAULT_SIZE + 2 * (focus_width + focus_pad); +} +#endif + +static void +gimp_color_wheel_size_allocate (GtkWidget *widget, + GtkAllocation *allocation) +{ + GimpColorWheel *wheel = GIMP_COLOR_WHEEL (widget); + GimpColorWheelPrivate *priv = wheel->priv; + gint focus_width; + gint focus_pad; + + gtk_widget_set_allocation (widget, allocation); + + gtk_widget_style_get (widget, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, + NULL); + + priv->size = MIN (allocation->width - 2 * (focus_width + focus_pad), + allocation->height - 2 * (focus_width + focus_pad)); + + priv->ring_width = priv->size * priv->ring_fraction; + + if (gtk_widget_get_realized (widget)) + gdk_window_move_resize (priv->window, + allocation->x, + allocation->y, + allocation->width, + allocation->height); +} + + +/* Utility functions */ + +#define INTENSITY(r, g, b) ((r) * 0.30 + (g) * 0.59 + (b) * 0.11) + +/* Converts from HSV to RGB */ +static void +hsv_to_rgb (gdouble *h, + gdouble *s, + gdouble *v) +{ + gdouble hue, saturation, value; + gdouble f, p, q, t; + + if (*s == 0.0) + { + *h = *v; + *s = *v; + *v = *v; /* heh */ + } + else + { + hue = *h * 6.0; + saturation = *s; + value = *v; + + if (hue == 6.0) + hue = 0.0; + + f = hue - (int) hue; + p = value * (1.0 - saturation); + q = value * (1.0 - saturation * f); + t = value * (1.0 - saturation * (1.0 - f)); + + switch ((int) hue) + { + case 0: + *h = value; + *s = t; + *v = p; + break; + + case 1: + *h = q; + *s = value; + *v = p; + break; + + case 2: + *h = p; + *s = value; + *v = t; + break; + + case 3: + *h = p; + *s = q; + *v = value; + break; + + case 4: + *h = t; + *s = p; + *v = value; + break; + + case 5: + *h = value; + *s = p; + *v = q; + break; + + default: + g_assert_not_reached (); + } + } +} + +/* Computes the vertices of the saturation/value triangle */ +static void +compute_triangle (GimpColorWheel *wheel, + gint *hx, + gint *hy, + gint *sx, + gint *sy, + gint *vx, + gint *vy) +{ + GimpColorWheelPrivate *priv = wheel->priv; + GtkAllocation allocation; + gdouble center_x; + gdouble center_y; + gdouble inner, outer; + gdouble angle; + + gtk_widget_get_allocation (GTK_WIDGET (wheel), &allocation); + + center_x = allocation.width / 2.0; + center_y = allocation.height / 2.0; + + outer = priv->size / 2.0; + inner = outer - priv->ring_width; + angle = priv->h * 2.0 * G_PI; + + *hx = floor (center_x + cos (angle) * inner + 0.5); + *hy = floor (center_y - sin (angle) * inner + 0.5); + *sx = floor (center_x + cos (angle + 2.0 * G_PI / 3.0) * inner + 0.5); + *sy = floor (center_y - sin (angle + 2.0 * G_PI / 3.0) * inner + 0.5); + *vx = floor (center_x + cos (angle + 4.0 * G_PI / 3.0) * inner + 0.5); + *vy = floor (center_y - sin (angle + 4.0 * G_PI / 3.0) * inner + 0.5); +} + +/* Computes whether a point is inside the hue ring */ +static gboolean +is_in_ring (GimpColorWheel *wheel, + gdouble x, + gdouble y) +{ + GimpColorWheelPrivate *priv = wheel->priv; + GtkAllocation allocation; + gdouble dx, dy, dist; + gdouble center_x; + gdouble center_y; + gdouble inner, outer; + + gtk_widget_get_allocation (GTK_WIDGET (wheel), &allocation); + + center_x = allocation.width / 2.0; + center_y = allocation.height / 2.0; + + outer = priv->size / 2.0; + inner = outer - priv->ring_width; + + dx = x - center_x; + dy = center_y - y; + dist = dx * dx + dy * dy; + + return (dist >= inner * inner && dist <= outer * outer); +} + +/* Computes a saturation/value pair based on the mouse coordinates */ +static void +compute_sv (GimpColorWheel *wheel, + gdouble x, + gdouble y, + gdouble *s, + gdouble *v) +{ + GtkAllocation allocation; + gint ihx, ihy, isx, isy, ivx, ivy; + gdouble hx, hy, sx, sy, vx, vy; + gdouble center_x; + gdouble center_y; + + gtk_widget_get_allocation (GTK_WIDGET (wheel), &allocation); + + compute_triangle (wheel, &ihx, &ihy, &isx, &isy, &ivx, &ivy); + + center_x = allocation.width / 2.0; + center_y = allocation.height / 2.0; + + hx = ihx - center_x; + hy = center_y - ihy; + sx = isx - center_x; + sy = center_y - isy; + vx = ivx - center_x; + vy = center_y - ivy; + x -= center_x; + y = center_y - y; + + if (vx * (x - sx) + vy * (y - sy) < 0.0) + { + *s = 1.0; + *v = (((x - sx) * (hx - sx) + (y - sy) * (hy-sy)) + / ((hx - sx) * (hx - sx) + (hy - sy) * (hy - sy))); + + if (*v < 0.0) + *v = 0.0; + else if (*v > 1.0) + *v = 1.0; + } + else if (hx * (x - sx) + hy * (y - sy) < 0.0) + { + *s = 0.0; + *v = (((x - sx) * (vx - sx) + (y - sy) * (vy - sy)) + / ((vx - sx) * (vx - sx) + (vy - sy) * (vy - sy))); + + if (*v < 0.0) + *v = 0.0; + else if (*v > 1.0) + *v = 1.0; + } + else if (sx * (x - hx) + sy * (y - hy) < 0.0) + { + *v = 1.0; + *s = (((x - vx) * (hx - vx) + (y - vy) * (hy - vy)) / + ((hx - vx) * (hx - vx) + (hy - vy) * (hy - vy))); + + if (*s < 0.0) + *s = 0.0; + else if (*s > 1.0) + *s = 1.0; + } + else + { + *v = (((x - sx) * (hy - vy) - (y - sy) * (hx - vx)) + / ((vx - sx) * (hy - vy) - (vy - sy) * (hx - vx))); + + if (*v<= 0.0) + { + *v = 0.0; + *s = 0.0; + } + else + { + if (*v > 1.0) + *v = 1.0; + + if (fabs (hy - vy) < fabs (hx - vx)) + *s = (x - sx - *v * (vx - sx)) / (*v * (hx - vx)); + else + *s = (y - sy - *v * (vy - sy)) / (*v * (hy - vy)); + + if (*s < 0.0) + *s = 0.0; + else if (*s > 1.0) + *s = 1.0; + } + } +} + +/* Computes whether a point is inside the saturation/value triangle */ +static gboolean +is_in_triangle (GimpColorWheel *wheel, + gdouble x, + gdouble y) +{ + gint hx, hy, sx, sy, vx, vy; + gdouble det, s, v; + + compute_triangle (wheel, &hx, &hy, &sx, &sy, &vx, &vy); + + det = (vx - sx) * (hy - sy) - (vy - sy) * (hx - sx); + + s = ((x - sx) * (hy - sy) - (y - sy) * (hx - sx)) / det; + v = ((vx - sx) * (y - sy) - (vy - sy) * (x - sx)) / det; + + return (s >= 0.0 && v >= 0.0 && s + v <= 1.0); +} + +/* Computes a value based on the mouse coordinates */ +static double +compute_v (GimpColorWheel *wheel, + gdouble x, + gdouble y) +{ + GtkAllocation allocation; + gdouble center_x; + gdouble center_y; + gdouble dx, dy; + gdouble angle; + + gtk_widget_get_allocation (GTK_WIDGET (wheel), &allocation); + + center_x = allocation.width / 2.0; + center_y = allocation.height / 2.0; + + dx = x - center_x; + dy = center_y - y; + + angle = atan2 (dy, dx); + if (angle < 0.0) + angle += 2.0 * G_PI; + + return angle / (2.0 * G_PI); +} + +static void +set_cross_grab (GimpColorWheel *wheel, + guint32 time) +{ + GimpColorWheelPrivate *priv = wheel->priv; + GdkCursor *cursor; + + cursor = + gdk_cursor_new_for_display (gtk_widget_get_display (GTK_WIDGET (wheel)), + GDK_CROSSHAIR); + +#if GTK_CHECK_VERSION(3,0,0) + gdk_device_grab (gtk_get_current_event_device(), + priv->window, + GDK_OWNERSHIP_NONE, + FALSE, + GDK_POINTER_MOTION_MASK | + GDK_POINTER_MOTION_HINT_MASK | + GDK_BUTTON_RELEASE_MASK, + cursor, time); + g_object_unref (cursor); +#else + gdk_pointer_grab (priv->window, FALSE, + GDK_POINTER_MOTION_MASK | + GDK_POINTER_MOTION_HINT_MASK | + GDK_BUTTON_RELEASE_MASK, + NULL, cursor, time); + gdk_cursor_unref (cursor); +#endif +} + +static gboolean gimp_color_wheel_grab_broken(GtkWidget *widget, GdkEventGrabBroken *event) +{ + (void)event; + GimpColorWheel *wheel = GIMP_COLOR_WHEEL (widget); + GimpColorWheelPrivate *priv = wheel->priv; + + priv->mode = DRAG_NONE; + + return TRUE; +} + +static gboolean +gimp_color_wheel_button_press (GtkWidget *widget, + GdkEventButton *event) +{ + GimpColorWheel *wheel = GIMP_COLOR_WHEEL (widget); + GimpColorWheelPrivate *priv = wheel->priv; + gdouble x, y; + + if (priv->mode != DRAG_NONE || event->button != 1) + return FALSE; + + x = event->x; + y = event->y; + + if (is_in_ring (wheel, x, y)) + { + priv->mode = DRAG_H; + set_cross_grab (wheel, event->time); + + gimp_color_wheel_set_color (wheel, + compute_v (wheel, x, y), + priv->s, + priv->v); + + gtk_widget_grab_focus (widget); + priv->focus_on_ring = TRUE; + + return TRUE; + } + + if (is_in_triangle (wheel, x, y)) + { + gdouble s, v; + + priv->mode = DRAG_SV; + set_cross_grab (wheel, event->time); + + compute_sv (wheel, x, y, &s, &v); + gimp_color_wheel_set_color (wheel, priv->h, s, v); + + gtk_widget_grab_focus (widget); + priv->focus_on_ring = FALSE; + + return TRUE; + } + + return FALSE; +} + +static gboolean +gimp_color_wheel_button_release (GtkWidget *widget, + GdkEventButton *event) +{ + GimpColorWheel *wheel = GIMP_COLOR_WHEEL (widget); + GimpColorWheelPrivate *priv = wheel->priv; + DragMode mode; + gdouble x, y; + + if (priv->mode == DRAG_NONE || event->button != 1) + return FALSE; + + /* Set the drag mode to DRAG_NONE so that signal handlers for "catched" + * can see that this is the final color state. + */ + + mode = priv->mode; + priv->mode = DRAG_NONE; + + x = event->x; + y = event->y; + + if (mode == DRAG_H) + { + gimp_color_wheel_set_color (wheel, + compute_v (wheel, x, y), priv->s, priv->v); + } + else if (mode == DRAG_SV) + { + gdouble s, v; + + compute_sv (wheel, x, y, &s, &v); + gimp_color_wheel_set_color (wheel, priv->h, s, v); + } + else + g_assert_not_reached (); + +#if GTK_CHECK_VERSION(3,0,0) + gdk_device_ungrab (gtk_get_current_event_device(), + event->time); +#else + gdk_display_pointer_ungrab (gdk_window_get_display (event->window), + event->time); +#endif + + return TRUE; +} + +static gboolean +gimp_color_wheel_motion (GtkWidget *widget, + GdkEventMotion *event) +{ + GimpColorWheel *wheel = GIMP_COLOR_WHEEL (widget); + GimpColorWheelPrivate *priv = wheel->priv; + gdouble x, y; + + if (priv->mode == DRAG_NONE) + return FALSE; + + gdk_event_request_motions (event); + x = event->x; + y = event->y; + + if (priv->mode == DRAG_H) + { + gimp_color_wheel_set_color (wheel, + compute_v (wheel, x, y), priv->s, priv->v); + return TRUE; + } + else if (priv->mode == DRAG_SV) + { + gdouble s, v; + + compute_sv (wheel, x, y, &s, &v); + gimp_color_wheel_set_color (wheel, priv->h, s, v); + return TRUE; + } + + g_assert_not_reached (); + + return FALSE; +} + + +/* Redrawing */ + +/* Paints the hue ring */ +static void +paint_ring (GimpColorWheel *wheel, + cairo_t *cr) +{ +#if GTK_CHECK_VERSION(3,0,0) + GtkWidget *widget = GTK_WIDGET (wheel); +#else + GtkAllocation allocation; +#endif + GimpColorWheelPrivate *priv = wheel->priv; + gint width, height; + gint xx, yy; + gdouble dx, dy, dist; + gdouble center_x; + gdouble center_y; + gdouble inner, outer; + guint32 *buf, *p; + gdouble angle; + gdouble hue; + gdouble r, g, b; + cairo_surface_t *source; + cairo_t *source_cr; + gint stride; + +#if GTK_CHECK_VERSION(3,0,0) + width = gtk_widget_get_allocated_width (widget); + height = gtk_widget_get_allocated_height (widget); +#else + gtk_widget_get_allocation (GTK_WIDGET (wheel), &allocation); + width = allocation.width; + height = allocation.height; +#endif + + center_x = width / 2.0; + center_y = height / 2.0; + + outer = priv->size / 2.0; + inner = outer - priv->ring_width; + + /* Create an image initialized with the ring colors */ + + stride = cairo_format_stride_for_width (CAIRO_FORMAT_RGB24, width); + buf = g_new (guint32, height * stride / 4); + + for (yy = 0; yy < height; yy++) + { + p = buf + yy * width; + dy = -(yy - center_y); + + for (xx = 0; xx < width; xx++) + { + dx = xx - center_x; + + dist = dx * dx + dy * dy; + if (dist < ((inner-1) * (inner-1)) || dist > ((outer+1) * (outer+1))) + { + *p++ = 0; + continue; + } + + angle = atan2 (dy, dx); + if (angle < 0.0) + angle += 2.0 * G_PI; + + hue = angle / (2.0 * G_PI); + + r = hue; + g = 1.0; + b = 1.0; + hsv_to_rgb (&r, &g, &b); + + *p++ = (((int)floor (r * 255 + 0.5) << 16) | + ((int)floor (g * 255 + 0.5) << 8) | + (int)floor (b * 255 + 0.5)); + } + } + + source = cairo_image_surface_create_for_data ((unsigned char *)buf, + CAIRO_FORMAT_RGB24, + width, height, stride); + + /* Now draw the value marker onto the source image, so that it + * will get properly clipped at the edges of the ring + */ + source_cr = cairo_create (source); + + r = priv->h; + g = 1.0; + b = 1.0; + hsv_to_rgb (&r, &g, &b); + + if (INTENSITY (r, g, b) > 0.5) + cairo_set_source_rgb (source_cr, 0.0, 0.0, 0.0); + else + cairo_set_source_rgb (source_cr, 1.0, 1.0, 1.0); + + cairo_move_to (source_cr, center_x, center_y); + cairo_line_to (source_cr, + center_x + cos (priv->h * 2.0 * G_PI) * priv->size / 2, + center_y - sin (priv->h * 2.0 * G_PI) * priv->size / 2); + cairo_stroke (source_cr); + cairo_destroy (source_cr); + + /* Draw the ring using the source image */ + + cairo_save (cr); + + cairo_set_source_surface (cr, source, 0, 0); + cairo_surface_destroy (source); + + cairo_set_line_width (cr, priv->ring_width); + cairo_new_path (cr); + cairo_arc (cr, + center_x, center_y, + priv->size / 2.0 - priv->ring_width / 2.0, + 0, 2 * G_PI); + cairo_stroke (cr); + + cairo_restore (cr); + + g_free (buf); +} + +/* Converts an HSV triplet to an integer RGB triplet */ +static void +get_color (gdouble h, + gdouble s, + gdouble v, + gint *r, + gint *g, + gint *b) +{ + hsv_to_rgb (&h, &s, &v); + + *r = floor (h * 255 + 0.5); + *g = floor (s * 255 + 0.5); + *b = floor (v * 255 + 0.5); +} + +#define SWAP(a, b, t) ((t) = (a), (a) = (b), (b) = (t)) + +#define LERP(a, b, v1, v2, i) (((v2) - (v1) != 0) \ + ? ((a) + ((b) - (a)) * ((i) - (v1)) / ((v2) - (v1))) \ + : (a)) + +/* Number of pixels we extend out from the edges when creating + * color source to avoid artifacts + */ +#define PAD 3 + +/* Paints the HSV triangle */ +static void +paint_triangle (GimpColorWheel *wheel, + cairo_t *cr, + gboolean draw_focus) +{ + GtkWidget *widget = GTK_WIDGET (wheel); + GimpColorWheelPrivate *priv = wheel->priv; + gint hx, hy, sx, sy, vx, vy; /* HSV vertices */ + gint x1, y1, r1, g1, b1; /* First vertex in scanline order */ + gint x2, y2, r2, g2, b2; /* Second vertex */ + gint x3, y3, r3, g3, b3; /* Third vertex */ + gint t; + guint32 *buf, *p, c; + gint xl, xr, rl, rr, gl, gr, bl, br; /* Scanline data */ + gint xx, yy; + gint x_interp, y_interp; + gint x_start, x_end; + cairo_surface_t *source; + gdouble r, g, b; + gint stride; + gint width, height; +#if GTK_CHECK_VERSION(3,0,0) + GtkStyleContext *context; + + width = gtk_widget_get_allocated_width (widget); + height = gtk_widget_get_allocated_height (widget); +#else + gchar *detail; + + GtkAllocation allocation; + gtk_widget_get_allocation (widget, &allocation); + width = allocation.width; + height = allocation.height; +#endif + + /* Compute triangle's vertices */ + + compute_triangle (wheel, &hx, &hy, &sx, &sy, &vx, &vy); + + x1 = hx; + y1 = hy; + get_color (priv->h, 1.0, 1.0, &r1, &g1, &b1); + + x2 = sx; + y2 = sy; + get_color (priv->h, 1.0, 0.0, &r2, &g2, &b2); + + x3 = vx; + y3 = vy; + get_color (priv->h, 0.0, 1.0, &r3, &g3, &b3); + + if (y2 > y3) + { + SWAP (x2, x3, t); + SWAP (y2, y3, t); + SWAP (r2, r3, t); + SWAP (g2, g3, t); + SWAP (b2, b3, t); + } + + if (y1 > y3) + { + SWAP (x1, x3, t); + SWAP (y1, y3, t); + SWAP (r1, r3, t); + SWAP (g1, g3, t); + SWAP (b1, b3, t); + } + + if (y1 > y2) + { + SWAP (x1, x2, t); + SWAP (y1, y2, t); + SWAP (r1, r2, t); + SWAP (g1, g2, t); + SWAP (b1, b2, t); + } + + /* Shade the triangle */ + + stride = cairo_format_stride_for_width (CAIRO_FORMAT_RGB24, width); + buf = g_new (guint32, height * stride / 4); + + for (yy = 0; yy < height; yy++) + { + p = buf + yy * width; + + if (yy >= y1 - PAD && yy < y3 + PAD) + { + y_interp = CLAMP (yy, y1, y3); + + if (y_interp < y2) + { + xl = LERP (x1, x2, y1, y2, y_interp); + + rl = LERP (r1, r2, y1, y2, y_interp); + gl = LERP (g1, g2, y1, y2, y_interp); + bl = LERP (b1, b2, y1, y2, y_interp); + } + else + { + xl = LERP (x2, x3, y2, y3, y_interp); + + rl = LERP (r2, r3, y2, y3, y_interp); + gl = LERP (g2, g3, y2, y3, y_interp); + bl = LERP (b2, b3, y2, y3, y_interp); + } + + xr = LERP (x1, x3, y1, y3, y_interp); + + rr = LERP (r1, r3, y1, y3, y_interp); + gr = LERP (g1, g3, y1, y3, y_interp); + br = LERP (b1, b3, y1, y3, y_interp); + + if (xl > xr) + { + SWAP (xl, xr, t); + SWAP (rl, rr, t); + SWAP (gl, gr, t); + SWAP (bl, br, t); + } + + x_start = MAX (xl - PAD, 0); + x_end = MIN (xr + PAD, width); + x_start = MIN (x_start, x_end); + + c = (rl << 16) | (gl << 8) | bl; + + for (xx = 0; xx < x_start; xx++) + *p++ = c; + + for (; xx < x_end; xx++) + { + x_interp = CLAMP (xx, xl, xr); + + *p++ = ((LERP (rl, rr, xl, xr, x_interp) << 16) | + (LERP (gl, gr, xl, xr, x_interp) << 8) | + LERP (bl, br, xl, xr, x_interp)); + } + + c = (rr << 16) | (gr << 8) | br; + + for (; xx < width; xx++) + *p++ = c; + } + } + + source = cairo_image_surface_create_for_data ((unsigned char *)buf, + CAIRO_FORMAT_RGB24, + width, height, stride); + + /* Draw a triangle with the image as a source */ + + cairo_set_source_surface (cr, source, 0, 0); + cairo_surface_destroy (source); + + cairo_move_to (cr, x1, y1); + cairo_line_to (cr, x2, y2); + cairo_line_to (cr, x3, y3); + cairo_close_path (cr); + cairo_fill (cr); + + g_free (buf); + + /* Draw value marker */ + + xx = floor (sx + (vx - sx) * priv->v + (hx - vx) * priv->s * priv->v + 0.5); + yy = floor (sy + (vy - sy) * priv->v + (hy - vy) * priv->s * priv->v + 0.5); + + r = priv->h; + g = priv->s; + b = priv->v; + hsv_to_rgb (&r, &g, &b); + +#if GTK_CHECK_VERSION(3,0,0) + context = gtk_widget_get_style_context (widget); + + gtk_style_context_save (context); +#endif + + if (INTENSITY (r, g, b) > 0.5) + { +#if GTK_CHECK_VERSION(3,0,0) + gtk_style_context_add_class (context, "light-area-focus"); +#else + detail = "colorwheel_light"; +#endif + cairo_set_source_rgb (cr, 0.0, 0.0, 0.0); + } + else + { +#if GTK_CHECK_VERSION(3,0,0) + gtk_style_context_add_class (context, "dark-area-focus"); +#else + detail = "colorwheel_dark"; +#endif + cairo_set_source_rgb (cr, 1.0, 1.0, 1.0); + } + +#define RADIUS 4 +#define FOCUS_RADIUS 6 + + cairo_new_path (cr); + cairo_arc (cr, xx, yy, RADIUS, 0, 2 * G_PI); + cairo_stroke (cr); + + /* Draw focus outline */ + + if (draw_focus && ! priv->focus_on_ring) + { + gint focus_width; + gint focus_pad; + + gtk_widget_style_get (widget, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, + NULL); + +#if GTK_CHECK_VERSION(3,0,0) + gtk_render_focus (context, cr, + xx - FOCUS_RADIUS - focus_width - focus_pad, + yy - FOCUS_RADIUS - focus_width - focus_pad, + 2 * (FOCUS_RADIUS + focus_width + focus_pad), + 2 * (FOCUS_RADIUS + focus_width + focus_pad)); +#else + gtk_widget_get_allocation (widget, &allocation); + gtk_paint_focus (gtk_widget_get_style (widget), + gtk_widget_get_window (widget), + gtk_widget_get_state (widget), + NULL, widget, detail, + allocation.x + xx - FOCUS_RADIUS - focus_width - focus_pad, + allocation.y + yy - FOCUS_RADIUS - focus_width - focus_pad, + 2 * (FOCUS_RADIUS + focus_width + focus_pad), + 2 * (FOCUS_RADIUS + focus_width + focus_pad)); +#endif + } + +#if GTK_CHECK_VERSION(3,0,0) + gtk_style_context_restore (context); +#endif +} + +#if GTK_CHECK_VERSION(3,2,0) +static gboolean +gimp_color_wheel_draw (GtkWidget *widget, + cairo_t *cr) +{ + GimpColorWheel *wheel = GIMP_COLOR_WHEEL (widget); + GimpColorWheelPrivate *priv = wheel->priv; + gboolean draw_focus; + + draw_focus = gtk_widget_has_visible_focus (widget); + + paint_ring (wheel, cr); + paint_triangle (wheel, cr, draw_focus); + + if (draw_focus && priv->focus_on_ring) + { + GtkStyleContext *context = gtk_widget_get_style_context (widget); + + gtk_render_focus (context, cr, 0, 0, + gtk_widget_get_allocated_width (widget), + gtk_widget_get_allocated_height (widget)); + } + + return FALSE; +} +#else +static gint +gimp_color_wheel_expose (GtkWidget *widget, + GdkEventExpose *event) +{ + cairo_t *cr = gdk_cairo_create (gtk_widget_get_window (widget)); + + GimpColorWheel *wheel = GIMP_COLOR_WHEEL (widget); + GimpColorWheelPrivate *priv = wheel->priv; + gboolean draw_focus; + GtkAllocation allocation; + + if (! (event->window == gtk_widget_get_window (widget) && + gtk_widget_is_drawable (widget))) + return FALSE; + + gdk_cairo_region (cr, event->region); + cairo_clip (cr); + + gtk_widget_get_allocation (widget, &allocation); + cairo_translate (cr, allocation.x, allocation.y); + + draw_focus = gtk_widget_has_focus (widget); + + paint_ring (wheel, cr); + paint_triangle (wheel, cr, draw_focus); + + cairo_destroy (cr); + + if (draw_focus && priv->focus_on_ring) + gtk_paint_focus (gtk_widget_get_style (widget), + gtk_widget_get_window (widget), + gtk_widget_get_state (widget), + &event->area, widget, NULL, + allocation.x, + allocation.y, + allocation.width, + allocation.height); + + return FALSE; +} +#endif + +static gboolean +gimp_color_wheel_focus (GtkWidget *widget, + GtkDirectionType dir) +{ + GimpColorWheel *wheel = GIMP_COLOR_WHEEL (widget); + GimpColorWheelPrivate *priv = wheel->priv; + + if (!gtk_widget_has_focus (widget)) + { + if (dir == GTK_DIR_TAB_BACKWARD) + priv->focus_on_ring = FALSE; + else + priv->focus_on_ring = TRUE; + + gtk_widget_grab_focus (widget); + return TRUE; + } + + switch (dir) + { + case GTK_DIR_UP: + if (priv->focus_on_ring) + return FALSE; + else + priv->focus_on_ring = TRUE; + break; + + case GTK_DIR_DOWN: + if (priv->focus_on_ring) + priv->focus_on_ring = FALSE; + else + return FALSE; + break; + + case GTK_DIR_LEFT: + case GTK_DIR_TAB_BACKWARD: + if (priv->focus_on_ring) + return FALSE; + else + priv->focus_on_ring = TRUE; + break; + + case GTK_DIR_RIGHT: + case GTK_DIR_TAB_FORWARD: + if (priv->focus_on_ring) + priv->focus_on_ring = FALSE; + else + return FALSE; + break; + } + + gtk_widget_queue_draw (widget); + + return TRUE; +} + +/** + * gimp_color_wheel_new: + * + * Creates a new HSV color selector. + * + * Return value: A newly-created HSV color selector. + * + * Since: 2.14 + */ +GtkWidget* +gimp_color_wheel_new (void) +{ + return g_object_new (GIMP_TYPE_COLOR_WHEEL, NULL); +} + +/** + * gimp_color_wheel_set_color: + * @hsv: An HSV color selector + * @h: Hue + * @s: Saturation + * @v: Value + * + * Sets the current color in an HSV color selector. + * Color component values must be in the [0.0, 1.0] range. + * + * Since: 2.14 + */ +void +gimp_color_wheel_set_color (GimpColorWheel *wheel, + gdouble h, + gdouble s, + gdouble v) +{ + GimpColorWheelPrivate *priv; + + g_return_if_fail (GIMP_IS_COLOR_WHEEL (wheel)); + g_return_if_fail (h >= 0.0 && h <= 1.0); + g_return_if_fail (s >= 0.0 && s <= 1.0); + g_return_if_fail (v >= 0.0 && v <= 1.0); + + priv = wheel->priv; + + priv->h = h; + priv->s = s; + priv->v = v; + + g_signal_emit (wheel, wheel_signals[CHANGED], 0); + + gtk_widget_queue_draw (GTK_WIDGET (wheel)); +} + +/** + * gimp_color_wheel_get_color: + * @hsv: An HSV color selector + * @h: (out): Return value for the hue + * @s: (out): Return value for the saturation + * @v: (out): Return value for the value + * + * Queries the current color in an HSV color selector. + * Returned values will be in the [0.0, 1.0] range. + * + * Since: 2.14 + */ +void +gimp_color_wheel_get_color (GimpColorWheel *wheel, + gdouble *h, + gdouble *s, + gdouble *v) +{ + GimpColorWheelPrivate *priv; + + g_return_if_fail (GIMP_IS_COLOR_WHEEL (wheel)); + + priv = wheel->priv; + + if (h) *h = priv->h; + if (s) *s = priv->s; + if (v) *v = priv->v; +} + +/** + * gimp_color_wheel_set_ring_fraction: + * @ring: A wheel color selector + * @fraction: Ring fraction + * + * Sets the ring fraction of a wheel color selector. + * + * Since: GIMP 2.10 + */ +void +gimp_color_wheel_set_ring_fraction (GimpColorWheel *hsv, + gdouble fraction) +{ + GimpColorWheelPrivate *priv; + + g_return_if_fail (GIMP_IS_COLOR_WHEEL (hsv)); + + priv = hsv->priv; + + priv->ring_fraction = CLAMP (fraction, 0.01, 0.99); + + gtk_widget_queue_draw (GTK_WIDGET (hsv)); +} + +/** + * gimp_color_wheel_get_ring_fraction: + * @ring: A wheel color selector + * + * Returns value: The ring fraction of the wheel color selector. + * + * Since: GIMP 2.10 + */ +gdouble +gimp_color_wheel_get_ring_fraction (GimpColorWheel *wheel) +{ + GimpColorWheelPrivate *priv; + + g_return_val_if_fail (GIMP_IS_COLOR_WHEEL (wheel), DEFAULT_FRACTION); + + priv = wheel->priv; + + return priv->ring_fraction; +} + +/** + * gimp_color_wheel_is_adjusting: + * @hsv: A #GimpColorWheel + * + * An HSV color selector can be said to be adjusting if multiple rapid + * changes are being made to its value, for example, when the user is + * adjusting the value with the mouse. This function queries whether + * the HSV color selector is being adjusted or not. + * + * Return value: %TRUE if clients can ignore changes to the color value, + * since they may be transitory, or %FALSE if they should consider + * the color value status to be final. + * + * Since: 2.14 + */ +gboolean +gimp_color_wheel_is_adjusting (GimpColorWheel *wheel) +{ + GimpColorWheelPrivate *priv; + + g_return_val_if_fail (GIMP_IS_COLOR_WHEEL (wheel), FALSE); + + priv = wheel->priv; + + return priv->mode != DRAG_NONE; +} + +static void +gimp_color_wheel_move (GimpColorWheel *wheel, + GtkDirectionType dir) +{ + GimpColorWheelPrivate *priv = wheel->priv; + gdouble hue, sat, val; + gint hx, hy, sx, sy, vx, vy; /* HSV vertices */ + gint x, y; /* position in triangle */ + + hue = priv->h; + sat = priv->s; + val = priv->v; + + compute_triangle (wheel, &hx, &hy, &sx, &sy, &vx, &vy); + + x = floor (sx + (vx - sx) * priv->v + (hx - vx) * priv->s * priv->v + 0.5); + y = floor (sy + (vy - sy) * priv->v + (hy - vy) * priv->s * priv->v + 0.5); + +#define HUE_DELTA 0.002 + switch (dir) + { + case GTK_DIR_UP: + if (priv->focus_on_ring) + hue += HUE_DELTA; + else + { + y -= 1; + compute_sv (wheel, x, y, &sat, &val); + } + break; + + case GTK_DIR_DOWN: + if (priv->focus_on_ring) + hue -= HUE_DELTA; + else + { + y += 1; + compute_sv (wheel, x, y, &sat, &val); + } + break; + + case GTK_DIR_LEFT: + if (priv->focus_on_ring) + hue += HUE_DELTA; + else + { + x -= 1; + compute_sv (wheel, x, y, &sat, &val); + } + break; + + case GTK_DIR_RIGHT: + if (priv->focus_on_ring) + hue -= HUE_DELTA + ; + else + { + x += 1; + compute_sv (wheel, x, y, &sat, &val); + } + break; + + default: + /* we don't care about the tab directions */ + break; + } + + /* Wrap */ + if (hue < 0.0) + hue = 1.0; + else if (hue > 1.0) + hue = 0.0; + + gimp_color_wheel_set_color (wheel, hue, sat, val); +} diff --git a/src/ui/widget/gimpcolorwheel.h b/src/ui/widget/gimpcolorwheel.h new file mode 100644 index 000000000..016fb593f --- /dev/null +++ b/src/ui/widget/gimpcolorwheel.h @@ -0,0 +1,95 @@ +/* HSV color selector for GTK+ + * + * Copyright (C) 1999 The Free Software Foundation + * + * Authors: Simon Budig <Simon.Budig@unix-ag.org> (original code) + * Federico Mena-Quintero <federico@gimp.org> (cleanup for GTK+) + * Jonathan Blandford <jrb@redhat.com> (cleanup for GTK+) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +/* + * Modified by the GTK+ Team and others 1997-2000. See the AUTHORS + * file for a list of people on the GTK+ Team. See the ChangeLog + * files for a list of changes. These files are distributed with + * GTK+ at ftp://ftp.gtk.org/pub/gtk/. + */ + +#ifndef __GIMP_COLOR_WHEEL_H__ +#define __GIMP_COLOR_WHEEL_H__ + +G_BEGIN_DECLS + +#define GIMP_TYPE_COLOR_WHEEL (gimp_color_wheel_get_type ()) +#define GIMP_COLOR_WHEEL(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GIMP_TYPE_COLOR_WHEEL, GimpColorWheel)) +#define GIMP_COLOR_WHEEL_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), GIMP_TYPE_COLOR_WHEEL, GimpColorWheelClass)) +#define GIMP_IS_COLOR_WHEEL(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GIMP_TYPE_COLOR_WHEEL)) +#define GIMP_IS_COLOR_WHEEL_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GIMP_TYPE_COLOR_WHEEL)) +#define GIMP_COLOR_WHEEL_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), GIMP_TYPE_COLOR_WHEEL, GimpColorWheelClass)) + + +typedef struct _GimpColorWheel GimpColorWheel; +typedef struct _GimpColorWheelClass GimpColorWheelClass; + +struct _GimpColorWheel +{ + GtkWidget parent_instance; + + /* Private data */ + gpointer priv; +}; + +struct _GimpColorWheelClass +{ + GtkWidgetClass parent_class; + + /* Notification signals */ + void (* changed) (GimpColorWheel *wheel); + + /* Keybindings */ + void (* move) (GimpColorWheel *wheel, + GtkDirectionType type); + + /* Padding for future expansion */ + void (*_gimp_reserved1) (void); + void (*_gimp_reserved2) (void); + void (*_gimp_reserved3) (void); + void (*_gimp_reserved4) (void); +}; + + +GType gimp_color_wheel_get_type (void) G_GNUC_CONST; +GtkWidget * gimp_color_wheel_new (void); + +void gimp_color_wheel_set_color (GimpColorWheel *wheel, + double h, + double s, + double v); +void gimp_color_wheel_get_color (GimpColorWheel *wheel, + gdouble *h, + gdouble *s, + gdouble *v); + +void gimp_color_wheel_set_ring_fraction (GimpColorWheel *wheel, + gdouble fraction); +gdouble gimp_color_wheel_get_ring_fraction (GimpColorWheel *wheel); + +gboolean gimp_color_wheel_is_adjusting (GimpColorWheel *wheel); + +G_END_DECLS + +#endif /* __GIMP_COLOR_WHEEL_H__ */ diff --git a/src/ui/widget/gimpspinscale.c b/src/ui/widget/gimpspinscale.c new file mode 100644 index 000000000..d99646a64 --- /dev/null +++ b/src/ui/widget/gimpspinscale.c @@ -0,0 +1,1225 @@ +/* GIMP - The GNU Image Manipulation Program + * Copyright (C) 1995 Spencer Kimball and Peter Mattis + * + * gimpspinscale.c + * Copyright (C) 2010 Michael Natterer <mitch@gimp.org> + * 2012 Øyvind Kolås <pippin@gimp.org> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include <math.h> +#include <string.h> +#include <gdk/gdkkeysyms.h> + +#include "gimpspinscale.h" + + +enum +{ + PROP_0, + PROP_LABEL, + PROP_FOCUS_WIDGET +}; + +typedef enum +{ + TARGET_NUMBER, + TARGET_UPPER, + TARGET_LOWER +#if WITH_GTKMM_3_0 + ,TARGET_NONE +#endif +} SpinScaleTarget; + +typedef enum +{ + APPEARANCE_FULL = 1, /* Full size suitable for tablets */ + APPEARANCE_COMPACT, /* Compact, suitable for desktops with mouse control */ +} SpinScaleAppearance; + +typedef struct _GimpSpinScalePrivate GimpSpinScalePrivate; + +struct _GimpSpinScalePrivate +{ + gchar *label; + + gboolean scale_limits_set; + gdouble scale_lower; + gdouble scale_upper; + gdouble gamma; + + PangoLayout *layout; + gboolean changing_value; + gboolean relative_change; + gdouble start_x; + gdouble start_value; + + GtkWidget* focusWidget; + gboolean transferFocus; + SpinScaleAppearance appearanceMode; +}; + +#define GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), \ + GIMP_TYPE_SPIN_SCALE, \ + GimpSpinScalePrivate)) + + +static void gimp_spin_scale_dispose (GObject *object); +static void gimp_spin_scale_finalize (GObject *object); +static void gimp_spin_scale_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec); +static void gimp_spin_scale_get_property (GObject *object, + guint property_id, + GValue *value, + GParamSpec *pspec); + +static void gimp_spin_scale_style_set (GtkWidget *widget, + GtkStyle *prev_style); + +#if WITH_GTKMM_3_0 +static void gimp_spin_scale_get_preferred_width (GtkWidget *widget, + gint *minimum_width, + gint *natural_width); +static void gimp_spin_scale_get_preferred_height (GtkWidget *widget, + gint *minimum_width, + gint *natural_width); +static gboolean gimp_spin_scale_draw (GtkWidget *widget, + cairo_t *cr); +#else +static void gimp_spin_scale_size_request (GtkWidget *widget, + GtkRequisition *requisition); + +static gboolean gimp_spin_scale_expose (GtkWidget *widget, + GdkEventExpose *event); +#endif + +static gboolean gimp_spin_scale_button_press (GtkWidget *widget, + GdkEventButton *event); +static gboolean gimp_spin_scale_button_release (GtkWidget *widget, + GdkEventButton *event); +static gboolean gimp_spin_scale_motion_notify (GtkWidget *widget, + GdkEventMotion *event); +static gboolean gimp_spin_scale_leave_notify (GtkWidget *widget, + GdkEventCrossing *event); +static gboolean gimp_spin_scale_keypress( GtkWidget *widget, + GdkEventKey *event); + +static void gimp_spin_scale_defocus( GtkSpinButton *spin_button ); + +static void gimp_spin_scale_value_changed (GtkSpinButton *spin_button); + + +G_DEFINE_TYPE (GimpSpinScale, gimp_spin_scale, GTK_TYPE_SPIN_BUTTON); + +#define parent_class gimp_spin_scale_parent_class + + +static void +gimp_spin_scale_class_init (GimpSpinScaleClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass); + GtkSpinButtonClass *spin_button_class = GTK_SPIN_BUTTON_CLASS (klass); + + object_class->dispose = gimp_spin_scale_dispose; + object_class->finalize = gimp_spin_scale_finalize; + object_class->set_property = gimp_spin_scale_set_property; + object_class->get_property = gimp_spin_scale_get_property; + + widget_class->style_set = gimp_spin_scale_style_set; +#if WITH_GTKMM_3_0 + widget_class->get_preferred_width = gimp_spin_scale_get_preferred_width; + widget_class->get_preferred_height = gimp_spin_scale_get_preferred_height; + widget_class->draw = gimp_spin_scale_draw; +#else + widget_class->size_request = gimp_spin_scale_size_request; + widget_class->expose_event = gimp_spin_scale_expose; +#endif + widget_class->button_press_event = gimp_spin_scale_button_press; + widget_class->button_release_event = gimp_spin_scale_button_release; + widget_class->motion_notify_event = gimp_spin_scale_motion_notify; + widget_class->leave_notify_event = gimp_spin_scale_leave_notify; + widget_class->key_press_event = gimp_spin_scale_keypress; + + spin_button_class->value_changed = gimp_spin_scale_value_changed; + + g_object_class_install_property (object_class, PROP_LABEL, + g_param_spec_string ("label", NULL, NULL, + NULL, + G_PARAM_READWRITE)); + + g_type_class_add_private (klass, sizeof (GimpSpinScalePrivate)); +} + +static void +gimp_spin_scale_init (GimpSpinScale *scale) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (scale); + + gtk_widget_add_events (GTK_WIDGET (scale), + GDK_BUTTON_PRESS_MASK | + GDK_BUTTON_RELEASE_MASK | + GDK_POINTER_MOTION_MASK | + GDK_BUTTON1_MOTION_MASK | + GDK_LEAVE_NOTIFY_MASK); + + gtk_entry_set_alignment (GTK_ENTRY (scale), 1.0); + gtk_spin_button_set_numeric (GTK_SPIN_BUTTON (scale), TRUE); + + private->gamma = 1.0; + private->focusWidget = NULL; + private->transferFocus = FALSE; + private->appearanceMode = APPEARANCE_COMPACT; +} + +static void +gimp_spin_scale_dispose (GObject *object) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (object); + + if (private->layout) + { + g_object_unref (private->layout); + private->layout = NULL; + } + + G_OBJECT_CLASS (parent_class)->dispose (object); +} + +static void +gimp_spin_scale_finalize (GObject *object) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (object); + + if (private->label) + { + g_free (private->label); + private->label = NULL; + } + + G_OBJECT_CLASS (parent_class)->finalize (object); +} + +static void +gimp_spin_scale_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (object); + GimpSpinScale *scale = GIMP_SPIN_SCALE (object); + + switch (property_id) + { + case PROP_LABEL: + gimp_spin_scale_set_label (scale, g_value_get_string (value)); + break; + + case PROP_FOCUS_WIDGET: + { + /* TODO unhook prior */ + private->focusWidget = GTK_WIDGET (g_value_get_pointer (value)); + } + break; + + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gimp_spin_scale_get_property (GObject *object, + guint property_id, + GValue *value, + GParamSpec *pspec) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (object); + GimpSpinScale *scale = GIMP_SPIN_SCALE (object); + + switch (property_id) + { + case PROP_LABEL: + g_value_set_string (value, gimp_spin_scale_get_label (scale)); + break; + + case PROP_FOCUS_WIDGET: + g_value_set_pointer (value, private->focusWidget); + break; + + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + + +void +gimp_spin_scale_set_focuswidget( GtkWidget *scale, GtkWidget* widget ) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (scale); + + /* TODO unhook prior */ + + private->focusWidget = widget; +} + +void +gimp_spin_scale_set_appearance( GtkWidget *widget, const gchar *appearance) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (widget); + + if ( strcmp("full", appearance) == 0 ) { + private->appearanceMode = APPEARANCE_FULL; + } else if ( strcmp("compact", appearance) == 0 ) { + private->appearanceMode = APPEARANCE_COMPACT; + } +} + +#if GTK_CHECK_VERSION(3,0,0) +static void +gimp_spin_scale_get_preferred_width (GtkWidget *widget, + gint *minimum_width, + gint *natural_width) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (widget); + PangoContext *context = gtk_widget_get_pango_context (widget); + PangoFontMetrics *metrics; + + GTK_WIDGET_CLASS (parent_class)->get_preferred_width (widget, + minimum_width, + natural_width); + + metrics = pango_context_get_metrics (context, + pango_context_get_font_description (context), + pango_context_get_language (context)); + + if (private->label) + { + gint char_width; + gint digit_width; + gint char_pixels; + + char_width = pango_font_metrics_get_approximate_char_width (metrics); + digit_width = pango_font_metrics_get_approximate_digit_width (metrics); + char_pixels = PANGO_PIXELS (MAX (char_width, digit_width)); + + /* ~3 chars for the ellipse */ + *minimum_width += char_pixels * 3; + *natural_width += char_pixels * 3; + } + + pango_font_metrics_unref (metrics); +} + +static void +gimp_spin_scale_get_preferred_height (GtkWidget *widget, + gint *minimum_height, + gint *natural_height) +{ + PangoContext *context = gtk_widget_get_pango_context (widget); + PangoFontMetrics *metrics; + //gint height; + + GTK_WIDGET_CLASS (parent_class)->get_preferred_height (widget, + minimum_height, + natural_height); + + metrics = pango_context_get_metrics (context, + pango_context_get_font_description (context), + pango_context_get_language (context)); + + //height = PANGO_PIXELS (pango_font_metrics_get_ascent (metrics) + + // pango_font_metrics_get_descent (metrics)); + + *minimum_height += 1; + *natural_height += 1; + + pango_font_metrics_unref (metrics); +} +#else +static void +gimp_spin_scale_size_request (GtkWidget *widget, + GtkRequisition *requisition) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (widget); + GtkStyle *style = gtk_widget_get_style (widget); + PangoContext *context = gtk_widget_get_pango_context (widget); + PangoFontMetrics *metrics; + gint height; + + GTK_WIDGET_CLASS (parent_class)->size_request (widget, requisition); + + metrics = pango_context_get_metrics (context, style->font_desc, + pango_context_get_language (context)); + + height = PANGO_PIXELS (pango_font_metrics_get_ascent (metrics) + + pango_font_metrics_get_descent (metrics)); + + if (private->appearanceMode == APPEARANCE_COMPACT) { + requisition->height += 1; + } else { + requisition->height += height; + } + + if (private->label) + { + gint char_width; + gint digit_width; + gint char_pixels; + + char_width = pango_font_metrics_get_approximate_char_width (metrics); + digit_width = pango_font_metrics_get_approximate_digit_width (metrics); + char_pixels = PANGO_PIXELS (MAX (char_width, digit_width)); + + /* ~3 chars for the ellipses */ + requisition->width += char_pixels * 3; + } + + pango_font_metrics_unref (metrics); +} +#endif + +static void +gimp_spin_scale_style_set (GtkWidget *widget, + GtkStyle *prev_style) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (widget); + + GTK_WIDGET_CLASS (parent_class)->style_set (widget, prev_style); + + if (private->layout) + { + g_object_unref (private->layout); + private->layout = NULL; + } +} + + +static gboolean +#if GTK_CHECK_VERSION(3,0,0) + gimp_spin_scale_draw (GtkWidget *widget, + cairo_t *cr) +#else + gimp_spin_scale_expose (GtkWidget *widget, + GdkEventExpose *event) +#endif +{ + GimpSpinScalePrivate *private = GET_PRIVATE (widget); +#if GTK_CHECK_VERSION(3,0,0) + GtkStyleContext *style = gtk_widget_get_style_context(widget); + GtkAllocation allocation; + GdkRGBA color; + + cairo_save (cr); + GTK_WIDGET_CLASS (parent_class)->draw (widget, cr); + cairo_restore (cr); + + gtk_widget_get_allocation (widget, &allocation); +#else + GtkStyle *style = gtk_widget_get_style (widget); + cairo_t *cr; + gint w; + + GTK_WIDGET_CLASS (parent_class)->expose_event (widget, event); + + cr = gdk_cairo_create (event->window); + gdk_cairo_region (cr, event->region); + cairo_clip (cr); + + w = gdk_window_get_width (event->window); +#endif + + cairo_set_line_width (cr, 1.0); + +#if GTK_CHECK_VERSION(3,0,0) + if (private->label) + { + GdkRectangle text_area; + gint minimum_width; + gint natural_width; +#else + if (private->label && + gtk_widget_is_drawable (widget) && + event->window == gtk_entry_get_text_window (GTK_ENTRY (widget))) + { + GtkRequisition requisition; + GtkAllocation allocation; +#endif + PangoRectangle logical; + gint layout_offset_x; + gint layout_offset_y; +#if GTK_CHECK_VERSION(3,0,0) + GtkStateFlags state; + GdkRGBA text_color; + GdkRGBA bar_text_color; +#else + GtkStateType state; + GdkColor text_color; + GdkColor bar_text_color; + gint window_width; + gint window_height; +#endif + gdouble progress_fraction; + gint progress_x; + gint progress_y; + gint progress_width; + gint progress_height; + +#if GTK_CHECK_VERSION(3,0,0) + gtk_entry_get_text_area (GTK_ENTRY (widget), &text_area); + + GTK_WIDGET_CLASS (parent_class)->get_preferred_width (widget, + &minimum_width, + &natural_width); +#else + GTK_WIDGET_CLASS (parent_class)->size_request (widget, &requisition); + gtk_widget_get_allocation (widget, &allocation); +#endif + + if (! private->layout) + { + private->layout = gtk_widget_create_pango_layout (widget, + private->label); + pango_layout_set_ellipsize (private->layout, PANGO_ELLIPSIZE_END); + } + + pango_layout_set_width (private->layout, + PANGO_SCALE * +#if GTK_CHECK_VERSION(3,0,0) + (allocation.width - minimum_width)); +#else + (allocation.width - requisition.width)); +#endif + pango_layout_get_pixel_extents (private->layout, NULL, &logical); + + gtk_entry_get_layout_offsets (GTK_ENTRY (widget), NULL, &layout_offset_y); + + if (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_RTL) +#if GTK_CHECK_VERSION(3,0,0) + layout_offset_x = text_area.x + text_area.width - logical.width - 4; +#else + layout_offset_x = w - logical.width - 4; +#endif + else + layout_offset_x = 4; + + layout_offset_x -= logical.x; + +#if GTK_CHECK_VERSION(3,0,0) + state = gtk_widget_get_state_flags (widget); + + gtk_style_context_get_color (style, state, &text_color); + + gtk_style_context_save (style); + gtk_style_context_add_class (style, GTK_STYLE_CLASS_PROGRESSBAR); + gtk_style_context_get_color (style, state, &bar_text_color); + gtk_style_context_restore (style); +#else + state = GTK_STATE_SELECTED; + if (! gtk_widget_get_sensitive (widget)) + state = GTK_STATE_INSENSITIVE; + text_color = style->text[gtk_widget_get_state (widget)]; + bar_text_color = style->fg[state]; + + window_width = gdk_window_get_width (event->window); + window_height = gdk_window_get_height (event->window); +#endif + + progress_fraction = gtk_entry_get_progress_fraction (GTK_ENTRY (widget)); + + if (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_RTL) + { + progress_fraction = 1.0 - progress_fraction; + +#if GTK_CHECK_VERSION(3,0,0) + progress_x = text_area.width * progress_fraction; +#else + progress_x = window_width * progress_fraction; +#endif + progress_y = 0; +#if GTK_CHECK_VERSION(3,0,0) + progress_width = text_area.width - progress_x; + progress_height = text_area.height; +#else + progress_width = window_width - progress_x; + progress_height = window_height; +#endif + } + else + { + progress_x = 0; + progress_y = 0; +#if GTK_CHECK_VERSION(3,0,0) + progress_width = text_area.width * progress_fraction; + progress_height = text_area.height; +#else + progress_width = window_width * progress_fraction; + progress_height = window_height; +#endif + } + + cairo_save (cr); + + cairo_set_fill_rule (cr, CAIRO_FILL_RULE_EVEN_ODD); +#if GTK_CHECK_VERSION(3,0,0) + cairo_rectangle (cr, 0, 0, text_area.width, text_area.height); +#else + cairo_rectangle (cr, 0, 0, window_width, window_height); +#endif + cairo_rectangle (cr, progress_x, progress_y, + progress_width, progress_height); + cairo_clip (cr); + cairo_set_fill_rule (cr, CAIRO_FILL_RULE_WINDING); + +#if GTK_CHECK_VERSION(3,0,0) + cairo_move_to (cr, layout_offset_x, text_area.y + layout_offset_y-3); + gdk_cairo_set_source_rgba (cr, &text_color); +#else + cairo_move_to (cr, layout_offset_x, layout_offset_y-3); + gdk_cairo_set_source_color (cr, &text_color); +#endif + pango_cairo_show_layout (cr, private->layout); + cairo_restore (cr); + + cairo_rectangle (cr, progress_x, progress_y, + progress_width, progress_height); + cairo_clip (cr); + +#if GTK_CHECK_VERSION(3,0,0) + cairo_move_to (cr, layout_offset_x, text_area.y + layout_offset_y-3); + gdk_cairo_set_source_rgba (cr, &bar_text_color); +#else + cairo_move_to (cr, layout_offset_x, layout_offset_y-3); + gdk_cairo_set_source_color (cr, &bar_text_color); +#endif + pango_cairo_show_layout (cr, private->layout); + } + +#if !GTK_CHECK_VERSION(3,0,0) + cairo_destroy (cr); +#endif + + return FALSE; +} + +#if WITH_GTKMM_3_0 +/* Returns TRUE if a translation should be done */ +static gboolean +gtk_widget_get_translation_to_window (GtkWidget *widget, + GdkWindow *window, + int *x, + int *y) +{ + GdkWindow *w, *widget_window; + + if (!gtk_widget_get_has_window (widget)) + { + GtkAllocation allocation; + + gtk_widget_get_allocation (widget, &allocation); + + *x = -allocation.x; + *y = -allocation.y; + } + else + { + *x = 0; + *y = 0; + } + + widget_window = gtk_widget_get_window (widget); + + for (w = window; w && w != widget_window; w = gdk_window_get_parent (w)) + { + int wx, wy; + gdk_window_get_position (w, &wx, &wy); + *x += wx; + *y += wy; + } + + if (w == NULL) + { + *x = 0; + *y = 0; + return FALSE; + } + + return TRUE; +} + +static void +gimp_spin_scale_event_to_widget_coords (GtkWidget *widget, + GdkWindow *window, + gdouble event_x, + gdouble event_y, + gint *widget_x, + gint *widget_y) +{ + gint tx, ty; + + if (gtk_widget_get_translation_to_window (widget, window, &tx, &ty)) + { + event_x += tx; + event_y += ty; + } + + *widget_x = event_x; + *widget_y = event_y; +} +#endif + +static SpinScaleTarget +gimp_spin_scale_get_target (GtkWidget *widget, + gdouble x, + gdouble y) +{ + GtkAllocation allocation; + PangoRectangle logical; + gint layout_x; + gint layout_y; + + gtk_widget_get_allocation (widget, &allocation); + gtk_entry_get_layout_offsets (GTK_ENTRY (widget), &layout_x, &layout_y); + pango_layout_get_pixel_extents (gtk_entry_get_layout (GTK_ENTRY (widget)), + NULL, &logical); + +#if WITH_GTKMM_3_0 + GdkRectangle text_area; + gtk_entry_get_text_area (GTK_ENTRY (widget), &text_area); + + if (x >= text_area.x && x < text_area.width && + y >= text_area.y && y < text_area.height) + { + x -= text_area.x; + y -= text_area.y; + + if (x > layout_x && x < layout_x + logical.width && + y > layout_y && y < layout_y + logical.height) + { + return TARGET_NUMBER; + } + else if (y > text_area.height / 2) + { + return TARGET_LOWER; + } + + return TARGET_UPPER; + } + + return TARGET_NONE; +#else + if (x > layout_x && x < layout_x + logical.width && + y > layout_y && y < layout_y + logical.height) + { + return TARGET_NUMBER; + } + + else if (y > allocation.height / 2) + { + return TARGET_LOWER; + } + return TARGET_UPPER; +#endif +} + +static void +gimp_spin_scale_get_limits (GimpSpinScale *scale, + gdouble *lower, + gdouble *upper) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (scale); + + if (private->scale_limits_set) + { + *lower = private->scale_lower; + *upper = private->scale_upper; + } + else + { + GtkSpinButton *spin_button = GTK_SPIN_BUTTON (scale); + GtkAdjustment *adjustment = gtk_spin_button_get_adjustment (spin_button); + + *lower = gtk_adjustment_get_lower (adjustment); + *upper = gtk_adjustment_get_upper (adjustment); + } +} + +static void +gimp_spin_scale_change_value (GtkWidget *widget, + gdouble x) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (widget); + GtkSpinButton *spin_button = GTK_SPIN_BUTTON (widget); + GtkAdjustment *adjustment = gtk_spin_button_get_adjustment (spin_button); + gdouble lower; + gdouble upper; + gdouble value; +#if WITH_GTKMM_3_0 +#else +#endif +#if WITH_GTKMM_3_0 + GdkRectangle text_area; + gtk_entry_get_text_area (GTK_ENTRY (widget), &text_area); + gimp_spin_scale_get_limits (GIMP_SPIN_SCALE (widget), &lower, &upper); +#else + GdkWindow *text_window = gtk_entry_get_text_window (GTK_ENTRY (widget)); + gint width; + + gimp_spin_scale_get_limits (GIMP_SPIN_SCALE (widget), &lower, &upper); + + width = gdk_window_get_width (text_window); +#endif + + + if (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_RTL) +#if WITH_GTKMM_3_0 + x = text_area.width - x; +#else + x = width - x; +#endif + + + if (private->relative_change) + { + gdouble diff; + gdouble step; + + +#if WITH_GTKMM_3_0 + step = (upper - lower) / text_area.width / 10.0; +#else + step = (upper - lower) / width / 10.0; +#endif + if (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_RTL) + +#if WITH_GTKMM_3_0 + diff = x - (text_area.width - private->start_x); +#else + diff = x - (width - private->start_x); +#endif + else + diff = x - private->start_x; + + value = (private->start_value + diff * step); + } + else + { + gdouble fraction; + + +#if WITH_GTKMM_3_0 + fraction = x / (gdouble) text_area.width; +#else + fraction = x / (gdouble) width; +#endif + if (fraction > 0.0) + fraction = pow (fraction, private->gamma); + + value = fraction * (upper - lower) + lower; + } + + gtk_adjustment_set_value (adjustment, value); +} + +static gboolean +gimp_spin_scale_button_press (GtkWidget *widget, + GdkEventButton *event) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (widget); + + private->changing_value = FALSE; + private->relative_change = FALSE; + +#if WITH_GTKMM_3_0 + gint x, y; + gimp_spin_scale_event_to_widget_coords (widget, event->window, + event->x, event->y, + &x, &y); + switch (gimp_spin_scale_get_target (widget, x, y)) + { + case TARGET_UPPER: + private->changing_value = TRUE; + + gtk_widget_grab_focus (widget); + + gimp_spin_scale_change_value (widget, x); + + return TRUE; + + case TARGET_LOWER: + private->changing_value = TRUE; + + gtk_widget_grab_focus (widget); + + private->relative_change = TRUE; + private->start_x = x; + private->start_value = gtk_adjustment_get_value (gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (widget))); + + return TRUE; + + default: + break; + } +#else + if (event->window == gtk_entry_get_text_window (GTK_ENTRY (widget))) + { + switch (gimp_spin_scale_get_target (widget, event->x, event->y)) + { + case TARGET_UPPER: + private->changing_value = TRUE; + + gtk_widget_grab_focus (widget); + + gimp_spin_scale_change_value (widget, event->x); + + return TRUE; + + case TARGET_LOWER: + private->changing_value = TRUE; + + gtk_widget_grab_focus (widget); + + private->relative_change = TRUE; + private->start_x = event->x; + private->start_value = gtk_adjustment_get_value (gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (widget))); + + return TRUE; + + default: + break; + } + } +#endif + + return GTK_WIDGET_CLASS (parent_class)->button_press_event (widget, event); +} + +static gboolean +gimp_spin_scale_button_release (GtkWidget *widget, + GdkEventButton *event) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (widget); +#if WITH_GTKMM_3_0 + gint x, y; + + gimp_spin_scale_event_to_widget_coords (widget, event->window, + event->x, event->y, + &x, &y); +#endif + + if (private->changing_value) + { + private->changing_value = FALSE; +#if WITH_GTKMM_3_0 + gimp_spin_scale_change_value (widget, x); +#else + gimp_spin_scale_change_value (widget, event->x); +#endif + return TRUE; + } + + return GTK_WIDGET_CLASS (parent_class)->button_release_event (widget, event); +} + +static gboolean +gimp_spin_scale_motion_notify (GtkWidget *widget, + GdkEventMotion *event) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (widget); + + gdk_event_request_motions (event); + +#if WITH_GTKMM_3_0 + gint x, y; + + gimp_spin_scale_event_to_widget_coords (widget, event->window, + event->x, event->y, + &x, &y); +#endif + + if (private->changing_value) + { +#if WITH_GTKMM_3_0 + gimp_spin_scale_change_value (widget, x); +#else + gimp_spin_scale_change_value (widget, event->x); +#endif + + return TRUE; + } + + GTK_WIDGET_CLASS (parent_class)->motion_notify_event (widget, event); + + if (! (event->state & + (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK | GDK_BUTTON3_MASK)) +#if WITH_GTKMM_3_0 +#else + && event->window == gtk_entry_get_text_window (GTK_ENTRY (widget)) +#endif + ) + { + GdkDisplay *display = gtk_widget_get_display (widget); + GdkCursor *cursor = NULL; + +#if WITH_GTKMM_3_0 + switch (gimp_spin_scale_get_target (widget, x, y)) +#else + switch (gimp_spin_scale_get_target (widget, event->x, event->y)) +#endif + { + case TARGET_NUMBER: + cursor = gdk_cursor_new_for_display (display, GDK_XTERM); + break; + + case TARGET_UPPER: + cursor = gdk_cursor_new_for_display (display, GDK_SB_UP_ARROW); + break; + + case TARGET_LOWER: + cursor = gdk_cursor_new_for_display (display, GDK_SB_H_DOUBLE_ARROW); + break; + + default: + break; + } + + +#if WITH_GTKMM_3_0 + if (cursor) + { + gdk_window_set_cursor (event->window, cursor); + g_object_unref (cursor); + } +#else + gdk_window_set_cursor (event->window, cursor); + gdk_cursor_unref (cursor); +#endif + } + + return FALSE; +} + +static gboolean +gimp_spin_scale_leave_notify (GtkWidget *widget, + GdkEventCrossing *event) +{ + gdk_window_set_cursor (event->window, NULL); + + return GTK_WIDGET_CLASS (parent_class)->leave_notify_event (widget, event); +} + +gboolean gimp_spin_scale_keypress( GtkWidget *widget, GdkEventKey *event) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (widget); + guint key = 0; + gdk_keymap_translate_keyboard_state( gdk_keymap_get_for_display( gdk_display_get_default() ), + event->hardware_keycode, (GdkModifierType)event->state, + 0, &key, 0, 0, 0 ); + + switch ( key ) { + + case GDK_KEY_Escape: + case GDK_KEY_Return: + case GDK_KEY_KP_Enter: + { + private->transferFocus = TRUE; + gimp_spin_scale_defocus( GTK_SPIN_BUTTON(widget) ); + } + break; + + } + + return GTK_WIDGET_CLASS (parent_class)->key_press_event (widget, event); +} + +static void +gimp_spin_scale_defocus( GtkSpinButton *spin_button ) +{ + GimpSpinScalePrivate *private = GET_PRIVATE (spin_button); + + if ( private->transferFocus ) { + if ( private->focusWidget ) { + gtk_widget_grab_focus( private->focusWidget ); + } + } +} + +static void +gimp_spin_scale_value_changed (GtkSpinButton *spin_button) +{ + GtkAdjustment *adjustment = gtk_spin_button_get_adjustment (spin_button); + GimpSpinScalePrivate *private = GET_PRIVATE (spin_button); + gdouble lower; + gdouble upper; + gdouble value; + + gimp_spin_scale_get_limits (GIMP_SPIN_SCALE (spin_button), &lower, &upper); + + value = CLAMP (gtk_adjustment_get_value (adjustment), lower, upper); + + gtk_entry_set_progress_fraction (GTK_ENTRY (spin_button), + pow ((value - lower) / (upper - lower), + 1.0 / private->gamma)); + + // TODO - Allow scrollwheel to change value then return focus, + // but clicks/keypress should keep focus in the control + //if ( gtk_widget_has_focus( GTK_WIDGET(spin_button) ) ) { + // gimp_spin_scale_defocus( spin_button ); + //} +} + + +/* public functions */ + +GtkWidget * +gimp_spin_scale_new (GtkAdjustment *adjustment, + const gchar *label, + gint digits) +{ + g_return_val_if_fail (GTK_IS_ADJUSTMENT (adjustment), NULL); + + return g_object_new (GIMP_TYPE_SPIN_SCALE, + "adjustment", adjustment, + "label", label, + "digits", digits, + NULL); +} + +void +gimp_spin_scale_set_label (GimpSpinScale *scale, + const gchar *label) +{ + GimpSpinScalePrivate *private; + + g_return_if_fail (GIMP_IS_SPIN_SCALE (scale)); + + private = GET_PRIVATE (scale); + + if (label == private->label) + return; + + g_free (private->label); + private->label = g_strdup (label); + + if (private->layout) + { + g_object_unref (private->layout); + private->layout = NULL; + } + + gtk_widget_queue_resize (GTK_WIDGET (scale)); + + g_object_notify (G_OBJECT (scale), "label"); +} + +const gchar * +gimp_spin_scale_get_label (GimpSpinScale *scale) +{ + g_return_val_if_fail (GIMP_IS_SPIN_SCALE (scale), NULL); + + return GET_PRIVATE (scale)->label; +} + +void +gimp_spin_scale_set_scale_limits (GimpSpinScale *scale, + gdouble lower, + gdouble upper) +{ + GimpSpinScalePrivate *private; + GtkSpinButton *spin_button; + GtkAdjustment *adjustment; + + g_return_if_fail (GIMP_IS_SPIN_SCALE (scale)); + + private = GET_PRIVATE (scale); + spin_button = GTK_SPIN_BUTTON (scale); + adjustment = gtk_spin_button_get_adjustment (spin_button); + + g_return_if_fail (lower >= gtk_adjustment_get_lower (adjustment)); + g_return_if_fail (upper <= gtk_adjustment_get_upper (adjustment)); + + private->scale_limits_set = TRUE; + private->scale_lower = lower; + private->scale_upper = upper; + private->gamma = 1.0; + + gimp_spin_scale_value_changed (spin_button); +} + +void +gimp_spin_scale_unset_scale_limits (GimpSpinScale *scale) +{ + GimpSpinScalePrivate *private; + + g_return_if_fail (GIMP_IS_SPIN_SCALE (scale)); + + private = GET_PRIVATE (scale); + + private->scale_limits_set = FALSE; + private->scale_lower = 0.0; + private->scale_upper = 0.0; + + gimp_spin_scale_value_changed (GTK_SPIN_BUTTON (scale)); +} + +gboolean +gimp_spin_scale_get_scale_limits (GimpSpinScale *scale, + gdouble *lower, + gdouble *upper) +{ + GimpSpinScalePrivate *private; + + g_return_val_if_fail (GIMP_IS_SPIN_SCALE (scale), FALSE); + + private = GET_PRIVATE (scale); + + if (lower) + *lower = private->scale_lower; + + if (upper) + *upper = private->scale_upper; + + return private->scale_limits_set; +} + +void +gimp_spin_scale_set_gamma (GimpSpinScale *scale, + gdouble gamma) +{ + GimpSpinScalePrivate *private; + + g_return_if_fail (GIMP_IS_SPIN_SCALE (scale)); + + private = GET_PRIVATE (scale); + + private->gamma = gamma; + + gimp_spin_scale_value_changed (GTK_SPIN_BUTTON (scale)); +} + +gdouble +gimp_spin_scale_get_gamma (GimpSpinScale *scale) +{ + g_return_val_if_fail (GIMP_IS_SPIN_SCALE (scale), 1.0); + + return GET_PRIVATE(scale)->gamma; +} diff --git a/src/ui/widget/gimpspinscale.h b/src/ui/widget/gimpspinscale.h new file mode 100644 index 000000000..b42a0faf8 --- /dev/null +++ b/src/ui/widget/gimpspinscale.h @@ -0,0 +1,82 @@ +/* GIMP - The GNU Image Manipulation Program + * Copyright (C) 1995 Spencer Kimball and Peter Mattis + * + * gimpspinscale.h + * Copyright (C) 2010 Michael Natterer <mitch@gimp.org> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef __GIMP_SPIN_SCALE_H__ +#define __GIMP_SPIN_SCALE_H__ + +#ifndef WITH_GIMP +#include <gtk/gtk.h> +#endif + +G_BEGIN_DECLS + +#define GIMP_TYPE_SPIN_SCALE (gimp_spin_scale_get_type ()) +#define GIMP_SPIN_SCALE(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GIMP_TYPE_SPIN_SCALE, GimpSpinScale)) +#define GIMP_SPIN_SCALE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), GIMP_TYPE_SPIN_SCALE, GimpSpinScaleClass)) +#define GIMP_IS_SPIN_SCALE(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GIMP_TYPE_SPIN_SCALE)) +#define GIMP_IS_SPIN_SCALE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GIMP_TYPE_SPIN_SCALE)) +#define GIMP_SPIN_SCALE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), GIMP_TYPE_SPIN_SCALE, GimpSpinScaleClass)) + + +typedef struct _GimpSpinScale GimpSpinScale; +typedef struct _GimpSpinScaleClass GimpSpinScaleClass; + +struct _GimpSpinScale +{ + GtkSpinButton parent_instance; +}; + +struct _GimpSpinScaleClass +{ + GtkSpinButtonClass parent_class; +}; + + +GType gimp_spin_scale_get_type (void) G_GNUC_CONST; + +GtkWidget * gimp_spin_scale_new (GtkAdjustment *adjustment, + const gchar *label, + gint digits); + +void gimp_spin_scale_set_label (GimpSpinScale *scale, + const gchar *label); +const gchar * gimp_spin_scale_get_label (GimpSpinScale *scale); + +void gimp_spin_scale_set_scale_limits (GimpSpinScale *scale, + gdouble lower, + gdouble upper); +void gimp_spin_scale_unset_scale_limits (GimpSpinScale *scale); +gboolean gimp_spin_scale_get_scale_limits (GimpSpinScale *scale, + gdouble *lower, + gdouble *upper); + +void gimp_spin_scale_set_gamma (GimpSpinScale *scale, + gdouble gamma); +gdouble gimp_spin_scale_get_gamma (GimpSpinScale *scale); + +void gimp_spin_scale_set_focuswidget (GtkWidget *scale, + GtkWidget *widget); + +void gimp_spin_scale_set_appearance (GtkWidget *scale, + const gchar *appearance); + +G_END_DECLS + +#endif /* __GIMP_SPIN_SCALE_H__ */ diff --git a/src/ui/widget/handlebox.cpp b/src/ui/widget/handlebox.cpp deleted file mode 100644 index 0ac84ef3a..000000000 --- a/src/ui/widget/handlebox.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Author: - * Derek P. Moore <derekm@hackunix.org> - * - * Copyright (C) 2004 Derek P. Moore - * - * Released under GNU GPL. Read the file 'COPYING' for more information. - */ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include "handlebox.h" - -namespace Inkscape { -namespace UI { -namespace Widget { - -HandleBox::HandleBox(Gtk::Widget *widget, - Gtk::PositionType position) - : _widget(widget) -{ - g_assert(_widget != NULL); - add(*Gtk::manage(_widget)); - set_handle_position(position); -} - -} // namespace Widget -} // namespace UI -} // namespace Inkscape - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=c++:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/widget/handlebox.h b/src/ui/widget/handlebox.h deleted file mode 100644 index db384552b..000000000 --- a/src/ui/widget/handlebox.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * Author: - * Derek P. Moore <derekm@hackunix.org> - * - * Copyright (C) 2004 Derek P. Moore - * - * Released under GNU GPL. Read the file 'COPYING' for more information. - */ - -#ifndef INKSCAPE_UI_WIDGET_HANDLEBOX_H -#define INKSCAPE_UI_WIDGET_HANDLEBOX_H - -#include <gtkmm/handlebox.h> - -namespace Inkscape { -namespace UI { -namespace Widget { - -/** - * Adds a detachment handle to another widget. - * - * This work really doesn't amount to much more than a convenience constructor - * for Gtk::HandleBox. Maybe this could be contributed back to Gtkmm, as - * Gtkmm provides several convenience constructors for other widgets as well. - */ -class HandleBox : public Gtk::HandleBox -{ -public: - HandleBox(Gtk::Widget *widget, - Gtk::PositionType position = Gtk::POS_LEFT); - -protected: - Gtk::Widget *_widget; -}; - -} // namespace Widget -} // namespace UI -} // namespace Inkscape - -#endif // INKSCAPE_UI_WIDGET_HANDLEBOX_H - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=c++:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/widget/icon-widget.cpp b/src/ui/widget/icon-widget.cpp deleted file mode 100644 index 0e0736371..000000000 --- a/src/ui/widget/icon-widget.cpp +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Author: - * Bryce Harrington <bryce@bryceharrington.org> - * - * Copyright (C) 2004 Bryce Harrington - * based on work by Lauris Kaplinski in 2002 released under GPL - * - * Released under GNU GPL. Read the file 'COPYING' for more information - */ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <glib.h> -#include "icon-widget.h" - -namespace Inkscape { -namespace UI { -namespace Widget { - -IconWidget::IconWidget() : - _size(0), - _pb(0), - _do_bitmap_icons(false) -{ -} - -IconWidget::IconWidget(int unsigned size, int unsigned scale, gchar const *name) : - _pb(0), - _do_bitmap_icons(false) -{ - _size = std::max((int unsigned)128, std::min(size, (int unsigned)1)); - - char c[256]; - g_snprintf (c, 256, "%d:%d:%s", _size, scale, name); - guchar *pixels = image_load_gtk(name, _size, scale); - - if (pixels == NULL) { - g_warning("Couldn't find matching icon for %s - has this application been installed?", name); - //_pb = NULL; - } else { - /* TODO - _pb = gdk_pixbuf_new_from_data(pixels, GDK_COLORSPACE_RGB, - TRUE, 8, _size, _size, _size * 4, - (GdkPixbufDestroyNotify)g_free, NULL); - */ - } -} - -IconWidget::IconWidget(int unsigned size, guchar const */*px*/) : - _pb(0), - _do_bitmap_icons(false) -{ - _size = std::max((int unsigned)128, std::min(size, (int unsigned)1)); - - /* - _pb = gdk_pixbuf_new_from_data((guchar *)px, GDK_COLORSPACE_RGB, - TRUE, 8, _size, _size, _size * 4, NULL, NULL); - */ -} - -IconWidget::~IconWidget() { -} - -void IconWidget::size_request(Gtk::Requisition &requisition) -{ - requisition.width = _size; - requisition.height = _size; -} - -void IconWidget::size_allocate(Gtk::Allocation const &allocation) -{ - Gtk::Widget::size_allocate(allocation); - - if (this->get_is_drawable()) { - this->queue_draw(); - } -} - -int IconWidget::expose(GdkEventExpose *event) -{ - if (this->get_is_drawable()) { - paint(&(event->area)); - } - return true; -} - -void IconWidget::paint(GdkRectangle const *area) -{ - Gtk::Allocation allocation = get_allocation(); - int const x_pad = std::max(0, (allocation.get_width() - _size)/2); - int const y_pad = std::max(0, (allocation.get_height() - _size)/2); - - int const x_max = std::max(area->x, allocation.get_x() + x_pad); - int const y_max = std::max(area->y, allocation.get_y() + y_pad); - int const x_min = std::min(area->x + area->width, - allocation.get_x() + x_pad + _size); - int const y_min = std::min(area->y + area->height, - allocation.get_y() + y_pad + _size); - - if (_pb) { - gdk_draw_pixbuf(this->get_window()->gobj(), NULL, _pb, - x_max - allocation.get_x() - x_pad, - y_max - allocation.get_y() - y_pad, - x_max, y_max, - x_min - x_max, y_min - y_max, - GDK_RGB_DITHER_NORMAL, x_max, y_max); - } -} - -guchar* IconWidget::image_load(gchar const *name, int unsigned size, int unsigned scale) -{ - guchar *px; - - if (_do_bitmap_icons) { - px = image_load_pixmap(name, size, scale); - if (!px) { - px = image_load_svg(name, size, scale); - } - } else { - px = image_load_svg(name, size, scale); - if (!px) { - px = image_load_pixmap(name, size, scale); - } - } - return px; -} - -guchar* IconWidget::image_load_pixmap(gchar const */*name*/, int unsigned /*size*/, int unsigned /*scale*/) -{ - // TODO - return NULL; -} - -guchar* IconWidget::image_load_svg(gchar const */*name*/, int unsigned /*size*/, int unsigned /*scale*/) -{ - // TODO - return NULL; -} - -guchar* IconWidget::image_load_gtk(gchar const */*name*/, int unsigned /*size*/, int unsigned /*scale*/) -{ - // TODO - return NULL; -} - -} // namespace Widget -} // namespace UI -} // namespace Inkscape - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=c++:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/widget/icon-widget.h b/src/ui/widget/icon-widget.h deleted file mode 100644 index 329702f2e..000000000 --- a/src/ui/widget/icon-widget.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Author: - * Bryce Harrington <bryce@bryceharrington.org> - * - * Copyright (C) 2004 Bryce Harrington - * - * Released under GNU GPL. Read the file 'COPYING' for more information - */ - -#ifndef INKSCAPE_UI_WIDGET_ICON_H -#define INKSCAPE_UI_WIDGET_ICON_H - -#include <gtkmm/image.h> -#include <gdkmm/rectangle.h> - -namespace Inkscape { -namespace UI { -namespace Widget { - -/** - * Icon Widget - General image widget (including SVG icons). - */ -class IconWidget : public Gtk::Widget -{ -public: - IconWidget(); - IconWidget(int unsigned size, int unsigned scale, gchar const *name); - IconWidget(int unsigned size, guchar const *px); - virtual ~IconWidget(); - - // Overrides of Gtk::Widget functions - void size_request(Gtk::Requisition &requisition); - void size_allocate(Gtk::Allocation const &allocation); - - int expose(GdkEventExpose *event); - void paint(GdkRectangle const *area); - guchar* image_load(gchar const *name, int unsigned size, int unsigned scale); - guchar* image_load_pixmap(gchar const *name, int unsigned size, int unsigned scale); - guchar* image_load_svg(gchar const *name, int unsigned size, int unsigned scale); - guchar* image_load_gtk(gchar const *name, int unsigned size, int unsigned scale); - -protected: - int _size; - GdkPixbuf *_pb; - bool _do_bitmap_icons; -}; - - -} // namespace Widget -} // namespace UI -} // namespace Inkscape - -#endif // INKSCAPE_UI_WIDGET_ICON_H - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=c++:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/widget/imageicon.cpp b/src/ui/widget/imageicon.cpp index 77015bdd2..cf41a16a4 100644 --- a/src/ui/widget/imageicon.cpp +++ b/src/ui/widget/imageicon.cpp @@ -19,6 +19,8 @@ #include "svg-view-widget.h" #include "document.h" #include "inkscape.h" +#include <glibmm/convert.h> +#include <glibmm/fileutils.h> namespace Inkscape @@ -115,7 +117,7 @@ bool ImageIcon::showSvgDocument(const SPDocument *docArg) viewerGtkmm->show(); pack_start(*viewerGtkmm, TRUE, TRUE, 0); - //GtkWidget *vbox = (GtkWidget *)gobj(); + //GtkWidget *vbox = GTK_WIDGET(gobj()); //gtk_box_pack_start(GTK_BOX(vbox), viewerGtk, TRUE, TRUE, 0); return true; @@ -304,7 +306,7 @@ void ImageIcon::showBrokenImage(const Glib::ustring &errorMessage) "</svg>"; //Fill in the template - char *cErrorMessage = (char *)errorMessage.c_str(); + char *cErrorMessage = const_cast<char *>(errorMessage.c_str()); gchar *xmlBuffer = g_strdup_printf(xformat, cErrorMessage); //g_message("%s\n", xmlBuffer); @@ -373,14 +375,14 @@ bool ImageIcon::show(const Glib::ustring &fileName) if (!Glib::file_test(fileName, Glib::FILE_TEST_EXISTS)) return false; - gchar *fName = (gchar *)fileName.c_str(); + gchar *fName = const_cast<gchar *>(fileName.c_str()); //g_message("fname:%s\n", fName); if (Glib::file_test(fileName, Glib::FILE_TEST_IS_REGULAR)) { struct stat info; - if (stat(fName, &info)) + if (g_file_test (fName, G_FILE_TEST_EXISTS) && stat(fName, &info)) { Glib::ustring err = "cannot get file info"; showBrokenImage(err); diff --git a/src/ui/widget/imageicon.h b/src/ui/widget/imageicon.h index 803b2f53f..8faf13cb1 100644 --- a/src/ui/widget/imageicon.h +++ b/src/ui/widget/imageicon.h @@ -12,9 +12,16 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ -#include <glibmm/ustring.h> -#include <gtkmm/box.h> +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif +#include <gtkmm/box.h> +#include <glibmm/ustring.h> class SPDocument; diff --git a/src/ui/widget/imagetoggler.cpp b/src/ui/widget/imagetoggler.cpp index 6517219f2..29907f4c9 100644 --- a/src/ui/widget/imagetoggler.cpp +++ b/src/ui/widget/imagetoggler.cpp @@ -53,13 +53,44 @@ ImageToggler::ImageToggler( char const* on, char const* off) : property_pixbuf() = _property_pixbuf_off.get_value(); } -void -ImageToggler::get_size_vfunc( Gtk::Widget& widget, - const Gdk::Rectangle* cell_area, - int* x_offset, - int* y_offset, - int* width, - int* height ) const + +#if WITH_GTKMM_3_0 +void ImageToggler::get_preferred_height_vfunc(Gtk::Widget& widget, + int& min_h, + int& nat_h) const +{ + Gtk::CellRendererPixbuf::get_preferred_height_vfunc(widget, min_h, nat_h); + + if (min_h) { + min_h += (min_h) >> 1; + } + + if (nat_h) { + nat_h += (nat_h) >> 1; + } +} + +void ImageToggler::get_preferred_width_vfunc(Gtk::Widget& widget, + int& min_w, + int& nat_w) const +{ + Gtk::CellRendererPixbuf::get_preferred_width_vfunc(widget, min_w, nat_w); + + if (min_w) { + min_w += (min_w) >> 1; + } + + if (nat_w) { + nat_w += (nat_w) >> 1; + } +} +#else +void ImageToggler::get_size_vfunc(Gtk::Widget& widget, + const Gdk::Rectangle* cell_area, + int* x_offset, + int* y_offset, + int* width, + int* height ) const { Gtk::CellRendererPixbuf::get_size_vfunc( widget, cell_area, x_offset, y_offset, width, height ); @@ -70,18 +101,29 @@ ImageToggler::get_size_vfunc( Gtk::Widget& widget, *height += (*height) >> 1; } } - - -void -ImageToggler::render_vfunc( const Glib::RefPtr<Gdk::Drawable>& window, - Gtk::Widget& widget, - const Gdk::Rectangle& background_area, - const Gdk::Rectangle& cell_area, - const Gdk::Rectangle& expose_area, - Gtk::CellRendererState flags ) +#endif + +#if WITH_GTKMM_3_0 +void ImageToggler::render_vfunc( const Cairo::RefPtr<Cairo::Context>& cr, + Gtk::Widget& widget, + const Gdk::Rectangle& background_area, + const Gdk::Rectangle& cell_area, + Gtk::CellRendererState flags ) +#else +void ImageToggler::render_vfunc( const Glib::RefPtr<Gdk::Drawable>& window, + Gtk::Widget& widget, + const Gdk::Rectangle& background_area, + const Gdk::Rectangle& cell_area, + const Gdk::Rectangle& expose_area, + Gtk::CellRendererState flags ) +#endif { property_pixbuf() = _property_active.get_value() ? _property_pixbuf_on : _property_pixbuf_off; +#if WITH_GTKMM_3_0 + Gtk::CellRendererPixbuf::render_vfunc( cr, widget, background_area, cell_area, flags ); +#else Gtk::CellRendererPixbuf::render_vfunc( window, widget, background_area, cell_area, expose_area, flags ); +#endif } bool diff --git a/src/ui/widget/imagetoggler.h b/src/ui/widget/imagetoggler.h index 6389ce8af..df6eb7ded 100644 --- a/src/ui/widget/imagetoggler.h +++ b/src/ui/widget/imagetoggler.h @@ -10,9 +10,17 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ -#include <glibmm/property.h> +#if HAVE_CONFIG_H +#include "config.h" +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/cellrendererpixbuf.h> #include <gtkmm/widget.h> +#include <glibmm/property.h> namespace Inkscape { namespace UI { @@ -33,17 +41,32 @@ public: protected: - virtual void get_size_vfunc( Gtk::Widget &widget, - Gdk::Rectangle const *cell_area, - int *x_offset, int *y_offset, int *width, int *height ) const; - +#if WITH_GTKMM_3_0 + virtual void render_vfunc( const Cairo::RefPtr<Cairo::Context>& cr, + Gtk::Widget& widget, + const Gdk::Rectangle& background_area, + const Gdk::Rectangle& cell_area, + Gtk::CellRendererState flags ); + virtual void get_preferred_width_vfunc(Gtk::Widget& widget, + int& min_w, + int& nat_w) const; + + virtual void get_preferred_height_vfunc(Gtk::Widget& widget, + int& min_h, + int& nat_h) const; +#else virtual void render_vfunc( const Glib::RefPtr<Gdk::Drawable>& window, Gtk::Widget& widget, const Gdk::Rectangle& background_area, const Gdk::Rectangle& cell_area, const Gdk::Rectangle& expose_area, Gtk::CellRendererState flags ); + + virtual void get_size_vfunc( Gtk::Widget &widget, + Gdk::Rectangle const *cell_area, + int *x_offset, int *y_offset, int *width, int *height ) const; +#endif virtual bool activate_vfunc(GdkEvent *event, Gtk::Widget &widget, diff --git a/src/ui/widget/labelled.cpp b/src/ui/widget/labelled.cpp index df800545a..6e3652830 100644 --- a/src/ui/widget/labelled.cpp +++ b/src/ui/widget/labelled.cpp @@ -71,6 +71,17 @@ Labelled::setLabelText(const Glib::ustring &str) _label->set_text(str); } +void +Labelled::setTooltipText(const Glib::ustring &tooltip) +{ + _label->set_tooltip_text(tooltip); + _widget->set_tooltip_text(tooltip); +} + +bool Labelled::on_mnemonic_activate ( bool group_cycling ) +{ + return _widget->mnemonic_activate ( group_cycling ); +} } // namespace Widget } // namespace UI diff --git a/src/ui/widget/labelled.h b/src/ui/widget/labelled.h index e49b289fe..5334454bc 100644 --- a/src/ui/widget/labelled.h +++ b/src/ui/widget/labelled.h @@ -11,6 +11,14 @@ #ifndef INKSCAPE_UI_WIDGET_LABELLED_H #define INKSCAPE_UI_WIDGET_LABELLED_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> namespace Gtk { @@ -54,8 +62,13 @@ public: Gtk::Label const *getLabel() const; void setLabelText(const Glib::ustring &str); + void setTooltipText(const Glib::ustring &tooltip); + +private: + virtual bool on_mnemonic_activate( bool group_cycling ); protected: + Gtk::Widget *_widget; Gtk::Label *_label; Gtk::Label *_suffix; diff --git a/src/ui/widget/layer-selector.cpp b/src/ui/widget/layer-selector.cpp index c6622627b..7b1a8dbfb 100644 --- a/src/ui/widget/layer-selector.cpp +++ b/src/ui/widget/layer-selector.cpp @@ -34,6 +34,7 @@ #include "widgets/icon.h" #include "widgets/shrink-wrap-button.h" #include "xml/node-event-vector.h" +#include "widgets/gradient-vector.h" namespace Inkscape { namespace Widgets { @@ -162,17 +163,6 @@ LayerSelector::~LayerSelector() { _selection_changed_connection.disconnect(); } -namespace { - -/** Helper function - detaches desktop from selector - */ -bool detach(LayerSelector *selector) { - selector->setDesktop(NULL); - return FALSE; -} - -} - /** Sets the desktop for the widget. First disconnects signals * for the current desktop, then stores the pointer to the * given \a desktop, and attaches its signals to this one. @@ -185,7 +175,10 @@ void LayerSelector::setDesktop(SPDesktop *desktop) { if (_desktop) { // _desktop_shutdown_connection.disconnect(); - _layer_changed_connection.disconnect(); + if (_current_layer_changed_connection) + _current_layer_changed_connection.disconnect(); + if (_layers_changed_connection) + _layers_changed_connection.disconnect(); // g_signal_handlers_disconnect_by_func(_desktop, (gpointer)&detach, this); } _desktop = desktop; @@ -195,9 +188,13 @@ void LayerSelector::setDesktop(SPDesktop *desktop) { // sigc::bind (sigc::ptr_fun (detach), this)); // g_signal_connect_after(_desktop, "shutdown", GCallback(detach), this); - _layer_changed_connection = _desktop->connectCurrentLayerChanged( - sigc::mem_fun(*this, &LayerSelector::_selectLayer) - ); + LayerManager *mgr = _desktop->layer_manager; + if ( mgr ) { + _current_layer_changed_connection = mgr->connectCurrentLayerChanged( sigc::mem_fun(*this, &LayerSelector::_selectLayer) ); + //_layerUpdatedConnection = mgr->connectLayerDetailsChanged( sigc::mem_fun(*this, &LayerSelector::_updateLayer) ); + _layers_changed_connection = mgr->connectChanged( sigc::mem_fun(*this, &LayerSelector::_layersChanged) ); + } + _selectLayer(_desktop->currentLayer()); } } @@ -230,6 +227,17 @@ private: } +void LayerSelector::_layersChanged() +{ + if (_desktop) { + /* + * This code fixes #166691 but causes issues #1066543 and #1080378. + * Comment out until solution found. + */ + //_selectLayer(_desktop->currentLayer()); + } +} + /** Selects the given layer in the dropdown selector. */ void LayerSelector::_selectLayer(SPObject *layer) { @@ -300,11 +308,13 @@ void LayerSelector::_setDesktopLayer() { Gtk::ListStore::iterator selected(_selector.get_active()); SPObject *layer=_selector.get_active()->get_value(_model_columns.object); if ( _desktop && layer ) { - _layer_changed_connection.block(); + _current_layer_changed_connection.block(); + _layers_changed_connection.block(); _desktop->layer_manager->setCurrentLayer(layer); - _layer_changed_connection.unblock(); + _current_layer_changed_connection.unblock(); + _layers_changed_connection.unblock(); _selectLayer(_desktop->currentLayer()); } @@ -565,7 +575,7 @@ void LayerSelector::_prepareLabelRenderer( gchar const *label; if ( object != root ) { label = object->label(); - if (!label) { + if (!object->label()) { label = object->defaultLabel(); label_defaulted = true; } @@ -573,7 +583,7 @@ void LayerSelector::_prepareLabelRenderer( label = _("(root)"); } - gchar *text = g_markup_printf_escaped(format, label); + gchar *text = g_markup_printf_escaped(format, gr_ellipsize_text (label, 50).c_str()); _label_renderer.property_markup() = text; g_free(text); g_free(format); @@ -585,6 +595,7 @@ void LayerSelector::_prepareLabelRenderer( _label_renderer.property_style() = ( label_defaulted ? Pango::STYLE_ITALIC : Pango::STYLE_NORMAL ); + } void LayerSelector::_lockLayer(bool lock) { diff --git a/src/ui/widget/layer-selector.h b/src/ui/widget/layer-selector.h index 6fbdc9857..ff9e4ddfc 100644 --- a/src/ui/widget/layer-selector.h +++ b/src/ui/widget/layer-selector.h @@ -68,7 +68,8 @@ private: Glib::RefPtr<Gtk::ListStore> _layer_model; // sigc::connection _desktop_shutdown_connection; - sigc::connection _layer_changed_connection; + sigc::connection _layers_changed_connection; + sigc::connection _current_layer_changed_connection; sigc::connection _selection_changed_connection; sigc::connection _visibility_toggled_connection; sigc::connection _lock_toggled_connection; @@ -76,6 +77,8 @@ private: SPObject *_layer; void _selectLayer(SPObject *layer); + void _layersChanged(); + void _setDesktopLayer(); void _buildEntry(unsigned depth, SPObject &object); diff --git a/src/ui/widget/licensor.cpp b/src/ui/widget/licensor.cpp index d31d4b759..c729354cb 100644 --- a/src/ui/widget/licensor.cpp +++ b/src/ui/widget/licensor.cpp @@ -25,6 +25,7 @@ #include "rdf.h" #include "inkscape.h" #include "document-undo.h" +#include "document-private.h" #include "verbs.h" #include <gtkmm/radiobutton.h> @@ -43,7 +44,7 @@ const struct rdf_license_t _other_license = class LicenseItem : public Gtk::RadioButton { public: - LicenseItem (struct rdf_license_t const* license, EntityEntry* entity, Registry &wr); + LicenseItem (struct rdf_license_t const* license, EntityEntry* entity, Registry &wr, Gtk::RadioButtonGroup *group); protected: void on_toggled(); struct rdf_license_t const *_lic; @@ -51,13 +52,12 @@ protected: Registry &_wr; }; -LicenseItem::LicenseItem (struct rdf_license_t const* license, EntityEntry* entity, Registry &wr) +LicenseItem::LicenseItem (struct rdf_license_t const* license, EntityEntry* entity, Registry &wr, Gtk::RadioButtonGroup *group) : Gtk::RadioButton(_(license->name)), _lic(license), _eep(entity), _wr(wr) { - static Gtk::RadioButtonGroup group = get_group(); - static bool first = true; - if (first) first = false; - else set_group (group); + if (group) { + set_group (*group); + } } /// \pre it is assumed that the license URI entry is a Gtk::Entry @@ -66,9 +66,11 @@ void LicenseItem::on_toggled() if (_wr.isUpdating()) return; _wr.setUpdating (true); - rdf_set_license (SP_ACTIVE_DOCUMENT, _lic->details ? _lic : 0); - DocumentUndo::done(SP_ACTIVE_DOCUMENT, SP_VERB_NONE, - /* TODO: annotate */ "licensor.cpp:65"); + SPDocument *doc = SP_ACTIVE_DOCUMENT; + rdf_set_license (doc, _lic->details ? _lic : 0); + if (doc->priv->sensitive) { + DocumentUndo::done(doc, SP_VERB_NONE, "Document license updated"); + } _wr.setUpdating (false); static_cast<Gtk::Entry*>(_eep->_packable)->set_text (_lic->uri); _eep->on_changed(); @@ -77,7 +79,8 @@ void LicenseItem::on_toggled() //--------------------------------------------------- Licensor::Licensor() -: Gtk::VBox(false,4) +: Gtk::VBox(false,4), + _eentry (NULL) { } @@ -94,18 +97,19 @@ void Licensor::init (Registry& wr) LicenseItem *i; wr.setUpdating (true); - i = manage (new LicenseItem (&_proprietary_license, _eentry, wr)); + i = manage (new LicenseItem (&_proprietary_license, _eentry, wr, NULL)); + Gtk::RadioButtonGroup group = i->get_group(); add (*i); LicenseItem *pd = i; for (struct rdf_license_t * license = rdf_licenses; license && license->name; license++) { - i = manage (new LicenseItem (license, _eentry, wr)); + i = manage (new LicenseItem (license, _eentry, wr, &group)); add(*i); } // add Other at the end before the URI field for the confused ppl. - LicenseItem *io = manage (new LicenseItem (&_other_license, _eentry, wr)); + LicenseItem *io = manage (new LicenseItem (&_other_license, _eentry, wr, &group)); add (*io); pd->set_active(); @@ -130,10 +134,18 @@ void Licensor::update (SPDocument *doc) for (i=0; rdf_licenses[i].name; i++) if (license == &rdf_licenses[i]) break; +#if WITH_GTKMM_3_0 + static_cast<LicenseItem*>(get_children()[i+1])->set_active(); +#else static_cast<LicenseItem*>(children()[i+1].get_widget())->set_active(); +#endif } else { +#if WITH_GTKMM_3_0 + static_cast<LicenseItem*>(get_children()[0])->set_active(); +#else static_cast<LicenseItem*>(children()[0].get_widget())->set_active(); +#endif } /* update the URI */ diff --git a/src/ui/widget/licensor.h b/src/ui/widget/licensor.h index ab6abd0a4..0ac3e5ab8 100644 --- a/src/ui/widget/licensor.h +++ b/src/ui/widget/licensor.h @@ -10,6 +10,14 @@ #ifndef INKSCAPE_UI_WIDGET_LICENSOR_H #define INKSCAPE_UI_WIDGET_LICENSOR_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> class SPDocument; diff --git a/src/ui/widget/notebook-page.cpp b/src/ui/widget/notebook-page.cpp index 92bcb6937..6653499b8 100644 --- a/src/ui/widget/notebook-page.cpp +++ b/src/ui/widget/notebook-page.cpp @@ -9,22 +9,35 @@ * Released under GNU GPL. Read the file 'COPYING' for more information */ -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - #include "notebook-page.h" +#if WITH_GTKMM_3_0 +# include <gtkmm/grid.h> +#else +# include <gtkmm/table.h> +#endif + namespace Inkscape { namespace UI { namespace Widget { NotebookPage::NotebookPage(int n_rows, int n_columns, bool expand, bool fill, guint padding) - :_table(n_rows, n_columns) +#if WITH_GTKMM_3_0 + :_table(Gtk::manage(new Gtk::Grid())) +#else + :_table(Gtk::manage(new Gtk::Table(n_rows, n_columns))) +#endif { set_border_width(2); - _table.set_spacings(2); - pack_start(_table, expand, fill, padding); + +#if WITH_GTKMM_3_0 + _table->set_row_spacing(2); + _table->set_column_spacing(2); +#else + _table->set_spacings(2); +#endif + + pack_start(*_table, expand, fill, padding); } } // namespace Widget diff --git a/src/ui/widget/notebook-page.h b/src/ui/widget/notebook-page.h index 140b7cb33..38ae9e054 100644 --- a/src/ui/widget/notebook-page.h +++ b/src/ui/widget/notebook-page.h @@ -10,8 +10,23 @@ #ifndef INKSCAPE_UI_WIDGET_NOTEBOOK_PAGE_H #define INKSCAPE_UI_WIDGET_NOTEBOOK_PAGE_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> -#include <gtkmm/table.h> + +namespace Gtk { +#if WITH_GTKMM_3_0 +class Grid; +#else +class Table; +#endif +} namespace Inkscape { namespace UI { @@ -31,10 +46,19 @@ public: */ NotebookPage(int n_rows, int n_columns, bool expand=false, bool fill=false, guint padding=0); - Gtk::Table& table() { return _table; } +#if WITH_GTKMM_3_0 + Gtk::Grid& table() { return *_table; } +#else + Gtk::Table& table() { return *_table; } +#endif protected: - Gtk::Table _table; + +#if WITH_GTKMM_3_0 + Gtk::Grid *_table; +#else + Gtk::Table *_table; +#endif }; } // namespace Widget diff --git a/src/ui/widget/object-composite-settings.cpp b/src/ui/widget/object-composite-settings.cpp index eb4790990..537db0fdd 100644 --- a/src/ui/widget/object-composite-settings.cpp +++ b/src/ui/widget/object-composite-settings.cpp @@ -16,6 +16,7 @@ #include <glibmm/i18n.h> +#include "desktop.h" #include "desktop-handles.h" #include "desktop-style.h" #include "document.h" @@ -32,13 +33,14 @@ #include "ui/icon-names.h" #include "display/sp-canvas.h" #include "ui/widget/style-subject.h" +#include "ui/widget/gimpspinscale.h" namespace Inkscape { namespace UI { namespace Widget { -void ObjectCompositeSettings::_on_desktop_activate( - Inkscape::Application */*application*/, +/*void ObjectCompositeSettings::_on_desktop_activate( + Inkscape::Application *application, SPDesktop *desktop, ObjectCompositeSettings *w ) { @@ -48,72 +50,54 @@ void ObjectCompositeSettings::_on_desktop_activate( } void ObjectCompositeSettings::_on_desktop_deactivate( - Inkscape::Application */*application*/, - SPDesktop */*desktop*/, + Inkscape::Application *application, + SPDesktop *desktop, ObjectCompositeSettings *w ) { if (w->_subject) { w->_subject->setDesktop(NULL); } -} +}*/ ObjectCompositeSettings::ObjectCompositeSettings(unsigned int verb_code, char const *history_prefix, int flags) : _verb_code(verb_code), _blur_tag(Glib::ustring(history_prefix) + ":blur"), _opacity_tag(Glib::ustring(history_prefix) + ":opacity"), _opacity_vbox(false, 0), - _opacity_label(_("Opacity:")), -#if WITH_GTKMM_3_0 - _opacity_adjustment(Gtk::Adjustment::create(100.0, 0.0, 100.0, 1.0, 1.0, 0.0)), -#else - _opacity_adjustment(100.0, 0.0, 100.0, 1.0, 1.0, 0.0), -#endif - _opacity_hscale(_opacity_adjustment), - _opacity_spin_button(_opacity_adjustment, 0.01, 1), + _opacity_scale(_("Opacity (%)"), 100.0, 0.0, 100.0, 1.0, 1.0, 1), _fe_cb(flags), _fe_vbox(false, 0), - _fe_alignment(1, 1, 1, 1), _blocked(false) { // Filter Effects pack_start(_fe_vbox, false, false, 2); - _fe_alignment.set_padding(0, 0, 4, 0); - _fe_alignment.add(_fe_cb); - _fe_vbox.pack_start(_fe_alignment, false, false, 0); + _fe_vbox.pack_start(_fe_cb, false, false, 0); _fe_cb.signal_blend_blur_changed().connect(sigc::mem_fun(*this, &ObjectCompositeSettings::_blendBlurValueChanged)); // Opacity pack_start(_opacity_vbox, false, false, 2); -#if WITH_GTKMM_2_22 - _opacity_label.set_alignment(Gtk::ALIGN_END, Gtk::ALIGN_CENTER); -#else - _opacity_label.set_alignment(Gtk::ALIGN_RIGHT, Gtk::ALIGN_CENTER); -#endif - - _opacity_hbox.pack_start(_opacity_label, false, false, 3); - //_opacity_vbox.pack_start(_opacity_label_box, false, false, 0); - _opacity_vbox.pack_start(_opacity_hbox, false, false, 0); - _opacity_hbox.pack_start(_opacity_hscale, true, true, 0); - _opacity_hbox.pack_start(_opacity_spin_button, false, false, 0); - _opacity_hscale.set_draw_value(false); -#if WITH_GTKMM_3_0 - _opacity_adjustment->signal_value_changed().connect(sigc::mem_fun(*this, &ObjectCompositeSettings::_opacityValueChanged)); - _opacity_label.set_mnemonic_widget(_opacity_hscale); -#else - _opacity_adjustment.signal_value_changed().connect(sigc::mem_fun(*this, &ObjectCompositeSettings::_opacityValueChanged)); - _opacity_label.set_mnemonic_widget(_opacity_hscale); -#endif + _opacity_vbox.pack_start(_opacity_scale); + + _opacity_scale.set_appearance("compact"); + + _opacity_scale.signal_value_changed().connect(sigc::mem_fun(*this, &ObjectCompositeSettings::_opacityValueChanged)); + + SPDesktop *desktop = SP_ACTIVE_DESKTOP; + _opacity_scale.set_focuswidget(GTK_WIDGET(desktop->canvas)); /* SizeGroup keeps the blur and opacity labels aligned in Fill & Stroke dlg */ +/* GtkSizeGroup *labels = gtk_size_group_new(GTK_SIZE_GROUP_HORIZONTAL); - gtk_size_group_add_widget(labels, (GtkWidget *) _opacity_label.gobj()); - gtk_size_group_add_widget(labels, (GtkWidget *) _fe_cb.get_blur_label()->gobj()); + gtk_size_group_add_widget(labels, GTK_WIDGET(_opacity_label.gobj())); + gtk_size_group_add_widget(labels, GTK_WIDGET(_fe_cb.get_blur_label()->gobj())); +*/ show_all_children(); - _desktop_activated = g_signal_connect ( G_OBJECT (INKSCAPE), "activate_desktop", G_CALLBACK (&ObjectCompositeSettings::_on_desktop_activate), this ); - _desktop_activated = g_signal_connect ( G_OBJECT (INKSCAPE), "deactivate_desktop", G_CALLBACK (&ObjectCompositeSettings::_on_desktop_deactivate), this ); + // These signals dont properly detect change in desktop, rely on owner dialog to call setSubject() from setTargetDesktop() + //_desktop_activated = g_signal_connect ( G_OBJECT (INKSCAPE), "activate_desktop", G_CALLBACK (&ObjectCompositeSettings::_on_desktop_activate), this ); + //_desktop_activated = g_signal_connect ( G_OBJECT (INKSCAPE), "deactivate_desktop", G_CALLBACK (&ObjectCompositeSettings::_on_desktop_deactivate), this ); } ObjectCompositeSettings::~ObjectCompositeSettings() { @@ -225,11 +209,7 @@ ObjectCompositeSettings::_opacityValueChanged() SPCSSAttr *css = sp_repr_css_attr_new (); Inkscape::CSSOStringStream os; -#if WITH_GTKMM_3_0 - os << CLAMP (_opacity_adjustment->get_value() / 100, 0.0, 1.0); -#else - os << CLAMP (_opacity_adjustment.get_value() / 100, 0.0, 1.0); -#endif + os << CLAMP (_opacity_scale.get_adjustment()->get_value() / 100, 0.0, 1.0); sp_repr_css_set_property (css, "opacity", os.str().c_str()); _subject->setCSS(css); @@ -265,18 +245,14 @@ ObjectCompositeSettings::_subjectChanged() { switch (result) { case QUERY_STYLE_NOTHING: - _opacity_hbox.set_sensitive(false); + _opacity_vbox.set_sensitive(false); // gtk_widget_set_sensitive (opa, FALSE); break; case QUERY_STYLE_SINGLE: case QUERY_STYLE_MULTIPLE_AVERAGED: // TODO: treat this slightly differently case QUERY_STYLE_MULTIPLE_SAME: - _opacity_hbox.set_sensitive(true); -#if WITH_GTKMM_3_0 - _opacity_adjustment->set_value(100 * SP_SCALE24_TO_FLOAT(query->opacity.value)); -#else - _opacity_adjustment.set_value(100 * SP_SCALE24_TO_FLOAT(query->opacity.value)); -#endif + _opacity_vbox.set_sensitive(true); + _opacity_scale.get_adjustment()->set_value(100 * SP_SCALE24_TO_FLOAT(query->opacity.value)); break; } diff --git a/src/ui/widget/object-composite-settings.h b/src/ui/widget/object-composite-settings.h index 9f9b336eb..19a6cb2a5 100644 --- a/src/ui/widget/object-composite-settings.h +++ b/src/ui/widget/object-composite-settings.h @@ -11,6 +11,14 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> #include <gtkmm/alignment.h> #include <gtkmm/adjustment.h> @@ -21,8 +29,10 @@ #include "ui/widget/filter-effect-chooser.h" #include "ui/widget/spinbutton.h" +class SPDesktop; + namespace Inkscape { -class Application; +struct Application; namespace UI { namespace Widget { @@ -45,21 +55,12 @@ private: Glib::ustring _opacity_tag; Gtk::VBox _opacity_vbox; - Gtk::HBox _opacity_hbox; - Gtk::Label _opacity_label; -#if WITH_GTKMM_3_0 - Glib::RefPtr<Gtk::Adjustment> _opacity_adjustment; -#else - Gtk::Adjustment _opacity_adjustment; -#endif - Gtk::HScale _opacity_hscale; - Inkscape::UI::Widget::SpinButton _opacity_spin_button; + Inkscape::UI::Widget::SpinScale _opacity_scale; StyleSubject *_subject; SimpleFilterModifier _fe_cb; Gtk::VBox _fe_vbox; - Gtk::Alignment _fe_alignment; bool _blocked; gulong _desktop_activated; diff --git a/src/ui/widget/page-sizer.cpp b/src/ui/widget/page-sizer.cpp index 83d923c15..eae0d4a95 100644 --- a/src/ui/widget/page-sizer.cpp +++ b/src/ui/widget/page-sizer.cpp @@ -27,13 +27,17 @@ #include <string> #include <string.h> #include <vector> + +#include <glibmm/i18n.h> + #include <2geom/transforms.h> #include "desktop-handles.h" #include "document.h" #include "desktop.h" #include "helper/action.h" -#include "helper/units.h" +#include "helper/action-context.h" +#include "util/units.h" #include "inkscape.h" #include "sp-namedview.h" #include "sp-root.h" @@ -44,6 +48,7 @@ #include "xml/repr.h" using std::pair; +using Inkscape::Util::unit_table; namespace Inkscape { namespace UI { @@ -92,7 +97,7 @@ struct PaperSizeRec { char const * const name; //name double const smaller; //lesser dimension double const larger; //greater dimension - SPUnitId const unit; //units + Glib::ustring const unit; //units }; // list of page formats that should be in landscape automatically @@ -110,31 +115,31 @@ fill_landscape_papers() { } static PaperSizeRec const inkscape_papers[] = { - { "A4", 210, 297, SP_UNIT_MM }, - { "US Letter", 8.5, 11, SP_UNIT_IN }, - { "US Legal", 8.5, 14, SP_UNIT_IN }, - { "US Executive", 7.25, 10.5, SP_UNIT_IN }, - { "A0", 841, 1189, SP_UNIT_MM }, - { "A1", 594, 841, SP_UNIT_MM }, - { "A2", 420, 594, SP_UNIT_MM }, - { "A3", 297, 420, SP_UNIT_MM }, - { "A5", 148, 210, SP_UNIT_MM }, - { "A6", 105, 148, SP_UNIT_MM }, - { "A7", 74, 105, SP_UNIT_MM }, - { "A8", 52, 74, SP_UNIT_MM }, - { "A9", 37, 52, SP_UNIT_MM }, - { "A10", 26, 37, SP_UNIT_MM }, - { "B0", 1000, 1414, SP_UNIT_MM }, - { "B1", 707, 1000, SP_UNIT_MM }, - { "B2", 500, 707, SP_UNIT_MM }, - { "B3", 353, 500, SP_UNIT_MM }, - { "B4", 250, 353, SP_UNIT_MM }, - { "B5", 176, 250, SP_UNIT_MM }, - { "B6", 125, 176, SP_UNIT_MM }, - { "B7", 88, 125, SP_UNIT_MM }, - { "B8", 62, 88, SP_UNIT_MM }, - { "B9", 44, 62, SP_UNIT_MM }, - { "B10", 31, 44, SP_UNIT_MM }, + { "A4", 210, 297, "mm" }, + { "US Letter", 8.5, 11, "in" }, + { "US Legal", 8.5, 14, "in" }, + { "US Executive", 7.25, 10.5, "in" }, + { "A0", 841, 1189, "mm" }, + { "A1", 594, 841, "mm" }, + { "A2", 420, 594, "mm" }, + { "A3", 297, 420, "mm" }, + { "A5", 148, 210, "mm" }, + { "A6", 105, 148, "mm" }, + { "A7", 74, 105, "mm" }, + { "A8", 52, 74, "mm" }, + { "A9", 37, 52, "mm" }, + { "A10", 26, 37, "mm" }, + { "B0", 1000, 1414, "mm" }, + { "B1", 707, 1000, "mm" }, + { "B2", 500, 707, "mm" }, + { "B3", 353, 500, "mm" }, + { "B4", 250, 353, "mm" }, + { "B5", 176, 250, "mm" }, + { "B6", 125, 176, "mm" }, + { "B7", 88, 125, "mm" }, + { "B8", 62, 88, "mm" }, + { "B9", 44, 62, "mm" }, + { "B10", 31, 44, "mm" }, @@ -146,63 +151,63 @@ static PaperSizeRec const inkscape_papers[] = { don't know what D and E series are used for. */ - { "C0", 917, 1297, SP_UNIT_MM }, - { "C1", 648, 917, SP_UNIT_MM }, - { "C2", 458, 648, SP_UNIT_MM }, - { "C3", 324, 458, SP_UNIT_MM }, - { "C4", 229, 324, SP_UNIT_MM }, - { "C5", 162, 229, SP_UNIT_MM }, - { "C6", 114, 162, SP_UNIT_MM }, - { "C7", 81, 114, SP_UNIT_MM }, - { "C8", 57, 81, SP_UNIT_MM }, - { "C9", 40, 57, SP_UNIT_MM }, - { "C10", 28, 40, SP_UNIT_MM }, - { "D1", 545, 771, SP_UNIT_MM }, - { "D2", 385, 545, SP_UNIT_MM }, - { "D3", 272, 385, SP_UNIT_MM }, - { "D4", 192, 272, SP_UNIT_MM }, - { "D5", 136, 192, SP_UNIT_MM }, - { "D6", 96, 136, SP_UNIT_MM }, - { "D7", 68, 96, SP_UNIT_MM }, - { "E3", 400, 560, SP_UNIT_MM }, - { "E4", 280, 400, SP_UNIT_MM }, - { "E5", 200, 280, SP_UNIT_MM }, - { "E6", 140, 200, SP_UNIT_MM }, + { "C0", 917, 1297, "mm" }, + { "C1", 648, 917, "mm" }, + { "C2", 458, 648, "mm" }, + { "C3", 324, 458, "mm" }, + { "C4", 229, 324, "mm" }, + { "C5", 162, 229, "mm" }, + { "C6", 114, 162, "mm" }, + { "C7", 81, 114, "mm" }, + { "C8", 57, 81, "mm" }, + { "C9", 40, 57, "mm" }, + { "C10", 28, 40, "mm" }, + { "D1", 545, 771, "mm" }, + { "D2", 385, 545, "mm" }, + { "D3", 272, 385, "mm" }, + { "D4", 192, 272, "mm" }, + { "D5", 136, 192, "mm" }, + { "D6", 96, 136, "mm" }, + { "D7", 68, 96, "mm" }, + { "E3", 400, 560, "mm" }, + { "E4", 280, 400, "mm" }, + { "E5", 200, 280, "mm" }, + { "E6", 140, 200, "mm" }, //#endif - { "CSE", 462, 649, SP_UNIT_PT }, - { "US #10 Envelope", 4.125, 9.5, SP_UNIT_IN }, + { "CSE", 462, 649, "pt" }, + { "US #10 Envelope", 4.125, 9.5, "in" }, /* See http://www.hbp.com/content/PCR_envelopes.cfm for a much larger list of US envelope sizes. */ - { "DL Envelope", 110, 220, SP_UNIT_MM }, - { "Ledger/Tabloid", 11, 17, SP_UNIT_IN }, + { "DL Envelope", 110, 220, "mm" }, + { "Ledger/Tabloid", 11, 17, "in" }, /* Note that `Folio' (used in QPrinter/KPrinter) is deliberately absent from this list, as it means different sizes to different people: different people may expect the width to be either 8, 8.25 or 8.5 inches, and the height to be either 13 or 13.5 inches, even restricting our interpretation to foolscap folio. If you wish to introduce a folio-like page size to the list, then please consider using a name more specific than just `Folio' or `Foolscap Folio'. */ - { "Banner 468x60", 60, 468, SP_UNIT_PX }, - { "Icon 16x16", 16, 16, SP_UNIT_PX }, - { "Icon 32x32", 32, 32, SP_UNIT_PX }, - { "Icon 48x48", 48, 48, SP_UNIT_PX }, + { "Banner 468x60", 60, 468, "px" }, + { "Icon 16x16", 16, 16, "px" }, + { "Icon 32x32", 32, 32, "px" }, + { "Icon 48x48", 48, 48, "px" }, /* business cards */ - { "Business Card (ISO 7810)", 53.98, 85.60, SP_UNIT_MM }, - { "Business Card (US)", 2, 3.5, SP_UNIT_IN }, - { "Business Card (Europe)", 55, 85, SP_UNIT_MM }, - { "Business Card (Aus/NZ)", 55, 90, SP_UNIT_MM }, + { "Business Card (ISO 7810)", 53.98, 85.60, "mm" }, + { "Business Card (US)", 2, 3.5, "in" }, + { "Business Card (Europe)", 55, 85, "mm" }, + { "Business Card (Aus/NZ)", 55, 90, "mm" }, // Start Arch Series List - { "Arch A", 9, 12, SP_UNIT_IN }, // 229 x 305 mm - { "Arch B", 12, 18, SP_UNIT_IN }, // 305 x 457 mm - { "Arch C", 18, 24, SP_UNIT_IN }, // 457 x 610 mm - { "Arch D", 24, 36, SP_UNIT_IN }, // 610 x 914 mm - { "Arch E", 36, 48, SP_UNIT_IN }, // 914 x 1219 mm - { "Arch E1", 30, 42, SP_UNIT_IN }, // 762 x 1067 mm + { "Arch A", 9, 12, "in" }, // 229 x 305 mm + { "Arch B", 12, 18, "in" }, // 305 x 457 mm + { "Arch C", 18, 24, "in" }, // 457 x 610 mm + { "Arch D", 24, 36, "in" }, // 610 x 914 mm + { "Arch E", 36, 48, "in" }, // 914 x 1219 mm + { "Arch E1", 30, 42, "in" }, // 762 x 1067 mm /* * The above list of Arch sizes were taken from the following site: @@ -213,7 +218,7 @@ static PaperSizeRec const inkscape_papers[] = { * September 2009 - DAK */ - { NULL, 0, 0, SP_UNIT_PX }, + { NULL, 0, 0, "px" }, }; @@ -222,10 +227,6 @@ static PaperSizeRec const inkscape_papers[] = { //# P A G E S I Z E R //######################################################################## -//The default unit for this widget and its calculations -static const SPUnit _px_unit = sp_unit_get_by_id (SP_UNIT_PX); - - /** * Constructor */ @@ -242,12 +243,14 @@ PageSizer::PageSizer(Registry & _wr) _widgetRegistry(&_wr) { // set precision of scalar entry boxes + _wr.setUpdating (true); _dimensionWidth.setDigits(5); _dimensionHeight.setDigits(5); _marginTop.setDigits(5); _marginLeft.setDigits(5); _marginRight.setDigits(5); _marginBottom.setDigits(5); + _wr.setUpdating (false); //# Set up the Paper Size combo box _paperSizeListStore = Gtk::ListStore::create(_paperSizeListColumns); @@ -274,13 +277,8 @@ PageSizer::PageSizer(Registry & _wr) char formatBuf[80]; snprintf(formatBuf, 79, "%0.1f x %0.1f", p->smaller, p->larger); Glib::ustring desc = formatBuf; - if (p->unit == SP_UNIT_IN) - desc.append(" in"); - else if (p->unit == SP_UNIT_MM) - desc.append(" mm"); - else if (p->unit == SP_UNIT_PX) - desc.append(" px"); - PaperSize paper(name, p->smaller, p->larger, p->unit); + desc.append(" " + p->unit); + PaperSize paper(name, p->smaller, p->larger, unit_table.getUnit(p->unit)); _paperSizeTable[name] = paper; Gtk::TreeModel::Row row = *(_paperSizeListStore->append()); row[_paperSizeListColumns.nameColumn] = name; @@ -312,25 +310,49 @@ PageSizer::PageSizer(Registry & _wr) // Setting default custom unit to document unit SPDesktop *dt = SP_ACTIVE_DESKTOP; SPNamedView *nv = sp_desktop_namedview(dt); + _wr.setUpdating (true); if (nv->units) { - _dimensionUnits.setUnit(nv->units); + _dimensionUnits.setUnit(nv->units->abbr); } else if (nv->doc_units) { - _dimensionUnits.setUnit(nv->doc_units); + _dimensionUnits.setUnit(nv->doc_units->abbr); } + _wr.setUpdating (false); //## Set up custom size frame _customFrame.set_label(_("Custom size")); pack_start (_customFrame, false, false, 0); _customFrame.add(_customDimTable); - _customDimTable.resize(3, 2); _customDimTable.set_border_width(4); + +#if WITH_GTKMM_3_0 + _customDimTable.set_row_spacing(4); + _customDimTable.set_column_spacing(4); + + _dimensionWidth.set_hexpand(); + _dimensionWidth.set_vexpand(); + _customDimTable.attach(_dimensionWidth, 0, 0, 1, 1); + + _dimensionUnits.set_hexpand(); + _dimensionUnits.set_vexpand(); + _customDimTable.attach(_dimensionUnits, 1, 0, 1, 1); + + _dimensionHeight.set_hexpand(); + _dimensionHeight.set_vexpand(); + _customDimTable.attach(_dimensionHeight, 0, 1, 1, 1); + + _fitPageMarginExpander.set_hexpand(); + _fitPageMarginExpander.set_vexpand(); + _customDimTable.attach(_fitPageMarginExpander, 0, 2, 2, 1); +#else + _customDimTable.resize(3, 2); _customDimTable.set_row_spacings(4); _customDimTable.set_col_spacings(4); _customDimTable.attach(_dimensionWidth, 0,1, 0,1); _customDimTable.attach(_dimensionUnits, 1,2, 0,1); _customDimTable.attach(_dimensionHeight, 0,1, 1,2); _customDimTable.attach(_fitPageMarginExpander, 0,2, 2,3); +#endif _dimTabOrderGList = NULL; _dimTabOrderGList = g_list_append(_dimTabOrderGList, _dimensionWidth.gobj()); @@ -346,7 +368,32 @@ PageSizer::PageSizer(Registry & _wr) _fitPageMarginExpander.add(_marginTable); //## Set up margin settings - _marginTable.resize(4, 2); + _marginTable.set_border_width(4); + +#if WITH_GTKMM_3_0 + _marginTable.set_row_spacing(4); + _marginTable.set_column_spacing(4); + + _marginTopAlign.set_hexpand(); + _marginTopAlign.set_vexpand(); + _marginTable.attach(_marginTopAlign, 0, 0, 2, 1); + + _marginLeftAlign.set_hexpand(); + _marginLeftAlign.set_vexpand(); + _marginTable.attach(_marginLeftAlign, 0, 1, 1, 1); + + _marginRightAlign.set_hexpand(); + _marginRightAlign.set_vexpand(); + _marginTable.attach(_marginRightAlign, 1, 1, 1, 1); + + _marginBottomAlign.set_hexpand(); + _marginBottomAlign.set_vexpand(); + _marginTable.attach(_marginBottomAlign, 0, 2, 2, 1); + + _fitPageButtonAlign.set_hexpand(); + _fitPageButtonAlign.set_vexpand(); + _marginTable.attach(_fitPageButtonAlign, 0, 3, 2, 1); +#else _marginTable.set_border_width(4); _marginTable.set_row_spacings(4); _marginTable.set_col_spacings(4); @@ -355,6 +402,7 @@ PageSizer::PageSizer(Registry & _wr) _marginTable.attach(_marginRightAlign, 1,2, 1,2); _marginTable.attach(_marginBottomAlign, 0,2, 2,3); _marginTable.attach(_fitPageButtonAlign, 0,2, 3,4); +#endif _marginTopAlign.set(0.5, 0.5, 0.0, 1.0); _marginTopAlign.add(_marginTop); @@ -394,6 +442,7 @@ PageSizer::init () _portrait_connection = _portraitButton.signal_toggled().connect (sigc::mem_fun (*this, &PageSizer::on_portrait)); _changedw_connection = _dimensionWidth.signal_value_changed().connect (sigc::mem_fun (*this, &PageSizer::on_value_changed)); _changedh_connection = _dimensionHeight.signal_value_changed().connect (sigc::mem_fun (*this, &PageSizer::on_value_changed)); + _changedu_connection = _dimensionUnits.getUnitMenu()->signal_changed().connect (sigc::mem_fun (*this, &PageSizer::on_units_changed)); _fitPageButton.signal_clicked().connect(sigc::mem_fun(*this, &PageSizer::fire_fit_canvas_to_selection_or_drawing)); show_all_children(); @@ -406,11 +455,11 @@ PageSizer::init () * 'changeList' is true, then adjust the paperSizeList to show the closest * standard page size. * - * \param w, h given in px + * \param w, h * \param changeList whether to modify the paper size list */ void -PageSizer::setDim (double w, double h, bool changeList) +PageSizer::setDim (Inkscape::Util::Quantity w, Inkscape::Util::Quantity h, bool changeList) { static bool _called = false; if (_called) { @@ -425,14 +474,16 @@ PageSizer::setDim (double w, double h, bool changeList) _changedw_connection.block(); _changedh_connection.block(); + _unit = w.unit->abbr; + if (SP_ACTIVE_DESKTOP && !_widgetRegistry->isUpdating()) { SPDocument *doc = sp_desktop_document(SP_ACTIVE_DESKTOP); - double const old_height = doc->getHeight(); - doc->setWidth (w, &_px_unit); - doc->setHeight (h, &_px_unit); + Inkscape::Util::Quantity const old_height = doc->getHeight(); + doc->setWidth (w); + doc->setHeight (h); // The origin for the user is in the lower left corner; this point should remain stationary when // changing the page size. The SVG's origin however is in the upper left corner, so we must compensate for this - Geom::Translate const vert_offset(Geom::Point(0, (old_height - h))); + Geom::Translate const vert_offset(Geom::Point(0, (old_height.value("px") - h.value("px")))); doc->getRoot()->translateChildItems(vert_offset); DocumentUndo::done(doc, SP_VERB_NONE, _("Set page size")); } @@ -455,9 +506,10 @@ PageSizer::setDim (double w, double h, bool changeList) _paperSizeListSelection->select(row); } - Unit const& unit = _dimensionUnits.getUnit(); - _dimensionWidth.setValue (w / unit.factor); - _dimensionHeight.setValue (h / unit.factor); + _dimensionWidth.setUnit(w.unit->abbr); + _dimensionWidth.setValue (w.quantity); + _dimensionHeight.setUnit(h.unit->abbr); + _dimensionHeight.setValue (h.quantity); _paper_size_list_connection.unblock(); _landscape_connection.unblock(); @@ -495,37 +547,40 @@ PageSizer::updateFitMarginsUI(Inkscape::XML::Node *nv_repr) /** * Returns an iterator pointing to a row in paperSizeListStore which - * contains a paper of the specified size (specified in px), or + * contains a paper of the specified size, or * paperSizeListStore->children().end() if no such paper exists. + * + * The code is not tested for the case where w and h have different units. */ Gtk::ListStore::iterator -PageSizer::find_paper_size (double w, double h) const +PageSizer::find_paper_size (Inkscape::Util::Quantity w, Inkscape::Util::Quantity h) const { - double smaller = w; - double larger = h; + using Inkscape::Util::Quantity; + using std::swap; + + // The code below assumes that w < h, so make sure that's the case: if ( h < w ) { - smaller = h; larger = w; + swap(h,w); } - g_return_val_if_fail(smaller <= larger, _paperSizeListStore->children().end()); + g_return_val_if_fail(w <= h, _paperSizeListStore->children().end()); std::map<Glib::ustring, PaperSize>::const_iterator iter; for (iter = _paperSizeTable.begin() ; iter != _paperSizeTable.end() ; ++iter) { PaperSize paper = iter->second; - SPUnit const &i_unit = sp_unit_get_by_id(paper.unit); - double smallX = sp_units_get_pixels(paper.smaller, i_unit); - double largeX = sp_units_get_pixels(paper.larger, i_unit); + Quantity smallX (paper.smaller, paper.unit); + Quantity largeX (paper.larger, paper.unit); - g_return_val_if_fail(smallX <= largeX, _paperSizeListStore->children().end()); + g_return_val_if_fail(smallX.quantity < largeX.quantity + 0.001, _paperSizeListStore->children().end()); - if ((std::abs(smaller - smallX) <= 0.1) && - (std::abs(larger - largeX) <= 0.1) ) { - Gtk::ListStore::iterator p; + if ( are_near(w, smallX, 0.1) && are_near(h, largeX, 0.1) ) { + Gtk::ListStore::iterator p = _paperSizeListStore->children().begin(); + Gtk::ListStore::iterator pend = _paperSizeListStore->children().end(); // We need to search paperSizeListStore explicitly for the // specified paper size because it is sorted in a different // way than paperSizeTable (which is sorted alphabetically) - for (p = _paperSizeListStore->children().begin(); p != _paperSizeListStore->children().end(); ++p) { + for ( ; p != pend; ++p) { if ((*p)[_paperSizeListColumns.nameColumn] == paper.name) { return p; } @@ -550,7 +605,7 @@ PageSizer::fire_fit_canvas_to_selection_or_drawing() SPDocument *doc; SPNamedView *nv; Inkscape::XML::Node *nv_repr; - + if ((doc = sp_desktop_document(SP_ACTIVE_DESKTOP)) && (nv = sp_document_namedview(doc, 0)) && (nv_repr = nv->getRepr())) { @@ -564,7 +619,7 @@ PageSizer::fire_fit_canvas_to_selection_or_drawing() Verb *verb = Verb::get( SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING ); if (verb) { - SPAction *action = verb->get_action(dt); + SPAction *action = verb->get_action(Inkscape::ActionContext(dt)); if (action) { sp_action_perform(action, NULL); } @@ -595,8 +650,8 @@ PageSizer::on_paper_size_list_changed() return; } PaperSize paper = piter->second; - double w = paper.smaller; - double h = paper.larger; + Inkscape::Util::Quantity w = Inkscape::Util::Quantity(paper.smaller, paper.unit); + Inkscape::Util::Quantity h = Inkscape::Util::Quantity(paper.larger, paper.unit); if (std::find(lscape_papers.begin(), lscape_papers.end(), paper.name.c_str()) != lscape_papers.end()) { // enforce landscape mode if this is desired for the given page format @@ -606,10 +661,6 @@ PageSizer::on_paper_size_list_changed() _landscape = _landscapeButton.get_active(); } - SPUnit const &src_unit = sp_unit_get_by_id (paper.unit); - sp_convert_distance (&w, &src_unit, &_px_unit); - sp_convert_distance (&h, &src_unit, &_px_unit); - if (_landscape) setDim (h, w, false); else @@ -626,8 +677,8 @@ PageSizer::on_portrait() { if (!_portraitButton.get_active()) return; - double w = _dimensionWidth.getValue ("px"); - double h = _dimensionHeight.getValue ("px"); + Inkscape::Util::Quantity w = Inkscape::Util::Quantity(_dimensionWidth.getValue(""), _dimensionWidth.getUnit()); + Inkscape::Util::Quantity h = Inkscape::Util::Quantity(_dimensionHeight.getValue(""), _dimensionHeight.getUnit()); if (h < w) { setDim (h, w); } @@ -642,8 +693,8 @@ PageSizer::on_landscape() { if (!_landscapeButton.get_active()) return; - double w = _dimensionWidth.getValue ("px"); - double h = _dimensionHeight.getValue ("px"); + Inkscape::Util::Quantity w = Inkscape::Util::Quantity(_dimensionWidth.getValue(""), _dimensionWidth.getUnit()); + Inkscape::Util::Quantity h = Inkscape::Util::Quantity(_dimensionHeight.getValue(""), _dimensionHeight.getUnit()); if (w < h) { setDim (h, w); } @@ -656,11 +707,18 @@ void PageSizer::on_value_changed() { if (_widgetRegistry->isUpdating()) return; - - setDim (_dimensionWidth.getValue("px"), - _dimensionHeight.getValue("px")); + if (_unit != _dimensionUnits.getUnit()->abbr) return; + setDim (Inkscape::Util::Quantity(_dimensionWidth.getValue(""), _dimensionUnits.getUnit()), + Inkscape::Util::Quantity(_dimensionHeight.getValue(""), _dimensionUnits.getUnit())); +} +void +PageSizer::on_units_changed() +{ + if (_widgetRegistry->isUpdating()) return; + _unit = _dimensionUnits.getUnit()->abbr; + setDim (Inkscape::Util::Quantity(_dimensionWidth.getValue(""), _dimensionUnits.getUnit()), + Inkscape::Util::Quantity(_dimensionHeight.getValue(""), _dimensionUnits.getUnit())); } - } // namespace Widget } // namespace UI diff --git a/src/ui/widget/page-sizer.h b/src/ui/widget/page-sizer.h index 17fd7b1ea..dc8e34d82 100644 --- a/src/ui/widget/page-sizer.h +++ b/src/ui/widget/page-sizer.h @@ -10,18 +10,28 @@ #ifndef INKSCAPE_UI_WIDGET_PAGE_SIZER_H #define INKSCAPE_UI_WIDGET_PAGE_SIZER_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + #include <stddef.h> #include "ui/widget/registered-widget.h" #include <sigc++/sigc++.h> -#include "helper/units.h" +#include "util/units.h" #include <gtkmm/alignment.h> #include <gtkmm/expander.h> #include <gtkmm/frame.h> #include <gtkmm/liststore.h> #include <gtkmm/scrolledwindow.h> -#include <gtkmm/table.h> + +#if WITH_GTKMM_3_0 +# include <gtkmm/grid.h> +#else +# include <gtkmm/table.h> +#endif + #include <gtkmm/radiobutton.h> namespace Inkscape { @@ -54,7 +64,7 @@ public: PaperSize(const Glib::ustring &nameArg, double smallerArg, double largerArg, - SPUnitId unitArg) + Inkscape::Util::Unit const *unitArg) { name = nameArg; smaller = smallerArg; @@ -98,7 +108,7 @@ public: /** * The units (px, pt, mm, etc) of this specification */ - SPUnitId unit; + Inkscape::Util::Unit const *unit; /// pointer to object in UnitTable, do not delete private: @@ -107,7 +117,7 @@ private: name = ""; smaller = 0.0; larger = 0.0; - unit = SP_UNIT_PX; + unit = unit_table.getUnit("px"); } void assign(const PaperSize &other) @@ -151,7 +161,7 @@ public: * Set the page size to the given dimensions. If 'changeList' is * true, then reset the paper size list to the closest match */ - void setDim (double w, double h, bool changeList=true); + void setDim (Inkscape::Util::Quantity w, Inkscape::Util::Quantity h, bool changeList=true); /** * Updates the scalar widgets for the fit margins. (Just changes the value @@ -169,7 +179,7 @@ protected: /** * Find the closest standard paper size in the table, to the */ - Gtk::ListStore::iterator find_paper_size (double w, double h) const; + Gtk::ListStore::iterator find_paper_size (Inkscape::Util::Quantity w, Inkscape::Util::Quantity h) const; void fire_fit_canvas_to_selection_or_drawing(); @@ -207,7 +217,13 @@ protected: //### Custom size frame Gtk::Frame _customFrame; + +#if WITH_GTKMM_3_0 + Gtk::Grid _customDimTable; +#else Gtk::Table _customDimTable; +#endif + RegisteredUnitMenu _dimensionUnits; RegisteredScalarUnit _dimensionWidth; RegisteredScalarUnit _dimensionHeight; @@ -215,7 +231,13 @@ protected: //### Fit Page options Gtk::Expander _fitPageMarginExpander; + +#if WITH_GTKMM_3_0 + Gtk::Grid _marginTable; +#else Gtk::Table _marginTable; +#endif + Gtk::Alignment _marginTopAlign; Gtk::Alignment _marginLeftAlign; Gtk::Alignment _marginRightAlign; @@ -230,13 +252,17 @@ protected: //callback void on_value_changed(); + void on_units_changed(); sigc::connection _changedw_connection; sigc::connection _changedh_connection; + sigc::connection _changedu_connection; Registry *_widgetRegistry; //### state - whether we are currently landscape or portrait bool _landscape; + + Glib::ustring _unit; }; diff --git a/src/ui/widget/panel.cpp b/src/ui/widget/panel.cpp index a1ae6a36d..d60eeefe0 100644 --- a/src/ui/widget/panel.cpp +++ b/src/ui/widget/panel.cpp @@ -15,7 +15,9 @@ # include <config.h> #endif -#include <glibmm/i18n.h> +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif #include <gtkmm/dialog.h> // for Gtk::RESPONSE_* #include <gtkmm/menu.h> @@ -24,6 +26,8 @@ #include <gtkmm/radiomenuitem.h> #include <gtkmm/separatormenuitem.h> +#include <glibmm/i18n.h> + #include <gtk/gtk.h> #include "panel.h" @@ -42,7 +46,8 @@ static const int PANEL_SETTING_SIZE = 0; static const int PANEL_SETTING_MODE = 1; static const int PANEL_SETTING_SHAPE = 2; static const int PANEL_SETTING_WRAP = 3; -static const int PANEL_SETTING_NEXTFREE = 4; +static const int PANEL_SETTING_BORDER = 4; +static const int PANEL_SETTING_NEXTFREE = 5; void Panel::prep() { @@ -93,7 +98,7 @@ void Panel::_init() Glib::ustring tmp("<"); _anchor = SP_ANCHOR_CENTER; - guint panel_size = 0, panel_mode = 0, panel_ratio = 100; + guint panel_size = 0, panel_mode = 0, panel_ratio = 100, panel_border = 0; bool panel_wrap = 0; if (!_prefs_path.empty()) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -101,6 +106,7 @@ void Panel::_init() panel_size = prefs->getIntLimited(_prefs_path + "/panel_size", 1, 0, PREVIEW_SIZE_HUGE); panel_mode = prefs->getIntLimited(_prefs_path + "/panel_mode", 1, 0, 10); panel_ratio = prefs->getIntLimited(_prefs_path + "/panel_ratio", 100, 0, 500 ); + panel_border = prefs->getIntLimited(_prefs_path + "/panel_border", BORDER_NONE, 0, 2 ); } _menu = new Gtk::Menu(); @@ -198,6 +204,42 @@ void Panel::_init() } { + Glib::ustring widthItemLabel(C_("Swatches", "Border")); + + //TRANSLATORS: Indicates border of colour swatches + const gchar *widthLabels[] = { + NC_("Swatches border", "None"), + NC_("Swatches border", "Solid"), + NC_("Swatches border", "Wide"), + }; + + Gtk::MenuItem *item = manage( new Gtk::MenuItem(widthItemLabel)); + Gtk::Menu *type_menu = manage(new Gtk::Menu()); + item->set_submenu(*type_menu); + _menu->append(*item); + + Gtk::RadioMenuItem::Group widthGroup; + + guint values[] = {0, 1, 2}; + guint hot_index = 0; + for ( guint i = 0; i < G_N_ELEMENTS(widthLabels); ++i ) { + // Assume all values are in increasing order + if ( values[i] <= panel_border ) { + hot_index = i; + } + } + for ( guint i = 0; i < G_N_ELEMENTS(widthLabels); ++i ) { + Glib::ustring _label(g_dpgettext2(NULL, "Swatches border", widthLabels[i])); + Gtk::RadioMenuItem *_item = manage(new Gtk::RadioMenuItem(widthGroup, _label)); + type_menu->append(*_item); + if ( i <= hot_index ) { + _item->set_active(true); + } + _item->signal_activate().connect(sigc::bind<int, int>(sigc::mem_fun(*this, &Panel::_bounceCall), PANEL_SETTING_BORDER, values[i])); + } + } + + { //TRANSLATORS: "Wrap" indicates how colour swatches are displayed Glib::ustring wrap_label(C_("Swatches","Wrap")); Gtk::CheckMenuItem *check = manage(new Gtk::CheckMenuItem(wrap_label)); @@ -259,6 +301,7 @@ void Panel::_init() _bounceCall(PANEL_SETTING_MODE, panel_mode); _bounceCall(PANEL_SETTING_SHAPE, panel_ratio); _bounceCall(PANEL_SETTING_WRAP, panel_wrap); + _bounceCall(PANEL_SETTING_BORDER, panel_border); } void Panel::setLabel(Glib::ustring const &label) @@ -323,7 +366,7 @@ void Panel::present() void Panel::restorePanelPrefs() { - guint panel_size = 0, panel_mode = 0, panel_ratio = 100; + guint panel_size = 0, panel_mode = 0, panel_ratio = 100, panel_border = 0; bool panel_wrap = 0; if (!_prefs_path.empty()) { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); @@ -331,11 +374,13 @@ void Panel::restorePanelPrefs() panel_size = prefs->getIntLimited(_prefs_path + "/panel_size", 1, 0, PREVIEW_SIZE_HUGE); panel_mode = prefs->getIntLimited(_prefs_path + "/panel_mode", 1, 0, 10); panel_ratio = prefs->getIntLimited(_prefs_path + "/panel_ratio", 000, 0, 500 ); + panel_border = prefs->getIntLimited(_prefs_path + "/panel_border", BORDER_NONE, 0, 2 ); } _bounceCall(PANEL_SETTING_SIZE, panel_size); _bounceCall(PANEL_SETTING_MODE, panel_mode); _bounceCall(PANEL_SETTING_SHAPE, panel_ratio); _bounceCall(PANEL_SETTING_WRAP, panel_wrap); + _bounceCall(PANEL_SETTING_BORDER, panel_border); } sigc::signal<void, int> &Panel::signalResponse() @@ -360,30 +405,32 @@ void Panel::_bounceCall(int i, int j) if (_fillable) { ViewType curr_type = _fillable->getPreviewType(); guint curr_ratio = _fillable->getPreviewRatio(); + ::BorderStyle curr_border = _fillable->getPreviewBorder(); + switch (j) { case 0: { - _fillable->setStyle(::PREVIEW_SIZE_TINY, curr_type, curr_ratio); + _fillable->setStyle(::PREVIEW_SIZE_TINY, curr_type, curr_ratio, curr_border); } break; case 1: { - _fillable->setStyle(::PREVIEW_SIZE_SMALL, curr_type, curr_ratio); + _fillable->setStyle(::PREVIEW_SIZE_SMALL, curr_type, curr_ratio, curr_border); } break; case 2: { - _fillable->setStyle(::PREVIEW_SIZE_MEDIUM, curr_type, curr_ratio); + _fillable->setStyle(::PREVIEW_SIZE_MEDIUM, curr_type, curr_ratio, curr_border); } break; case 3: { - _fillable->setStyle(::PREVIEW_SIZE_BIG, curr_type, curr_ratio); + _fillable->setStyle(::PREVIEW_SIZE_BIG, curr_type, curr_ratio, curr_border); } break; case 4: { - _fillable->setStyle(::PREVIEW_SIZE_HUGE, curr_type, curr_ratio); + _fillable->setStyle(::PREVIEW_SIZE_HUGE, curr_type, curr_ratio, curr_border); } break; default: @@ -399,15 +446,16 @@ void Panel::_bounceCall(int i, int j) if (_fillable) { ::PreviewSize curr_size = _fillable->getPreviewSize(); guint curr_ratio = _fillable->getPreviewRatio(); + ::BorderStyle curr_border = _fillable->getPreviewBorder(); switch (j) { case 0: { - _fillable->setStyle(curr_size, VIEW_TYPE_LIST, curr_ratio); + _fillable->setStyle(curr_size, VIEW_TYPE_LIST, curr_ratio, curr_border); } break; case 1: { - _fillable->setStyle(curr_size, VIEW_TYPE_GRID, curr_ratio); + _fillable->setStyle(curr_size, VIEW_TYPE_GRID, curr_ratio, curr_border); } break; default: @@ -423,7 +471,40 @@ void Panel::_bounceCall(int i, int j) if ( _fillable ) { ViewType curr_type = _fillable->getPreviewType(); ::PreviewSize curr_size = _fillable->getPreviewSize(); - _fillable->setStyle(curr_size, curr_type, j); + ::BorderStyle curr_border = _fillable->getPreviewBorder(); + + _fillable->setStyle(curr_size, curr_type, j, curr_border); + } + break; + case PANEL_SETTING_BORDER: + if (!_prefs_path.empty()) { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + prefs->setInt(_prefs_path + "/panel_border", j); + } + if ( _fillable ) { + ::PreviewSize curr_size = _fillable->getPreviewSize(); + ViewType curr_type = _fillable->getPreviewType(); + guint curr_ratio = _fillable->getPreviewRatio(); + + switch (j) { + case 0: + { + _fillable->setStyle(curr_size, curr_type, curr_ratio, BORDER_NONE); + } + break; + case 1: + { + _fillable->setStyle(curr_size, curr_type, curr_ratio, BORDER_SOLID); + } + break; + case 2: + { + _fillable->setStyle(curr_size, curr_type, curr_ratio, BORDER_WIDE); + } + break; + default: + break; + } } break; case PANEL_SETTING_WRAP: @@ -483,6 +564,7 @@ void Panel::_regItem(Gtk::MenuItem* item, int group, int id) _menu->append(*item); item->signal_activate().connect(sigc::bind<int, int>(sigc::mem_fun(*this, &Panel::_bounceCall), group + PANEL_SETTING_NEXTFREE, id)); item->show(); + } void Panel::_handleAction(int /*set_id*/, int /*item_id*/) @@ -495,31 +577,41 @@ void Panel::_apply() g_warning("Apply button clicked for panel [Panel::_apply()]"); } -Gtk::Button *Panel::addResponseButton(const Glib::ustring &button_text, int response_id) +Gtk::Button *Panel::addResponseButton(const Glib::ustring &button_text, int response_id, bool pack_start) { Gtk::Button *button = new Gtk::Button(button_text); - _addResponseButton(button, response_id); + _addResponseButton(button, response_id, pack_start); return button; } -Gtk::Button *Panel::addResponseButton(const Gtk::StockID &stock_id, int response_id) +Gtk::Button *Panel::addResponseButton(const Gtk::StockID &stock_id, int response_id, bool pack_start) { Gtk::Button *button = new Gtk::Button(stock_id); - _addResponseButton(button, response_id); + _addResponseButton(button, response_id, pack_start); return button; } -void Panel::_addResponseButton(Gtk::Button *button, int response_id) +void Panel::_addResponseButton(Gtk::Button *button, int response_id, bool pack_start) { // Create a button box for the response buttons if it's the first button to be added if (!_action_area) { +#if WITH_GTKMM_3_0 + _action_area = new Gtk::ButtonBox(); + _action_area->set_layout(Gtk::BUTTONBOX_END); + _action_area->set_spacing(6); +#else _action_area = new Gtk::HButtonBox(Gtk::BUTTONBOX_END, 6); +#endif _action_area->set_border_width(4); pack_end(*_action_area, Gtk::PACK_SHRINK, 0); } _action_area->pack_end(*button); + if (pack_start) { + _action_area->set_child_secondary( *button , true); + } + if (response_id != 0) { // Re-emit clicked signals as response signals button->signal_clicked().connect(sigc::bind(_signal_response.make_slot(), response_id)); diff --git a/src/ui/widget/panel.h b/src/ui/widget/panel.h index 2d92d65c9..0c3d822b8 100644 --- a/src/ui/widget/panel.h +++ b/src/ui/widget/panel.h @@ -13,6 +13,14 @@ #ifndef SEEN_INKSCAPE_UI_WIDGET_PANEL_H #define SEEN_INKSCAPE_UI_WIDGET_PANEL_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> #include <gtkmm/arrow.h> #include <gtkmm/button.h> @@ -27,7 +35,13 @@ class SPDocument; namespace Gtk { class CheckMenuItem; + +#if WITH_GTKMM_3_0 + class ButtonBox; +#else class HButtonBox; +#endif + class MenuItem; } @@ -96,8 +110,8 @@ public: /* Methods providing a Gtk::Dialog like interface for adding buttons that emit Gtk::RESPONSE * signals on click. */ - Gtk::Button* addResponseButton (const Glib::ustring &button_text, int response_id); - Gtk::Button* addResponseButton (const Gtk::StockID &stock_id, int response_id); + Gtk::Button* addResponseButton (const Glib::ustring &button_text, int response_id, bool pack_start=false); + Gtk::Button* addResponseButton (const Gtk::StockID &stock_id, int response_id, bool pack_start=false); void setDefaultResponse(int response_id); void setResponseSensitive(int response_id, bool setting); @@ -119,7 +133,7 @@ protected: virtual void _handleResponse(int response_id); /* Helper methods */ - void _addResponseButton(Gtk::Button *button, int response_id); + void _addResponseButton(Gtk::Button *button, int response_id, bool pack_start=false); Inkscape::Selection *_getSelection(); /** @@ -157,7 +171,13 @@ private: Gtk::EventBox _menu_popper; Gtk::Button _close_button; Gtk::Menu *_menu; + +#if WITH_GTKMM_3_0 + Gtk::ButtonBox *_action_area; //< stores response buttons +#else Gtk::HButtonBox *_action_area; //< stores response buttons +#endif + std::vector<Gtk::Widget *> _non_horizontal; std::vector<Gtk::Widget *> _non_vertical; PreviewFillable *_fillable; diff --git a/src/ui/widget/point.h b/src/ui/widget/point.h index 15f1a80fb..17078df8f 100644 --- a/src/ui/widget/point.h +++ b/src/ui/widget/point.h @@ -13,8 +13,8 @@ #ifndef INKSCAPE_UI_WIDGET_POINT_H #define INKSCAPE_UI_WIDGET_POINT_H -#include <2geom/point.h> #include "ui/widget/labelled.h" +#include <2geom/point.h> #include "ui/widget/scalar.h" namespace Gtk { diff --git a/src/ui/widget/preferences-widget.cpp b/src/ui/widget/preferences-widget.cpp index a7b51d535..3ba00c083 100644 --- a/src/ui/widget/preferences-widget.cpp +++ b/src/ui/widget/preferences-widget.cpp @@ -18,10 +18,16 @@ #include <windows.h> #endif +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> #include <gtkmm/frame.h> #include <gtkmm/alignment.h> +#include <gtkmm/scale.h> #include <gtkmm/stock.h> +#include <gtkmm/table.h> #include "preferences.h" #include "ui/widget/preferences-widget.h" @@ -39,6 +45,8 @@ #include "selection-chemistry.h" #include "ui/dialog/filedialog.h" #include "xml/repr.h" + +#include <glibmm/convert.h> #include <glibmm/i18n.h> using namespace Inkscape::UI::Widget; @@ -49,98 +57,139 @@ namespace Widget { DialogPage::DialogPage() { - this->set_border_width(12); - this->set_col_spacings(12); - this->set_row_spacings(6); + set_border_width(12); + +#if WITH_GTKMM_3_0 + set_orientation(Gtk::ORIENTATION_VERTICAL); + set_column_spacing(12); + set_row_spacing(6); +#else + set_col_spacings(12); + set_row_spacings(6); +#endif } -void DialogPage::add_line(bool indent, Glib::ustring const &label, Gtk::Widget &widget, Glib::ustring const &suffix, const Glib::ustring &tip, bool expand_widget) +/** + * Add a widget to the bottom row of the dialog page + * + * \param[in] indent Whether the widget should be indented by one column + * \param[in] label The label text for the widget + * \param[in] widget The widget to add to the page + * \param[in] suffix Text for an optional label at the right of the widget + * \param[in] tip Tooltip text for the widget + * \param[in] expand_widget Whether to expand the widget horizontally + * \param[in] other_widget An optional additional widget to display at the right of the first one + */ +void DialogPage::add_line(bool indent, + Glib::ustring const &label, + Gtk::Widget &widget, + Glib::ustring const &suffix, + const Glib::ustring &tip, + bool expand_widget, + Gtk::Widget *other_widget) { - int start_col; - int row = this->property_n_rows(); - Gtk::Widget* w; - if (expand_widget) - { - w = &widget; - } - else - { - Gtk::HBox* hb = Gtk::manage(new Gtk::HBox()); - hb->set_spacing(12); - hb->pack_start(widget,false,false); - w = (Gtk::Widget*) hb; - } - if (label != "") - { - Gtk::Label* label_widget; -#if WITH_GTKMM_2_22 - label_widget = Gtk::manage(new Gtk::Label(label , Gtk::ALIGN_START , Gtk::ALIGN_CENTER, true)); + if (tip != "") + widget.set_tooltip_text (tip); + + Gtk::Alignment* label_alignment = Gtk::manage(new Gtk::Alignment()); + + Gtk::HBox* hb = Gtk::manage(new Gtk::HBox()); + hb->set_spacing(12); + hb->pack_start(widget, expand_widget, expand_widget); + + // Pack an additional widget into a box with the widget if desired + if (other_widget) + hb->pack_start(*other_widget, expand_widget, expand_widget); + + // Pack the widget into an alignment container so that it can + // be indented if desired + Gtk::Alignment* w_alignment = Gtk::manage(new Gtk::Alignment()); + w_alignment->add(*hb); + +#if WITH_GTKMM_3_0 + w_alignment->set_valign(Gtk::ALIGN_CENTER); #else - label_widget = Gtk::manage(new Gtk::Label(label , Gtk::ALIGN_LEFT , Gtk::ALIGN_CENTER, true)); + guint row = property_n_rows(); #endif + + // Add a label in the first column if provided + if (label != "") + { + Gtk::Label* label_widget = Gtk::manage(new Gtk::Label(label, Gtk::ALIGN_START, + Gtk::ALIGN_CENTER, true)); label_widget->set_mnemonic_widget(widget); + + // Pack the label into an alignment container so that we can indent it + // if necessary + label_alignment->add(*label_widget); + if (indent) - { - Gtk::Alignment* alignment = Gtk::manage(new Gtk::Alignment()); - alignment->set_padding(0, 0, 12, 0); - alignment->add(*label_widget); - this->attach(*alignment , 0, 1, row, row + 1, Gtk::FILL, Gtk::AttachOptions(), 0, 0); - } - else - this->attach(*label_widget , 0, 1, row, row + 1, Gtk::FILL, Gtk::AttachOptions(), 0, 0); - start_col = 1; - } - else - start_col = 0; + label_alignment->set_padding(0, 0, 12, 0); - if (start_col == 0 && indent) //indent this widget - { - Gtk::Alignment* alignment = Gtk::manage(new Gtk::Alignment()); - alignment->set_padding(0, 0, 12, 0); - alignment->add(*w); - this->attach(*alignment, start_col, 2, row, row + 1, Gtk::FILL | Gtk::EXPAND, Gtk::AttachOptions(), 0, 0); - } - else - { - this->attach(*w, start_col, 2, row, row + 1, Gtk::FILL | Gtk::EXPAND, Gtk::AttachOptions(), 0, 0); +#if WITH_GTKMM_3_0 + label_alignment->set_valign(Gtk::ALIGN_CENTER); + add(*label_alignment); + attach_next_to(*w_alignment, *label_alignment, Gtk::POS_RIGHT, 1, 1); +#else + attach(*label_alignment, 0, 1, row, row + 1, Gtk::FILL, Gtk::AttachOptions(), 0, 0); +#endif } - if (suffix != "") + // Now add the widget to the bottom of the dialog +#if WITH_GTKMM_3_0 + if (label == "") { -#if WITH_GTKMM_2_22 - Gtk::Label* suffix_widget = Gtk::manage(new Gtk::Label(suffix , Gtk::ALIGN_START , Gtk::ALIGN_CENTER, true)); + if (indent) + w_alignment->set_padding(0, 0, 12, 0); + + add(*w_alignment); + + GValue width = G_VALUE_INIT; + g_value_init(&width, G_TYPE_INT); + g_value_set_int(&width, 2); + gtk_container_child_set_property(GTK_CONTAINER(gobj()), GTK_WIDGET(w_alignment->gobj()), "width", &width); + } #else - Gtk::Label* suffix_widget = Gtk::manage(new Gtk::Label(suffix , Gtk::ALIGN_LEFT , Gtk::ALIGN_CENTER, true)); + // The widget should span two columns if there is no label + int w_col_span = 1; + if (label == "") + w_col_span = 2; + + attach(*w_alignment, 2 - w_col_span, 2, row, row + 1, + Gtk::FILL | Gtk::EXPAND, + Gtk::AttachOptions(), + 0, 0); #endif - if (expand_widget) - this->attach(*suffix_widget, 2, 3, row, row + 1, Gtk::FILL, Gtk::AttachOptions(), 0, 0); - else - ((Gtk::HBox*)w)->pack_start(*suffix_widget,false,false); - } - if (tip != "") + // Add a label on the right of the widget if desired + if (suffix != "") { - widget.set_tooltip_text (tip); + Gtk::Label* suffix_widget = Gtk::manage(new Gtk::Label(suffix , Gtk::ALIGN_START , Gtk::ALIGN_CENTER, true)); + hb->pack_start(*suffix_widget,false,false); } } void DialogPage::add_group_header(Glib::ustring name) { - int row = this->property_n_rows(); if (name != "") { -#if WITH_GTKMM_2_22 Gtk::Label* label_widget = Gtk::manage(new Gtk::Label(Glib::ustring(/*"<span size='large'>*/"<b>") + name + Glib::ustring("</b>"/*</span>"*/) , Gtk::ALIGN_START , Gtk::ALIGN_CENTER, true)); -#else - Gtk::Label* label_widget = Gtk::manage(new Gtk::Label(Glib::ustring(/*"<span size='large'>*/"<b>") + name + - Glib::ustring("</b>"/*</span>"*/) , Gtk::ALIGN_LEFT , Gtk::ALIGN_CENTER, true)); -#endif + label_widget->set_use_markup(true); - this->attach(*label_widget , 0, 4, row, row + 1, Gtk::FILL, Gtk::AttachOptions(), 0, 0); + +#if WITH_GTKMM_3_0 + label_widget->set_valign(Gtk::ALIGN_CENTER); + add(*label_widget); +// if (row != 1) + // set_row_spacing(row - 1, 18); +#else + int row = property_n_rows(); + attach(*label_widget , 0, 4, row, row + 1, Gtk::FILL, Gtk::AttachOptions(), 0, 0); if (row != 1) - this->set_row_spacing(row - 1, 18); + set_row_spacing(row - 1, 18); +#endif } } @@ -305,7 +354,7 @@ void PrefSpinUnit::on_my_value_changed() Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (getWidget()->get_visible()) //only take action if user changed value { - prefs->setDoubleUnit(_prefs_path, getValue(getUnit().abbr), getUnit().abbr); + prefs->setDoubleUnit(_prefs_path, getValue(getUnit()->abbr), getUnit()->abbr); } } @@ -381,17 +430,29 @@ ZoomCorrRuler::draw_marks(Cairo::RefPtr<Cairo::Context> cr, double dist, int maj } } -void -ZoomCorrRuler::redraw() { +#if !WITH_GTKMM_3_0 +bool +ZoomCorrRuler::on_expose_event(GdkEventExpose *event) { + bool result = false; + + if(get_is_drawable()) + { + Cairo::RefPtr<Cairo::Context> cr = get_window()->create_cairo_context(); + cr->rectangle(event->area.x, event->area.y, + event->area.width, event->area.height); + cr->clip(); + result = on_draw(cr); + } + + return result; +} +#endif + +bool +ZoomCorrRuler::on_draw(const Cairo::RefPtr<Cairo::Context>& cr) { Glib::RefPtr<Gdk::Window> window = get_window(); - Cairo::RefPtr<Cairo::Context> cr = window->create_cairo_context(); -#if WITH_GTKMM_2_24 int w = window->get_width(); -#else - int w, h; - window->get_size(w, h); -#endif _drawing_width = w - _border * 2; cr->set_source_rgb(1.0, 1.0, 1.0); @@ -428,14 +489,11 @@ ZoomCorrRuler::redraw() { draw_marks(cr, 1, 1); } cr->stroke(); -} -bool -ZoomCorrRuler::on_expose_event(GdkEventExpose */*event*/) { - this->redraw(); return true; } + void ZoomCorrRulerSlider::on_slider_value_changed() { @@ -443,9 +501,9 @@ ZoomCorrRulerSlider::on_slider_value_changed() { freeze = true; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble("/options/zoomcorrection/value", _slider.get_value() / 100.0); - _sb.set_value(_slider.get_value()); - _ruler.redraw(); + prefs->setDouble("/options/zoomcorrection/value", _slider->get_value() / 100.0); + _sb.set_value(_slider->get_value()); + _ruler.queue_draw(); freeze = false; } } @@ -458,8 +516,8 @@ ZoomCorrRulerSlider::on_spinbutton_value_changed() freeze = true; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble("/options/zoomcorrection/value", _sb.get_value() / 100.0); - _slider.set_value(_sb.get_value()); - _ruler.redraw(); + _slider->set_value(_sb.get_value()); + _ruler.queue_draw(); freeze = false; } } @@ -476,10 +534,16 @@ ZoomCorrRulerSlider::on_unit_changed() { double conv = _unit.getConversion(_unit.getUnitAbbr(), "px"); _ruler.set_unit_conversion(conv); if (_ruler.get_visible()) { - _ruler.redraw(); + _ruler.queue_draw(); } } +bool ZoomCorrRulerSlider::on_mnemonic_activate ( bool group_cycling ) +{ + return _sb.mnemonic_activate ( group_cycling ); +} + + void ZoomCorrRulerSlider::init(int ruler_width, int ruler_height, double lower, double upper, double step_increment, double page_increment, double default_value) @@ -491,13 +555,19 @@ ZoomCorrRulerSlider::init(int ruler_width, int ruler_height, double lower, doubl _ruler.set_size(ruler_width, ruler_height); - _slider.set_size_request(_ruler.width(), -1); - _slider.set_range (lower, upper); - _slider.set_increments (step_increment, page_increment); - _slider.set_value (value); - _slider.set_digits(2); +#if WITH_GTKMM_3_0 + _slider = Gtk::manage(new Gtk::Scale(Gtk::ORIENTATION_HORIZONTAL)); +#else + _slider = Gtk::manage(new Gtk::HScale()); +#endif + + _slider->set_size_request(_ruler.width(), -1); + _slider->set_range (lower, upper); + _slider->set_increments (step_increment, page_increment); + _slider->set_value (value); + _slider->set_digits(2); - _slider.signal_value_changed().connect(sigc::mem_fun(*this, &ZoomCorrRulerSlider::on_slider_value_changed)); + _slider->signal_value_changed().connect(sigc::mem_fun(*this, &ZoomCorrRulerSlider::on_slider_value_changed)); _sb.signal_value_changed().connect(sigc::mem_fun(*this, &ZoomCorrRulerSlider::on_spinbutton_value_changed)); _unit.signal_changed().connect(sigc::mem_fun(*this, &ZoomCorrRulerSlider::on_unit_changed)); @@ -511,18 +581,28 @@ ZoomCorrRulerSlider::init(int ruler_width, int ruler_height, double lower, doubl _unit.set_data("sensitive", GINT_TO_POINTER(1)); _unit.setUnit(prefs->getString("/options/zoomcorrection/unit")); - Gtk::Table *table = Gtk::manage(new Gtk::Table()); Gtk::Alignment *alignment1 = Gtk::manage(new Gtk::Alignment(0.5,1,0,0)); Gtk::Alignment *alignment2 = Gtk::manage(new Gtk::Alignment(0.5,1,0,0)); alignment1->add(_sb); alignment2->add(_unit); - table->attach(_slider, 0, 1, 0, 1); +#if WITH_GTKMM_3_0 + Gtk::Grid *table = Gtk::manage(new Gtk::Grid()); + table->attach(*_slider, 0, 0, 1, 1); + alignment1->set_halign(Gtk::ALIGN_CENTER); + table->attach(*alignment1, 1, 0, 1, 1); + table->attach(_ruler, 0, 1, 1, 1); + alignment2->set_halign(Gtk::ALIGN_CENTER); + table->attach(*alignment2, 1, 1, 1, 1); +#else + Gtk::Table *table = Gtk::manage(new Gtk::Table()); + table->attach(*_slider, 0, 1, 0, 1); table->attach(*alignment1, 1, 2, 0, 1, static_cast<Gtk::AttachOptions>(0)); table->attach(_ruler, 0, 1, 1, 2); table->attach(*alignment2, 1, 2, 1, 2, static_cast<Gtk::AttachOptions>(0)); +#endif - this->pack_start(*table, Gtk::PACK_EXPAND_WIDGET); + pack_start(*table, Gtk::PACK_SHRINK); } void @@ -532,8 +612,8 @@ PrefSlider::on_slider_value_changed() { freeze = true; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - prefs->setDouble(_prefs_path, _slider.get_value()); - _sb.set_value(_slider.get_value()); + prefs->setDouble(_prefs_path, _slider->get_value()); + _sb.set_value(_slider->get_value()); freeze = false; } } @@ -546,11 +626,16 @@ PrefSlider::on_spinbutton_value_changed() freeze = true; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); prefs->setDouble(_prefs_path, _sb.get_value()); - _slider.set_value(_sb.get_value()); + _slider->set_value(_sb.get_value()); freeze = false; } } +bool PrefSlider::on_mnemonic_activate ( bool group_cycling ) +{ + return _sb.mnemonic_activate ( group_cycling ); +} + void PrefSlider::init(Glib::ustring const &prefs_path, double lower, double upper, double step_increment, double page_increment, double default_value, int digits) @@ -562,11 +647,17 @@ PrefSlider::init(Glib::ustring const &prefs_path, freeze = false; - _slider.set_range (lower, upper); - _slider.set_increments (step_increment, page_increment); - _slider.set_value (value); - _slider.set_digits(digits); - _slider.signal_value_changed().connect(sigc::mem_fun(*this, &PrefSlider::on_slider_value_changed)); +#if WITH_GTKMM_3_0 + _slider = Gtk::manage(new Gtk::Scale(Gtk::ORIENTATION_HORIZONTAL)); +#else + _slider = Gtk::manage(new Gtk::HScale()); +#endif + + _slider->set_range (lower, upper); + _slider->set_increments (step_increment, page_increment); + _slider->set_value (value); + _slider->set_digits(digits); + _slider->signal_value_changed().connect(sigc::mem_fun(*this, &PrefSlider::on_slider_value_changed)); _sb.signal_value_changed().connect(sigc::mem_fun(*this, &PrefSlider::on_spinbutton_value_changed)); _sb.set_range (lower, upper); @@ -574,12 +665,20 @@ PrefSlider::init(Glib::ustring const &prefs_path, _sb.set_value (value); _sb.set_digits(digits); - Gtk::Table *table = Gtk::manage(new Gtk::Table()); Gtk::Alignment *alignment1 = Gtk::manage(new Gtk::Alignment(0.5,1,0,0)); alignment1->add(_sb); - table->attach(_slider, 0, 1, 0, 1); +#if WITH_GTKMM_3_0 + Gtk::Grid *table = Gtk::manage(new Gtk::Grid()); + _slider->set_hexpand(); + table->attach(*_slider, 0, 0, 1, 1); + alignment1->set_halign(Gtk::ALIGN_CENTER); + table->attach(*alignment1, 1, 0, 1, 1); +#else + Gtk::Table *table = Gtk::manage(new Gtk::Table()); + table->attach(*_slider, 0, 1, 0, 1); table->attach(*alignment1, 1, 2, 0, 1, static_cast<Gtk::AttachOptions>(0)); +#endif this->pack_start(*table, Gtk::PACK_EXPAND_WIDGET); } @@ -594,11 +693,7 @@ void PrefCombo::init(Glib::ustring const &prefs_path, for (int i = 0 ; i < num_items; ++i) { -#if WITH_GTKMM_2_24 this->append(labels[i]); -#else - this->append_text(labels[i]); -#endif _values.push_back(values[i]); if (value == values[i]) row = i; @@ -620,11 +715,7 @@ void PrefCombo::init(Glib::ustring const &prefs_path, for (int i = 0 ; i < num_items; ++i) { -#if WITH_GTKMM_2_24 this->append(labels[i]); -#else - this->append_text(labels[i]); -#endif _ustr_values.push_back(values[i]); if (value == values[i]) row = i; @@ -637,7 +728,7 @@ void PrefCombo::on_changed() if (this->get_visible()) //only take action if user changed value { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if(_values.size() > 0) + if(!_values.empty()) { prefs->setInt(_prefs_path, _values[this->get_active_row_number()]); } @@ -686,6 +777,11 @@ void PrefEntryButtonHBox::onRelatedButtonClickedCallback() } } +bool PrefEntryButtonHBox::on_mnemonic_activate ( bool group_cycling ) +{ + return relatedEntry->mnemonic_activate ( group_cycling ); +} + void PrefEntryFileButtonHBox::init(Glib::ustring const &prefs_path, bool visibility) { @@ -818,6 +914,11 @@ void PrefEntryFileButtonHBox::onRelatedButtonClickedCallback() } } +bool PrefEntryFileButtonHBox::on_mnemonic_activate ( bool group_cycling ) +{ + return relatedEntry->mnemonic_activate ( group_cycling ); +} + void PrefFileButton::init(Glib::ustring const &prefs_path) { _prefs_path = prefs_path; diff --git a/src/ui/widget/preferences-widget.h b/src/ui/widget/preferences-widget.h index 874e0958a..cb4ce17d1 100644 --- a/src/ui/widget/preferences-widget.h +++ b/src/ui/widget/preferences-widget.h @@ -15,8 +15,17 @@ #ifndef INKSCAPE_UI_WIDGET_INKSCAPE_PREFERENCES_H #define INKSCAPE_UI_WIDGET_INKSCAPE_PREFERENCES_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + #include <iostream> #include <vector> + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/filechooserbutton.h> #include "ui/widget/spinbutton.h" #include <stddef.h> @@ -25,14 +34,26 @@ #include <gtkmm/radiobutton.h> #include <gtkmm/comboboxtext.h> #include <gtkmm/drawingarea.h> -#include <gtkmm/scale.h> + +#if WITH_GTKMM_3_0 +#include <gtkmm/grid.h> +#else #include <gtkmm/table.h> +#endif #include "ui/widget/color-picker.h" #include "ui/widget/unit-menu.h" #include "ui/widget/spinbutton.h" #include "ui/widget/scalar-unit.h" +namespace Gtk { +#if WITH_GTKMM_3_0 +class Scale; +#else +class HScale; +#endif +} + namespace Inkscape { namespace UI { namespace Widget { @@ -101,8 +122,6 @@ public: ZoomCorrRuler(int width = 100, int height = 20); void set_size(int x, int y); void set_unit_conversion(double conv) { _unitconv = conv; } - void set_cairo_context(Cairo::RefPtr<Cairo::Context> cr); - void redraw(); int width() { return _min_width + _border*2; } @@ -110,7 +129,12 @@ public: static const double textpadding; private: +#if !WITH_GTKMM_3_0 bool on_expose_event(GdkEventExpose *event); +#endif + + bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr); + void draw_marks(Cairo::RefPtr<Cairo::Context> cr, double dist, int major_interval); double _unitconv; @@ -130,10 +154,15 @@ private: void on_slider_value_changed(); void on_spinbutton_value_changed(); void on_unit_changed(); + virtual bool on_mnemonic_activate( bool group_cycling ); Inkscape::UI::Widget::SpinButton _sb; UnitMenu _unit; - Gtk::HScale _slider; +#if WITH_GTKMM_3_0 + Gtk::Scale* _slider; +#else + Gtk::HScale* _slider; +#endif ZoomCorrRuler _ruler; bool freeze; // used to block recursive updates of slider and spinbutton }; @@ -147,10 +176,17 @@ public: private: void on_slider_value_changed(); void on_spinbutton_value_changed(); - + virtual bool on_mnemonic_activate( bool group_cycling ); + Glib::ustring _prefs_path; Inkscape::UI::Widget::SpinButton _sb; - Gtk::HScale _slider; + +#if WITH_GTKMM_3_0 + Gtk::Scale* _slider; +#else + Gtk::HScale* _slider; +#endif + bool freeze; // used to block recursive updates of slider and spinbutton }; @@ -188,6 +224,7 @@ class PrefEntryButtonHBox : public Gtk::HBox public: void init(Glib::ustring const &prefs_path, bool mask, Glib::ustring const &default_string); + protected: Glib::ustring _prefs_path; Glib::ustring _default_string; @@ -195,6 +232,7 @@ protected: Gtk::Entry *relatedEntry; void onRelatedEntryChangedCallback(); void onRelatedButtonClickedCallback(); + virtual bool on_mnemonic_activate( bool group_cycling ); }; class PrefEntryFileButtonHBox : public Gtk::HBox @@ -208,6 +246,7 @@ protected: Gtk::Entry *relatedEntry; void onRelatedEntryChangedCallback(); void onRelatedButtonClickedCallback(); + virtual bool on_mnemonic_activate( bool group_cycling ); }; class PrefFileButton : public Gtk::FileChooserButton @@ -243,11 +282,15 @@ protected: void on_changed(); }; +#if WITH_GTKMM_3_0 +class DialogPage : public Gtk::Grid +#else class DialogPage : public Gtk::Table +#endif { public: DialogPage(); - void add_line(bool indent, Glib::ustring const &label, Gtk::Widget& widget, Glib::ustring const &suffix, Glib::ustring const &tip, bool expand = true); + void add_line(bool indent, Glib::ustring const &label, Gtk::Widget& widget, Glib::ustring const &suffix, Glib::ustring const &tip, bool expand = true, Gtk::Widget *other_widget = NULL); void add_group_header(Glib::ustring name); void set_tip(Gtk::Widget &widget, Glib::ustring const &tip); }; diff --git a/src/ui/widget/registered-widget.cpp b/src/ui/widget/registered-widget.cpp index ea2bac867..175f6471c 100644 --- a/src/ui/widget/registered-widget.cpp +++ b/src/ui/widget/registered-widget.cpp @@ -27,7 +27,6 @@ #include "ui/widget/random.h" #include "widgets/spinbutton-events.h" -#include "helper/units.h" #include "xml/repr.h" #include "svg/svg-color.h" #include "svg/stringstream.h" @@ -50,8 +49,10 @@ RegisteredCheckButton::~RegisteredCheckButton() _toggled_connection.disconnect(); } -RegisteredCheckButton::RegisteredCheckButton (const Glib::ustring& label, const Glib::ustring& tip, const Glib::ustring& key, Registry& wr, bool right, Inkscape::XML::Node* repr_in, SPDocument *doc_in) +RegisteredCheckButton::RegisteredCheckButton (const Glib::ustring& label, const Glib::ustring& tip, const Glib::ustring& key, Registry& wr, bool right, Inkscape::XML::Node* repr_in, SPDocument *doc_in, char const *active_str, char const *inactive_str) : RegisteredWidget<Gtk::CheckButton>() + , _active_str(active_str) + , _inactive_str(inactive_str) { init_parent(key, wr, repr_in, doc_in); @@ -89,7 +90,7 @@ RegisteredCheckButton::on_toggled() return; _wr->setUpdating (true); - write_to_xml(get_active() ? "true" : "false"); + write_to_xml(get_active() ? _active_str : _inactive_str); //The slave button is greyed out if the master button is unchecked for (std::list<Gtk::Widget*>::const_iterator i = _slavewidgets.begin(); i != _slavewidgets.end(); ++i) { (*i)->set_sensitive(get_active()); @@ -118,9 +119,9 @@ RegisteredUnitMenu::RegisteredUnitMenu (const Glib::ustring& label, const Glib:: } void -RegisteredUnitMenu::setUnit (const SPUnit* unit) +RegisteredUnitMenu::setUnit (Glib::ustring unit) { - getUnitMenu()->setUnit (sp_unit_get_abbreviation (unit)); + getUnitMenu()->setUnit(unit); } void diff --git a/src/ui/widget/registered-widget.h b/src/ui/widget/registered-widget.h index 2a7843a51..d64c09c16 100644 --- a/src/ui/widget/registered-widget.h +++ b/src/ui/widget/registered-widget.h @@ -32,7 +32,6 @@ #include <gtkmm/checkbutton.h> -class SPUnit; class SPDocument; namespace Gtk { @@ -56,6 +55,11 @@ public: event_description = _event_description; write_undo = true; } + void set_xml_target(Inkscape::XML::Node *xml_node, SPDocument *document) + { + repr = xml_node; + doc = document; + } bool is_updating() {if (_wr) return _wr->isUpdating(); else return false;} @@ -128,6 +132,7 @@ private: repr = NULL; doc = NULL; write_undo = false; + event_type = -1; } }; @@ -136,7 +141,7 @@ private: class RegisteredCheckButton : public RegisteredWidget<Gtk::CheckButton> { public: virtual ~RegisteredCheckButton(); - RegisteredCheckButton (const Glib::ustring& label, const Glib::ustring& tip, const Glib::ustring& key, Registry& wr, bool right=true, Inkscape::XML::Node* repr_in=NULL, SPDocument *doc_in=NULL); + RegisteredCheckButton (const Glib::ustring& label, const Glib::ustring& tip, const Glib::ustring& key, Registry& wr, bool right=true, Inkscape::XML::Node* repr_in=NULL, SPDocument *doc_in=NULL, char const *active_str = "true", char const *inactive_str = "false"); void setActive (bool); @@ -153,6 +158,7 @@ public: // if a callback checks it, it must reset it back to false protected: + char const *_active_str, *_inactive_str; sigc::connection _toggled_connection; void on_toggled(); }; @@ -166,8 +172,8 @@ public: Inkscape::XML::Node* repr_in = NULL, SPDocument *doc_in = NULL ); - void setUnit (const SPUnit*); - Unit getUnit() const { return static_cast<UnitMenu*>(_widget)->getUnit(); }; + void setUnit (const Glib::ustring); + Unit const * getUnit() const { return static_cast<UnitMenu*>(_widget)->getUnit(); }; UnitMenu* getUnitMenu() const { return static_cast<UnitMenu*>(_widget); }; sigc::connection _changed_connection; diff --git a/src/ui/widget/registry.h b/src/ui/widget/registry.h index ed1281d79..2da29735c 100644 --- a/src/ui/widget/registry.h +++ b/src/ui/widget/registry.h @@ -9,10 +9,6 @@ #ifndef INKSCAPE_UI_WIDGET_REGISTRY__H #define INKSCAPE_UI_WIDGET_REGISTRY__H -#include <map> -#include <glibmm/i18n.h> -#include <glibmm/ustring.h> - namespace Gtk { class Object; } diff --git a/src/ui/widget/rendering-options.cpp b/src/ui/widget/rendering-options.cpp index 7655f25e3..d6248df69 100644 --- a/src/ui/widget/rendering-options.cpp +++ b/src/ui/widget/rendering-options.cpp @@ -12,10 +12,9 @@ # include <config.h> #endif -#include <glibmm/i18n.h> - -#include "unit-constants.h" #include "rendering-options.h" +#include "util/units.h" +#include <glibmm/i18n.h> namespace Inkscape { namespace UI { @@ -60,8 +59,8 @@ RenderingOptions::RenderingOptions () : _radio_bitmap.signal_toggled().connect(sigc::mem_fun(*this, &RenderingOptions::_toggled)); // configure default DPI - _dpi.setRange(PT_PER_IN,2400.0); - _dpi.setValue(PT_PER_IN); + _dpi.setRange(Inkscape::Util::Quantity::convert(1, "in", "pt"),2400.0); + _dpi.setValue(Inkscape::Util::Quantity::convert(1, "in", "pt")); _dpi.setIncrements(1.0,10.0); _dpi.setDigits(0); _dpi.update(); diff --git a/src/ui/widget/rotateable.cpp b/src/ui/widget/rotateable.cpp index c31e6f529..72ec69362 100644 --- a/src/ui/widget/rotateable.cpp +++ b/src/ui/widget/rotateable.cpp @@ -7,11 +7,19 @@ * Released under GNU GPL. Read the file 'COPYING' for more information. */ +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> #include <gtkmm/eventbox.h> #include <glibmm/i18n.h> #include <2geom/point.h> -#include "event-context.h" +#include "ui/tools/tool-base.h" #include "rotateable.h" namespace Inkscape { @@ -24,25 +32,28 @@ Rotateable::Rotateable(): { dragging = false; working = false; + scrolling = false; modifier = 0; current_axis = axis; signal_button_press_event().connect(sigc::mem_fun(*this, &Rotateable::on_click)); signal_motion_notify_event().connect(sigc::mem_fun(*this, &Rotateable::on_motion)); signal_button_release_event().connect(sigc::mem_fun(*this, &Rotateable::on_release)); + signal_scroll_event().connect(sigc::mem_fun(*this, &Rotateable::on_scroll)); + } bool Rotateable::on_click(GdkEventButton *event) { - if (event->button == 1) { + if (event->button == 1) { drag_started_x = event->x; drag_started_y = event->y; - modifier = get_single_modifier(modifier, event->state); + modifier = get_single_modifier(modifier, event->state); dragging = true; working = false; current_axis = axis; return true; - } - return false; + } + return false; } guint Rotateable::get_single_modifier(guint old, guint state) { @@ -100,7 +111,7 @@ bool Rotateable::on_motion(GdkEventMotion *event) { do_motion(force, modifier); } } - gobble_motion_events(GDK_BUTTON1_MASK); + Inkscape::UI::Tools::gobble_motion_events(GDK_BUTTON1_MASK); return true; } return false; @@ -108,9 +119,9 @@ bool Rotateable::on_motion(GdkEventMotion *event) { bool Rotateable::on_release(GdkEventButton *event) { - if (dragging && working) { + if (dragging && working) { double angle = atan2(event->y - drag_started_y, event->x - drag_started_x); - double force = CLAMP (-(angle - current_axis)/maxdecl, -1, 1); + double force = CLAMP(-(angle - current_axis) / maxdecl, -1, 1); if (fabs(force) < 0.002) force = 0; // snap to zero do_release(force, modifier); @@ -118,12 +129,40 @@ bool Rotateable::on_release(GdkEventButton *event) { dragging = false; working = false; return true; - } + } dragging = false; working = false; - return false; + return false; } +bool Rotateable::on_scroll(GdkEventScroll* event) +{ + double change = 0.0; + + if (event->direction == GDK_SCROLL_UP) { + change = 1.0; + } else if (event->direction == GDK_SCROLL_DOWN) { + change = -1.0; + } else { + return FALSE; + } + + drag_started_x = event->x; + drag_started_y = event->y; + modifier = get_single_modifier(modifier, event->state); + dragging = false; + working = false; + scrolling = true; + current_axis = axis; + + do_scroll(change, modifier); + + dragging = false; + working = false; + scrolling = false; + + return TRUE; +} Rotateable::~Rotateable() { } diff --git a/src/ui/widget/rotateable.h b/src/ui/widget/rotateable.h index 15e0bf71c..52fb5306c 100644 --- a/src/ui/widget/rotateable.h +++ b/src/ui/widget/rotateable.h @@ -31,10 +31,12 @@ public: bool on_click(GdkEventButton *event); bool on_motion(GdkEventMotion *event); bool on_release(GdkEventButton *event); + bool on_scroll(GdkEventScroll* event); double axis; double current_axis; double maxdecl; + bool scrolling; private: double drag_started_x; @@ -47,6 +49,7 @@ private: virtual void do_motion (double /*by*/, guint /*state*/) {} virtual void do_release (double /*by*/, guint /*state*/) {} + virtual void do_scroll (double /*by*/, guint /*state*/) {} }; } // namespace Widget diff --git a/src/ui/widget/ruler.cpp b/src/ui/widget/ruler.cpp deleted file mode 100644 index ecbd641a7..000000000 --- a/src/ui/widget/ruler.cpp +++ /dev/null @@ -1,218 +0,0 @@ -/** \file - * Gtkmm facade/wrapper around SPRuler code that formerly lived - * in desktop-events.cpp - */ -/* - * Authors: - * Ralf Stephan <ralf@ark.in-berlin.de> - * Lauris Kaplinski - * Jon A. Cruz <jon@joncruz.org> - * Abhishek Sharma - * - * Copyright (C) 2005 Ralf Stephan - * - * Released under GNU GPL, read the file 'COPYING' for more information - */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include <glibmm/i18n.h> - -#include "ui/widget/ruler.h" -#include "widgets/ruler.h" -#include "helper/units.h" - -#include "xml/repr.h" -#include "display/sp-canvas.h" -#include "display/guideline.h" -#include "desktop.h" -#include "desktop-handles.h" -#include "document.h" -#include "document-undo.h" -#include "sp-namedview.h" -#include "verbs.h" - -namespace Gtk { -namespace Deprecated { -void Ruler::set_range(double lower, double upper, double position, double max_size) -{ -gtk_deprecated_ruler_set_range(gobj(), lower, upper, position, max_size); -} - -void Ruler::get_range(double& lower, double& upper, double& position, double& max_size) -{ -gtk_deprecated_ruler_get_range(gobj(), &(lower), &(upper), &(position), &(max_size)); -} -}// namespace Deprecated -}// namespace Gtk - - -namespace Inkscape { -namespace UI { -namespace Widget { - -void -Ruler::init(SPDesktop *dt, Gtk::Widget &w) -{ - _dt = dt; - _canvas_widget = &w; - _dragging = false; - _guide = 0; - sp_ruler_set_metric(GTK_DEPRECATED_RULER(_r->gobj()), SP_PT); - _r->set_range(-500, 500, 0, 1000); -} - -void -Ruler::get_range(double &lo, double &up, double &pos, double &max) -{ - _r->get_range(lo, up, pos, max); -} - -void -Ruler::set_range(double lo, double up, double pos, double max) -{ - _r->set_range(lo, up, pos, max); -} - -/// Set metric from namedview -void -Ruler::update_metric() -{ - if (!_dt) return; - sp_ruler_set_metric(GTK_DEPRECATED_RULER(_r->gobj()), _dt->namedview->getDefaultMetric()); -} - -/// Returns text to be used for tooltip for ruler. -/// \todo incorrect -Glib::ustring -Ruler::get_tip() -{ - return gettext(sp_unit_get_plural( _dt - ? _dt->namedview->doc_units - : &sp_unit_get_by_id(SP_UNIT_PT) )); -} - -/// Helper that gets mouse coordinates relative to canvas widget. -void -Ruler::canvas_get_pointer(int &x, int &y) -{ - Gdk::ModifierType mask; - (void) _canvas_widget->get_window()->get_pointer(x, y, mask); -} - -Geom::Point -Ruler::get_event_dt() -{ - int wx, wy; - canvas_get_pointer(wx, wy); - Geom::Point const event_win(wx, wy); - Geom::Point const event_w(sp_canvas_window_to_world(_dt->canvas, event_win)); - return _dt->w2d(event_w); -} - -bool -Ruler::on_button_press_event(GdkEventButton *evb) -{ - g_assert(_dt); - Geom::Point const &event_dt = get_event_dt(); - Inkscape::XML::Node *repr = _dt->namedview->getRepr(); - - if (evb->button == 1) { - _dragging = true; - sp_repr_set_boolean(repr, "showguides", TRUE); - sp_repr_set_boolean(repr, "inkscape:guide-bbox", TRUE); - _guide = sp_guideline_new(_dt->guides, NULL, event_dt, _horiz_f ? Geom::Point(0.,1.) : Geom::Point(1.,0.)); - sp_guideline_set_color(SP_GUIDELINE(_guide), _dt->namedview->guidehicolor); - (void) get_window()->pointer_grab(false, - Gdk::BUTTON_RELEASE_MASK | - Gdk::POINTER_MOTION_MASK | - Gdk::POINTER_MOTION_HINT_MASK, - evb->time); - } - return false; -} - -bool -Ruler::on_motion_notify_event(GdkEventMotion *) -{ - g_assert(_dt); - Geom::Point const &event_dt = get_event_dt(); - - if (_dragging) { - sp_guideline_set_position(SP_GUIDELINE(_guide), event_dt); - _dt->set_coordinate_status(event_dt); - _dt->setPosition(event_dt); - } - return false; -} - -bool -Ruler::on_button_release_event(GdkEventButton *evb) -{ - g_assert(_dt); - int wx, wy; - canvas_get_pointer(wx, wy); - Geom::Point const &event_dt = get_event_dt(); - - if (_dragging && evb->button == 1) { - Gdk::Window::pointer_ungrab(evb->time); - gtk_object_destroy(GTK_OBJECT(_guide)); - _guide = 0; - _dragging = false; - - if ( (_horiz_f ? wy : wx ) >= 0 ) { - Inkscape::XML::Document *xml_doc = _dt->doc()->getReprDoc(); - Inkscape::XML::Node *repr = xml_doc->createElement("sodipodi:guide"); - repr->setAttribute("orientation", _horiz_f ? "horizontal" : "vertical"); - double const guide_pos_dt = event_dt[ _horiz_f ? Geom::Y : Geom::X ]; - sp_repr_set_svg_double(repr, "position", guide_pos_dt); - _dt->namedview->getRepr()->appendChild(repr); - Inkscape::GC::release(repr); - DocumentUndo::done(sp_desktop_document(_dt), SP_VERB_NONE, - /* TODO: annotate */ "ruler.cpp:157"); - } - _dt->set_coordinate_status(event_dt); - } - return false; -} - -//------------------------------------------------------------ -HRuler::HRuler() -{ - _dt = 0; - _r = static_cast<Gtk::Deprecated::HRuler*>(Glib::wrap(static_cast<GtkWidget*> (sp_hruler_new()))); - add(*_r); - _horiz_f = true; -} - -HRuler::~HRuler() -{ -} - - -VRuler::VRuler() -{ - _dt = 0; - _r = static_cast<Gtk::Deprecated::VRuler*>(Glib::wrap(static_cast<GtkWidget*> (sp_vruler_new()))); - add(*_r); - _horiz_f = false; -} - -VRuler::~VRuler() -{ -} - -}}} - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/widget/ruler.h b/src/ui/widget/ruler.h deleted file mode 100644 index d63c585a8..000000000 --- a/src/ui/widget/ruler.h +++ /dev/null @@ -1,184 +0,0 @@ -#ifndef SEEN_UI_WIDGET_RULER_H -#define SEEN_UI_WIDGET_RULER_H - -/* - * Authors: - * Ralf Stephan <ralf@ark.in-berlin.de> - * - * Copyright (C) 2005 The Authors - * - * Released under GNU GPL, read the file 'COPYING' for more information - */ - -#include <gtkmm/eventbox.h> -#include <2geom/point.h> - -struct SPCanvasItem; -class SPDesktop; -namespace Glib { - class ustring; -} - -typedef struct _GtkDeprecatedRuler GtkDeprecatedRuler; -typedef struct _GtkDeprecatedVRuler GtkDeprecatedVRuler; -typedef struct _GtkDeprecatedHRuler GtkDeprecatedHRuler; - - -// This is an import of the now-deprecated Gtk::Ruler API. -namespace Gtk { -namespace Deprecated { - -/** Base class for horizontal or vertical rulers. - * - * This is an abstract base for Gtk::HRuler and - * Gtk::VRuler. Users should only instantiate those types. - */ -class Ruler : public Widget -{ -public: - virtual ~Ruler(); - -protected: - explicit Ruler(const Glib::ConstructParams& construct_params); - explicit Ruler(GtkDeprecatedRuler* castitem); - -public: - ///Provides access to the underlying C GtkObject. - GtkDeprecatedRuler* gobj() { return reinterpret_cast<GtkDeprecatedRuler*>(gobject_); } - - ///Provides access to the underlying C GtkObject. - const GtkDeprecatedRuler* gobj() const { return reinterpret_cast<GtkDeprecatedRuler*>(gobject_); } - -protected: - Ruler(); - -public: - /** sets the range of the ruler. - * <i>upper</i> and <i>lower</i> arguments denote the extents of the Ruler. - * <i>max_size</i> is the largest number displayed by the ruler. - * <i>position</i> gives the initial value of the ruler. - * Rulers do not have sane defaults so this function should always be called. - */ - void set_range(double lower, double upper, double position, double max_size); - - /** Retrieves values indicating the range and current position of a Gtk::Ruler. - * See set_range(). - * - * @param lower Location to store lower limit of the ruler, or <tt>0</tt>. - * @param upper Location to store upper limit of the ruler, or <tt>0</tt>. - * @param position Location to store the current position of the mark on the ruler, or <tt>0</tt>. - * @param max_size Location to store the maximum size of the ruler used when calculating - * the space to leave for the text, or <tt>0</tt>. - */ - void get_range(double& lower, double& upper, double& position, double& max_size); -}; - - -/** Vertical Ruler */ -class VRuler : public Ruler -{ - public: - virtual ~VRuler(); - -public: - ///Provides access to the underlying C GtkObject. - GtkDeprecatedVRuler* gobj() { return reinterpret_cast<GtkDeprecatedVRuler*>(gobject_); } - - ///Provides access to the underlying C GtkObject. - const GtkDeprecatedVRuler* gobj() const { return reinterpret_cast<GtkDeprecatedVRuler*>(gobject_); } - -public: - VRuler(); -}; //class VRuler - -/** Horizontal Ruler */ -class HRuler : public Ruler -{ - public: - virtual ~HRuler(); - -public: - ///Provides access to the underlying C GtkObject. - GtkDeprecatedHRuler* gobj() { return reinterpret_cast<GtkDeprecatedHRuler*>(gobject_); } - - ///Provides access to the underlying C GtkObject. - const GtkDeprecatedHRuler* gobj() const { return reinterpret_cast<GtkDeprecatedHRuler*>(gobject_); } - -public: - HRuler(); -}; // class HRuler -} // namespace Deprecated -} // namespace Gtk - - - -namespace Inkscape { -namespace UI { -namespace Widget { - -/** - * Gtkmm facade/wrapper around sp_rulers. - */ -class Ruler : public Gtk::EventBox -{ -public: - void init (SPDesktop*, Gtk::Widget&); - void get_range (double&, double&, double&, double&); - void set_range (double, double, double, double); - void update_metric(); - Glib::ustring get_tip(); - -protected: - SPDesktop *_dt; - SPCanvasItem *_guide; - Gtk::Widget *_canvas_widget; - Gtk::Deprecated::Ruler *_r; - bool _horiz_f, _dragging; - - virtual bool on_button_press_event (GdkEventButton *); - virtual bool on_motion_notify_event (GdkEventMotion *); - virtual bool on_button_release_event (GdkEventButton *); - -private: - void canvas_get_pointer (int&, int&); - Geom::Point get_event_dt(); -}; - -/** - * Horizontal ruler gtkmm wrapper. - */ -class HRuler : public Ruler -{ -public: - HRuler(); - ~HRuler(); -}; - -/** - * Vertical ruler gtkmm wrapper. - */ -class VRuler : public Ruler -{ -public: - VRuler(); - ~VRuler(); -}; - -} // namespace Widget -} // namespace UI -} // namespace Inkscape - - -#endif // SEEN_UI_WIDGET_RULER_H - - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/widget/scalar-unit.cpp b/src/ui/widget/scalar-unit.cpp index 99ff70846..4fa1a7584 100644 --- a/src/ui/widget/scalar-unit.cpp +++ b/src/ui/widget/scalar-unit.cpp @@ -16,6 +16,8 @@ #include "scalar-unit.h" #include "spinbutton.h" +using Inkscape::Util::unit_table; + namespace Inkscape { namespace UI { namespace Widget { @@ -100,7 +102,7 @@ void ScalarUnit::resetUnitType(UnitType unit_type) lastUnits = _unit_menu->getUnitAbbr(); } -Unit ScalarUnit::getUnit() const +Unit const * ScalarUnit::getUnit() const { g_assert(_unit_menu != NULL); return _unit_menu->getUnit(); @@ -226,14 +228,13 @@ void ScalarUnit::on_unit_changed() Glib::ustring abbr = _unit_menu->getUnitAbbr(); _suffix->set_label(abbr); - Inkscape::Util::UnitTable &table = _unit_menu->getUnitTable(); - Inkscape::Util::Unit new_unit = (table.getUnit(abbr)); - Inkscape::Util::Unit old_unit = (table.getUnit(lastUnits)); + Inkscape::Util::Unit const *new_unit = unit_table.getUnit(abbr); + Inkscape::Util::Unit const *old_unit = unit_table.getUnit(lastUnits); double convertedVal = 0; - if (old_unit.type == UNIT_TYPE_DIMENSIONLESS && new_unit.type == UNIT_TYPE_LINEAR) { + if (old_unit->type == UNIT_TYPE_DIMENSIONLESS && new_unit->type == UNIT_TYPE_LINEAR) { convertedVal = PercentageToAbsolute(Scalar::getValue()); - } else if (old_unit.type == UNIT_TYPE_LINEAR && new_unit.type == UNIT_TYPE_DIMENSIONLESS) { + } else if (old_unit->type == UNIT_TYPE_LINEAR && new_unit->type == UNIT_TYPE_DIMENSIONLESS) { convertedVal = AbsoluteToPercentage(Scalar::getValue()); } else { double conversion = _unit_menu->getConversion(lastUnits); diff --git a/src/ui/widget/scalar-unit.h b/src/ui/widget/scalar-unit.h index 4f22f438c..9e310d3bd 100644 --- a/src/ui/widget/scalar-unit.h +++ b/src/ui/widget/scalar-unit.h @@ -82,7 +82,7 @@ public: /** * Gets the object for the currently selected unit. */ - Unit getUnit() const; + Unit const * getUnit() const; /** * Gets the UnitType ID for the unit. diff --git a/src/ui/widget/scalar.cpp b/src/ui/widget/scalar.cpp index 9bbcc80f9..fca8a7974 100644 --- a/src/ui/widget/scalar.cpp +++ b/src/ui/widget/scalar.cpp @@ -142,7 +142,7 @@ void Scalar::update() void Scalar::addSlider() { #if WITH_GTKMM_3_0 - Gtk::HScale *scale = new Gtk::HScale(static_cast<SpinButton*>(_widget)->get_adjustment()); + Gtk::Scale *scale = new Gtk::Scale(static_cast<SpinButton*>(_widget)->get_adjustment()); #else Gtk::HScale *scale = new Gtk::HScale( * static_cast<SpinButton*>(_widget)->get_adjustment() ); #endif diff --git a/src/ui/widget/selected-style.cpp b/src/ui/widget/selected-style.cpp index a60e3cc31..042a6614e 100644 --- a/src/ui/widget/selected-style.cpp +++ b/src/ui/widget/selected-style.cpp @@ -23,8 +23,9 @@ #include "desktop-handles.h" #include "style.h" #include "desktop-style.h" -#include "sp-linear-gradient-fns.h" -#include "sp-radial-gradient-fns.h" +#include "sp-namedview.h" +#include "sp-linear-gradient.h" +#include "sp-radial-gradient.h" #include "sp-pattern.h" #include "ui/dialog/dialog-manager.h" #include "ui/dialog/fill-and-stroke.h" @@ -38,8 +39,7 @@ #include "sp-gradient.h" #include "svg/svg-color.h" #include "svg/css-ostringstream.h" -#include "helper/units.h" -#include "event-context.h" +#include "ui/tools/tool-base.h" #include "message-context.h" #include "verbs.h" #include "color.h" @@ -47,7 +47,12 @@ #include "pixmaps/cursor-adj-h.xpm" #include "pixmaps/cursor-adj-s.xpm" #include "pixmaps/cursor-adj-l.xpm" +#include "pixmaps/cursor-adj-a.xpm" #include "sp-cursor.h" +#include "gradient-chemistry.h" +#include "util/units.h" + +using Inkscape::Util::unit_table; static gdouble const _sw_presets[] = { 32 , 16 , 10 , 8 , 6 , 4 , 3 , 2 , 1.5 , 1 , 0.75 , 0.5 , 0.25 , 0.1 }; static gchar const *const _sw_presets_str[] = {"32", "16", "10", "8", "6", "4", "3", "2", "1.5", "1", "0.75", "0.5", "0.25", "0.1"}; @@ -102,7 +107,7 @@ typedef enum { // pointers/types used need to be read-only. So until we correct the using // code, those warnings are actually desired. They say "Hey! Fix this". We // definitely don't want to hide/ignore them. --JonCruz -static GtkTargetEntry ui_drop_target_entries [] = { +static const GtkTargetEntry ui_drop_target_entries [] = { {"application/x-color", 0, APP_X_COLOR} }; @@ -117,8 +122,11 @@ SelectedStyle::SelectedStyle(bool /*layout*/) current_stroke_width(0), _desktop (NULL), - +#if WITH_GTKMM_3_0 + _table(), +#else _table(2, 6), +#endif _fill_label (_("Fill:")), _stroke_label (_("Stroke:")), _opacity_label (_("O:")), @@ -143,10 +151,7 @@ SelectedStyle::SelectedStyle(bool /*layout*/) _opacity_blocked (false), - _popup_px(_sw_group), - _popup_pt(_sw_group), - _popup_mm(_sw_group), - + _unit_mis(NULL), _sw_unit(NULL) { _drop[0] = _drop[1] = 0; @@ -159,8 +164,13 @@ SelectedStyle::SelectedStyle(bool /*layout*/) _opacity_label.set_alignment(0.0, 0.5); _opacity_label.set_padding(0, 0); +#if WITH_GTKMM_3_0 + _table.set_column_spacing(2); + _table.set_row_spacing(0); +#else _table.set_col_spacings (2); _table.set_row_spacings (0); +#endif for (int i = SS_FILL; i <= SS_STROKE; i++) { @@ -297,34 +307,41 @@ SelectedStyle::SelectedStyle(bool /*layout*/) } { - _popup_px.add(*(new Gtk::Label(_("px"), 0.0, 0.5))); - _popup_px.signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::on_popup_px)); - _popup_sw.attach(_popup_px, 0,1, 0,1); - - _popup_pt.add(*(new Gtk::Label(_("pt"), 0.0, 0.5))); - _popup_pt.signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::on_popup_pt)); - _popup_sw.attach(_popup_pt, 0,1, 1,2); - - _popup_mm.add(*(new Gtk::Label(_("mm"), 0.0, 0.5))); - _popup_mm.signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::on_popup_mm)); - _popup_sw.attach(_popup_mm, 0,1, 2,3); + int row = 0; + + Inkscape::Util::UnitTable::UnitMap m = unit_table.units(Inkscape::Util::UNIT_TYPE_LINEAR); + Inkscape::Util::UnitTable::UnitMap::iterator iter = m.begin(); + while(iter != m.end()) { + Gtk::RadioMenuItem *mi = Gtk::manage(new Gtk::RadioMenuItem(_sw_group)); + mi->add(*(new Gtk::Label(iter->first, 0.0, 0.5))); + _unit_mis = g_slist_append(_unit_mis, mi); + Inkscape::Util::Unit const *u = unit_table.getUnit(iter->first); + mi->signal_activate().connect(sigc::bind<Inkscape::Util::Unit const *>(sigc::mem_fun(*this, &SelectedStyle::on_popup_units), u)); + _popup_sw.attach(*mi, 0,1, row, row+1); + row++; + ++iter; + } - _popup_sw.attach(*(new Gtk::SeparatorMenuItem()), 0,1, 3,4); + _popup_sw.attach(*(new Gtk::SeparatorMenuItem()), 0,1, row, row+1); + row++; for (guint i = 0; i < G_N_ELEMENTS(_sw_presets_str); ++i) { Gtk::MenuItem *mi = Gtk::manage(new Gtk::MenuItem()); mi->add(*(new Gtk::Label(_sw_presets_str[i], 0.0, 0.5))); mi->signal_activate().connect(sigc::bind<int>(sigc::mem_fun(*this, &SelectedStyle::on_popup_preset), i)); - _popup_sw.attach(*mi, 0,1, 4+i, 5+i); + _popup_sw.attach(*mi, 0,1, row, row+1); + row++; } - guint i = G_N_ELEMENTS(_sw_presets_str) + 5; - - _popup_sw.attach(*(new Gtk::SeparatorMenuItem()), 0,1, i,i+1); + _popup_sw.attach(*(new Gtk::SeparatorMenuItem()), 0,1, row, row+1); + row++; _popup_sw_remove.add(*(new Gtk::Label(_("Remove"), 0.0, 0.5))); _popup_sw_remove.signal_activate().connect(sigc::mem_fun(*this, &SelectedStyle::on_stroke_remove)); - _popup_sw.attach(_popup_sw_remove, 0,1, i+1,i+2); + _popup_sw.attach(_popup_sw_remove, 0,1, row, row+1); + row++; + + sp_set_font_size_smaller (GTK_WIDGET(_popup_sw.gobj())); _popup_sw.show_all(); } @@ -333,9 +350,14 @@ SelectedStyle::SelectedStyle(bool /*layout*/) _stroke_place.signal_button_release_event().connect(sigc::mem_fun(*this, &SelectedStyle::on_stroke_click)); _opacity_place.signal_button_press_event().connect(sigc::mem_fun(*this, &SelectedStyle::on_opacity_click)); _stroke_width_place.signal_button_press_event().connect(sigc::mem_fun(*this, &SelectedStyle::on_sw_click)); + _stroke_width_place.signal_button_release_event().connect(sigc::mem_fun(*this, &SelectedStyle::on_sw_click)); + _opacity_sb.signal_populate_popup().connect(sigc::mem_fun(*this, &SelectedStyle::on_opacity_menu)); _opacity_sb.signal_value_changed().connect(sigc::mem_fun(*this, &SelectedStyle::on_opacity_changed)); + // Connect to key-press to ensure focus is consistent with other spin buttons when using the keys vs mouse-click + g_signal_connect (G_OBJECT (_opacity_sb.gobj()), "key-press-event", G_CALLBACK (spinbutton_keypress), _opacity_sb.gobj()); + g_signal_connect (G_OBJECT (_opacity_sb.gobj()), "focus-in-event", G_CALLBACK (spinbutton_focus_in), _opacity_sb.gobj()); _fill_place.add(_na[SS_FILL]); _fill_place.set_tooltip_text(__na[SS_FILL]); @@ -352,6 +374,16 @@ SelectedStyle::SelectedStyle(bool /*layout*/) _opacity_sb.set_size_request (SELECTED_STYLE_SB_WIDTH, -1); _opacity_sb.set_sensitive (false); +#if WITH_GTKMM_3_0 + _table.attach(_fill_label, 0, 0, 1, 1); + _table.attach(_stroke_label, 0, 1, 1, 1); + + _table.attach(_fill_flag_place, 1, 0, 1, 1); + _table.attach(_stroke_flag_place, 1, 1, 1, 1); + + _table.attach(_fill_place, 2, 0, 1, 1); + _table.attach(_stroke, 2, 1, 1, 1); +#else _table.attach(_fill_label, 0,1, 0,1, Gtk::FILL, Gtk::SHRINK); _table.attach(_stroke_label, 0,1, 1,2, Gtk::FILL, Gtk::SHRINK); @@ -360,10 +392,17 @@ SelectedStyle::SelectedStyle(bool /*layout*/) _table.attach(_fill_place, 2,3, 0,1); _table.attach(_stroke, 2,3, 1,2); +#endif _opacity_place.add(_opacity_label); + +#if WITH_GTKMM_3_0 + _table.attach(_opacity_place, 4, 0, 1, 2); + _table.attach(_opacity_sb, 5, 0, 1, 2); +#else _table.attach(_opacity_place, 4,5, 0,2, Gtk::SHRINK, Gtk::SHRINK); _table.attach(_opacity_sb, 5,6, 0,2, Gtk::SHRINK, Gtk::SHRINK); +#endif pack_start(_table, true, true, 2); @@ -442,7 +481,17 @@ SelectedStyle::setDesktop(SPDesktop *desktop) this ) )); - //_sw_unit = (SPUnit *) sp_desktop_namedview(desktop)->doc_units; + _sw_unit = sp_desktop_namedview(desktop)->doc_units; + + // Set the doc default unit active in the units list + gint length = g_slist_length(_unit_mis); + for (int i = 0; i < length; i++) { + Gtk::RadioMenuItem *mi = (Gtk::RadioMenuItem *) g_slist_nth_data(_unit_mis, i); + if (mi && mi->get_label() == _sw_unit->abbr) { + mi->set_active(); + break; + } + } } void SelectedStyle::dragDataReceived( GtkWidget */*widget*/, @@ -594,6 +643,12 @@ void SelectedStyle::on_fill_invert() { SPCSSAttr *css = sp_repr_css_attr_new (); guint32 color = _thisselected[SS_FILL]; gchar c[64]; + if (_mode[SS_FILL] == SS_LGRADIENT || _mode[SS_FILL] == SS_RGRADIENT) { + sp_gradient_invert_selected_gradients(_desktop, Inkscape::FOR_FILL); + return; + + } + if (_mode[SS_FILL] != SS_COLOR) return; sp_svg_write_color (c, sizeof(c), SP_RGBA32_U_COMPOSE( @@ -614,6 +669,10 @@ void SelectedStyle::on_stroke_invert() { SPCSSAttr *css = sp_repr_css_attr_new (); guint32 color = _thisselected[SS_STROKE]; gchar c[64]; + if (_mode[SS_STROKE] == SS_LGRADIENT || _mode[SS_STROKE] == SS_RGRADIENT) { + sp_gradient_invert_selected_gradients(_desktop, Inkscape::FOR_STROKE); + return; + } if (_mode[SS_STROKE] != SS_COLOR) return; sp_svg_write_color (c, sizeof(c), SP_RGBA32_U_COMPOSE( @@ -872,16 +931,8 @@ SelectedStyle::on_opacity_click(GdkEventButton *event) return false; } -void SelectedStyle::on_popup_px() { - _sw_unit = (SPUnit *) &(sp_unit_get_by_id(SP_UNIT_PX)); - update(); -} -void SelectedStyle::on_popup_pt() { - _sw_unit = (SPUnit *) &(sp_unit_get_by_id(SP_UNIT_PT)); - update(); -} -void SelectedStyle::on_popup_mm() { - _sw_unit = (SPUnit *) &(sp_unit_get_by_id(SP_UNIT_MM)); +void SelectedStyle::on_popup_units(Inkscape::Util::Unit const *unit) { + _sw_unit = unit; update(); } @@ -889,7 +940,7 @@ void SelectedStyle::on_popup_preset(int i) { SPCSSAttr *css = sp_repr_css_attr_new (); gdouble w; if (_sw_unit) { - w = sp_units_get_pixels (_sw_presets[i], *_sw_unit); + w = Inkscape::Util::Quantity::convert(_sw_presets[i], _sw_unit, "px"); } else { w = _sw_presets[i]; } @@ -967,13 +1018,13 @@ SelectedStyle::update() if (SP_IS_LINEARGRADIENT (server)) { SPGradient *vector = SP_GRADIENT(server)->getVector(); - sp_gradient_image_set_gradient ((SPGradientImage *) _gradient_preview_l[i], vector); + sp_gradient_image_set_gradient(SP_GRADIENT_IMAGE(_gradient_preview_l[i]), vector); place->add(_gradient_box_l[i]); place->set_tooltip_text(__lgradient[i]); _mode[i] = SS_LGRADIENT; } else if (SP_IS_RADIALGRADIENT (server)) { SPGradient *vector = SP_GRADIENT(server)->getVector(); - sp_gradient_image_set_gradient ((SPGradientImage *) _gradient_preview_r[i], vector); + sp_gradient_image_set_gradient(SP_GRADIENT_IMAGE(_gradient_preview_r[i]), vector); place->add(_gradient_box_r[i]); place->set_tooltip_text(__rgradient[i]); _mode[i] = SS_RGRADIENT; @@ -989,7 +1040,7 @@ SelectedStyle::update() guint32 color = paint->value.color.toRGBA32( SP_SCALE24_TO_FLOAT ((i == SS_FILL)? query->fill_opacity.value : query->stroke_opacity.value)); _lastselected[i] = _thisselected[i]; - _thisselected[i] = color | 0xff; // only color, opacity === 1 + _thisselected[i] = color; // include opacity ((Inkscape::UI::Widget::ColorPreview*)_color_preview[i])->setRgba32 (color); _color_preview[i]->show_all(); place->add(*_color_preview[i]); @@ -1068,7 +1119,7 @@ SelectedStyle::update() { double w; if (_sw_unit) { - w = sp_pixels_get_units(query->stroke_width.computed, *_sw_unit); + w = Inkscape::Util::Quantity::convert(query->stroke_width.computed, "px", _sw_unit); } else { w = query->stroke_width.computed; } @@ -1082,7 +1133,7 @@ SelectedStyle::update() { gchar *str = g_strdup_printf(_("Stroke width: %.5g%s%s"), w, - _sw_unit? sp_unit_get_abbreviation(_sw_unit) : "px", + _sw_unit? _sw_unit->abbr.c_str() : "px", (result_sw == QUERY_STYLE_MULTIPLE_AVERAGED)? _(" (averaged)") : ""); _stroke_width_place.set_tooltip_text(str); @@ -1192,39 +1243,48 @@ RotateableSwatch::~RotateableSwatch() { } double -RotateableSwatch::color_adjust(float *hsl, double by, guint32 cc, guint modifier) +RotateableSwatch::color_adjust(float *hsla, double by, guint32 cc, guint modifier) { - sp_color_rgb_to_hsl_floatv (hsl, SP_RGBA32_R_F(cc), SP_RGBA32_G_F(cc), SP_RGBA32_B_F(cc)); - + sp_color_rgb_to_hsl_floatv (hsla, SP_RGBA32_R_F(cc), SP_RGBA32_G_F(cc), SP_RGBA32_B_F(cc)); + hsla[3] = SP_RGBA32_A_F(cc); double diff = 0; if (modifier == 2) { // saturation - double old = hsl[1]; + double old = hsla[1]; if (by > 0) { - hsl[1] += by * (1 - hsl[1]); + hsla[1] += by * (1 - hsla[1]); } else { - hsl[1] += by * (hsl[1]); + hsla[1] += by * (hsla[1]); } - diff = hsl[1] - old; + diff = hsla[1] - old; } else if (modifier == 1) { // lightness - double old = hsl[2]; + double old = hsla[2]; if (by > 0) { - hsl[2] += by * (1 - hsl[2]); + hsla[2] += by * (1 - hsla[2]); } else { - hsl[2] += by * (hsl[2]); + hsla[2] += by * (hsla[2]); } - diff = hsl[2] - old; + diff = hsla[2] - old; + } else if (modifier == 3) { // alpha + double old = hsla[3]; + hsla[3] += by/2; + if (hsla[3] < 0) { + hsla[3] = 0; + } else if (hsla[3] > 1) { + hsla[3] = 1; + } + diff = hsla[3] - old; } else { // hue - double old = hsl[0]; - hsl[0] += by/2; - while (hsl[0] < 0) - hsl[0] += 1; - while (hsl[0] > 1) - hsl[0] -= 1; - diff = hsl[0] - old; + double old = hsla[0]; + hsla[0] += by/2; + while (hsla[0] < 0) + hsla[0] += 1; + while (hsla[0] > 1) + hsla[0] -= 1; + diff = hsla[0] - old; } float rgb[3]; - sp_color_hsl_to_rgb_floatv (rgb, hsl[0], hsl[1], hsl[2]); + sp_color_hsl_to_rgb_floatv (rgb, hsla[0], hsla[1], hsla[2]); gchar c[64]; sp_svg_write_color (c, sizeof(c), @@ -1237,10 +1297,14 @@ RotateableSwatch::color_adjust(float *hsl, double by, guint32 cc, guint modifier ); SPCSSAttr *css = sp_repr_css_attr_new (); - if (fillstroke == SS_FILL) - sp_repr_css_set_property (css, "fill", c); - else - sp_repr_css_set_property (css, "stroke", c); + + if (modifier == 3) { // alpha + Inkscape::CSSOStringStream osalpha; + osalpha << hsla[3]; + sp_repr_css_set_property(css, (fillstroke == SS_FILL) ? "fill-opacity" : "stroke-opacity", osalpha.str().c_str()); + } else { + sp_repr_css_set_property (css, (fillstroke == SS_FILL) ? "fill" : "stroke", c); + } sp_desktop_set_style (parent->getDesktop(), css); sp_repr_css_attr_unref (css); return diff; @@ -1251,32 +1315,31 @@ RotateableSwatch::do_motion(double by, guint modifier) { if (parent->_mode[fillstroke] != SS_COLOR) return; - if (!cr_set && modifier != 3) { + if (!scrolling && !cr_set) { GtkWidget *w = GTK_WIDGET(gobj()); + GdkPixbuf *pixbuf = NULL; - GdkBitmap *bitmap = NULL; - GdkBitmap *mask = NULL; if (modifier == 2) { // saturation - sp_cursor_bitmap_and_mask_from_xpm(&bitmap, &mask, cursor_adj_s_xpm); + pixbuf = gdk_pixbuf_new_from_xpm_data((const gchar **)cursor_adj_s_xpm); } else if (modifier == 1) { // lightness - sp_cursor_bitmap_and_mask_from_xpm(&bitmap, &mask, cursor_adj_l_xpm); + pixbuf = gdk_pixbuf_new_from_xpm_data((const gchar **)cursor_adj_l_xpm); + } else if (modifier == 3) { // alpha + pixbuf = gdk_pixbuf_new_from_xpm_data((const gchar **)cursor_adj_a_xpm); } else { // hue - sp_cursor_bitmap_and_mask_from_xpm(&bitmap, &mask, cursor_adj_h_xpm); + pixbuf = gdk_pixbuf_new_from_xpm_data((const gchar **)cursor_adj_h_xpm); } - if ((bitmap != NULL) && (mask != NULL)) { - GtkStyle *style = gtk_widget_get_style(w); - cr = gdk_cursor_new_from_pixmap(bitmap, mask, - &style->black, - &style->white, - 16, 16); - g_object_unref (bitmap); - g_object_unref (mask); + + if (pixbuf != NULL) { + cr = gdk_cursor_new_from_pixbuf(gdk_display_get_default(), pixbuf, 16, 16); + + g_object_unref(pixbuf); gdk_window_set_cursor(gtk_widget_get_window(w), cr); #if GTK_CHECK_VERSION(3,0,0) g_object_unref(cr); #else gdk_cursor_unref(cr); #endif + cr = NULL; cr_set = true; } } @@ -1289,43 +1352,51 @@ RotateableSwatch::do_motion(double by, guint modifier) { cc = startcolor; } - float hsl[3]; + float hsla[4]; double diff = 0; - if (modifier != 3) { - diff = color_adjust(hsl, by, cc, modifier); - } - if (modifier == 3) { // Alt, do nothing + diff = color_adjust(hsla, by, cc, modifier); + + if (modifier == 3) { // alpha + DocumentUndo::maybeDone(sp_desktop_document(parent->getDesktop()), undokey, + SP_VERB_DIALOG_FILL_STROKE, (_("Adjust alpha"))); + double ch = hsla[3]; + parent->getDesktop()->event_context->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("Adjusting <b>alpha</b>: was %.3g, now <b>%.3g</b> (diff %.3g); with <b>Ctrl</b> to adjust lightness, with <b>Shift</b> to adjust saturation, without modifiers to adjust hue"), ch - diff, ch, diff); } else if (modifier == 2) { // saturation DocumentUndo::maybeDone(sp_desktop_document(parent->getDesktop()), undokey, SP_VERB_DIALOG_FILL_STROKE, (_("Adjust saturation"))); - double ch = hsl[1]; - parent->getDesktop()->event_context->_message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("Adjusting <b>saturation</b>: was %.3g, now <b>%.3g</b> (diff %.3g); with <b>Ctrl</b> to adjust lightness, without modifiers to adjust hue"), ch - diff, ch, diff); + double ch = hsla[1]; + parent->getDesktop()->event_context->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("Adjusting <b>saturation</b>: was %.3g, now <b>%.3g</b> (diff %.3g); with <b>Ctrl</b> to adjust lightness, with <b>Alt</b> to adjust alpha, without modifiers to adjust hue"), ch - diff, ch, diff); } else if (modifier == 1) { // lightness DocumentUndo::maybeDone(sp_desktop_document(parent->getDesktop()), undokey, SP_VERB_DIALOG_FILL_STROKE, (_("Adjust lightness"))); - double ch = hsl[2]; - parent->getDesktop()->event_context->_message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("Adjusting <b>lightness</b>: was %.3g, now <b>%.3g</b> (diff %.3g); with <b>Shift</b> to adjust saturation, without modifiers to adjust hue"), ch - diff, ch, diff); + double ch = hsla[2]; + parent->getDesktop()->event_context->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("Adjusting <b>lightness</b>: was %.3g, now <b>%.3g</b> (diff %.3g); with <b>Shift</b> to adjust saturation, with <b>Alt</b> to adjust alpha, without modifiers to adjust hue"), ch - diff, ch, diff); } else { // hue DocumentUndo::maybeDone(sp_desktop_document(parent->getDesktop()), undokey, SP_VERB_DIALOG_FILL_STROKE, (_("Adjust hue"))); - double ch = hsl[0]; - parent->getDesktop()->event_context->_message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("Adjusting <b>hue</b>: was %.3g, now <b>%.3g</b> (diff %.3g); with <b>Shift</b> to adjust saturation, with <b>Ctrl</b> to adjust lightness"), ch - diff, ch, diff); + double ch = hsla[0]; + parent->getDesktop()->event_context->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("Adjusting <b>hue</b>: was %.3g, now <b>%.3g</b> (diff %.3g); with <b>Shift</b> to adjust saturation, with <b>Alt</b> to adjust alpha, with <b>Ctrl</b> to adjust lightness"), ch - diff, ch, diff); } } + +void +RotateableSwatch::do_scroll(double by, guint modifier) { + do_motion(by/30.0, modifier); + do_release(by/30.0, modifier); +} + void RotateableSwatch::do_release(double by, guint modifier) { if (parent->_mode[fillstroke] != SS_COLOR) return; - float hsl[3]; - if (modifier != 3) { - color_adjust(hsl, by, startcolor, modifier); - } + float hsla[4]; + color_adjust(hsla, by, startcolor, modifier); if (cr_set) { GtkWidget *w = GTK_WIDGET(gobj()); @@ -1341,7 +1412,9 @@ RotateableSwatch::do_release(double by, guint modifier) { cr_set = false; } - if (modifier == 3) { // Alt, do nothing + if (modifier == 3) { // alpha + DocumentUndo::maybeDone(sp_desktop_document(parent->getDesktop()), undokey, + SP_VERB_DIALOG_FILL_STROKE, ("Adjust alpha")); } else if (modifier == 2) { // saturation DocumentUndo::maybeDone(sp_desktop_document(parent->getDesktop()), undokey, SP_VERB_DIALOG_FILL_STROKE, ("Adjust saturation")); @@ -1361,7 +1434,7 @@ RotateableSwatch::do_release(double by, guint modifier) { undokey = "ssrot1"; } - parent->getDesktop()->event_context->_message_context->clear(); + parent->getDesktop()->event_context->message_context->clear(); startcolor_set = false; } @@ -1371,9 +1444,7 @@ RotateableStrokeWidth::RotateableStrokeWidth(SelectedStyle *parent) : parent(parent), startvalue(0), startvalue_set(false), - undokey("swrot1"), - cr(0), - cr_set(false) + undokey("swrot1") { } @@ -1427,7 +1498,7 @@ RotateableStrokeWidth::do_motion(double by, guint modifier) { double diff = value_adjust(startvalue, by, modifier, false); DocumentUndo::maybeDone(sp_desktop_document(parent->getDesktop()), undokey, SP_VERB_DIALOG_FILL_STROKE, (_("Adjust stroke width"))); - parent->getDesktop()->event_context->_message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("Adjusting <b>stroke width</b>: was %.3g, now <b>%.3g</b> (diff %.3g)"), startvalue, startvalue + diff, diff); + parent->getDesktop()->event_context->message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("Adjusting <b>stroke width</b>: was %.3g, now <b>%.3g</b> (diff %.3g)"), startvalue, startvalue + diff, diff); } } @@ -1448,9 +1519,14 @@ RotateableStrokeWidth::do_release(double by, guint modifier) { } else { undokey = "swrot1"; } - parent->getDesktop()->event_context->_message_context->clear(); + parent->getDesktop()->event_context->message_context->clear(); } +void +RotateableStrokeWidth::do_scroll(double by, guint modifier) { + do_motion(by/10.0, modifier); + startvalue_set = false; +} Dialog::FillAndStroke *get_fill_and_stroke_panel(SPDesktop *desktop) { diff --git a/src/ui/widget/selected-style.h b/src/ui/widget/selected-style.h index 542983b53..9557a8d74 100644 --- a/src/ui/widget/selected-style.h +++ b/src/ui/widget/selected-style.h @@ -11,8 +11,22 @@ #ifndef INKSCAPE_UI_CURRENT_STYLE_H #define INKSCAPE_UI_CURRENT_STYLE_H +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> -#include <gtkmm/table.h> + +#if WITH_GTKMM_3_0 +# include <gtkmm/grid.h> +#else +# include <gtkmm/table.h> +#endif + #include <gtkmm/label.h> #include <gtkmm/eventbox.h> #include <gtkmm/enums.h> @@ -29,9 +43,13 @@ #include "rotateable.h" class SPDesktop; -class SPUnit; namespace Inkscape { + +namespace Util { + class Unit; +} + namespace UI { namespace Widget { @@ -60,8 +78,10 @@ public: ~RotateableSwatch(); double color_adjust (float *hsl, double by, guint32 cc, guint state); + virtual void do_motion (double by, guint state); virtual void do_release (double by, guint state); + virtual void do_scroll (double by, guint state); private: guint fillstroke; @@ -86,6 +106,7 @@ public: double value_adjust(double current, double by, guint modifier, bool final); virtual void do_motion (double by, guint state); virtual void do_release (double by, guint state); + virtual void do_scroll (double by, guint state); private: SelectedStyle *parent; @@ -94,9 +115,6 @@ private: bool startvalue_set; gchar const *undokey; - - GdkCursor *cr; - bool cr_set; }; /** @@ -123,7 +141,11 @@ public: protected: SPDesktop *_desktop; +#if WITH_GTKMM_3_0 + Gtk::Grid _table; +#else Gtk::Table _table; +#endif Gtk::Label _fill_label; Gtk::Label _stroke_label; @@ -250,16 +272,12 @@ protected: Gtk::Menu _popup_sw; Gtk::RadioButtonGroup _sw_group; - Gtk::RadioMenuItem _popup_px; - void on_popup_px(); - Gtk::RadioMenuItem _popup_pt; - void on_popup_pt(); - Gtk::RadioMenuItem _popup_mm; - void on_popup_mm(); + GSList *_unit_mis; + void on_popup_units(Inkscape::Util::Unit const *u); void on_popup_preset(int i); Gtk::MenuItem _popup_sw_remove; - SPUnit *_sw_unit; + Inkscape::Util::Unit const *_sw_unit; /// points to object in UnitTable, do not delete void *_drop[2]; bool _dropEnabled[2]; diff --git a/src/ui/widget/spin-scale.cpp b/src/ui/widget/spin-scale.cpp new file mode 100644 index 000000000..ade3d1e60 --- /dev/null +++ b/src/ui/widget/spin-scale.cpp @@ -0,0 +1,247 @@ +/* + * Author: + * + * Copyright (C) 2012 Author + * + * Released under GNU GPL. Read the file 'COPYING' for more information. + */ + +#include "spin-scale.h" + +#include <gtkmm/adjustment.h> +#include <glibmm/i18n.h> +#include <glibmm/stringutils.h> + +#include "ui/widget/gimpspinscale.h" + +namespace Inkscape { +namespace UI { +namespace Widget { + +SpinScale::SpinScale(const char* label, double value, double lower, double upper, double step_inc, + double /*climb_rate*/, int digits, const SPAttributeEnum a, const char* tip_text) + : AttrWidget(a, value) +{ +#if WITH_GTKMM_3_0 + _adjustment = Gtk::Adjustment::create(value, lower, upper, step_inc); + _spinscale = gimp_spin_scale_new (_adjustment->gobj(), label, digits); +#else + _adjustment = new Gtk::Adjustment(value, lower, upper, step_inc); + _spinscale = gimp_spin_scale_new (_adjustment->gobj(), label, digits); +#endif + + signal_value_changed().connect(signal_attr_changed().make_slot()); + + pack_start(*Gtk::manage(Glib::wrap(_spinscale))); + + if (tip_text){ + gtk_widget_set_tooltip_text( _spinscale, tip_text ); + } + + show_all_children(); +} + +SpinScale::SpinScale(const char* label, +#if WITH_GTKMM_3_0 + Glib::RefPtr<Gtk::Adjustment> adj, +#else + Gtk::Adjustment *adj, +#endif + int digits, const SPAttributeEnum a, const char* tip_text) + : AttrWidget(a, 0.0), + _adjustment(adj) + +{ + + _spinscale = gimp_spin_scale_new (_adjustment->gobj(), label, digits); + + signal_value_changed().connect(signal_attr_changed().make_slot()); + + pack_start(*Gtk::manage(Glib::wrap(_spinscale))); + + if (tip_text){ + gtk_widget_set_tooltip_text( _spinscale, tip_text ); + } + + show_all_children(); +} + +Glib::ustring SpinScale::get_as_attribute() const +{ + const double val = _adjustment->get_value(); + + //if(_spin.get_digits() == 0) + // return Glib::Ascii::dtostr((int)val); + //else + return Glib::Ascii::dtostr(val); +} + +void SpinScale::set_from_attribute(SPObject* o) +{ + const gchar* val = attribute_value(o); + if(val) + _adjustment->set_value(Glib::Ascii::strtod(val)); + else + _adjustment->set_value(get_default()->as_double()); +} + +Glib::SignalProxy0<void> SpinScale::signal_value_changed() +{ + return _adjustment->signal_value_changed(); +} + +double SpinScale::get_value() const +{ + return _adjustment->get_value(); +} + +void SpinScale::set_value(const double val) +{ + _adjustment->set_value(val); +} + +void SpinScale::set_focuswidget(GtkWidget *widget) +{ + gimp_spin_scale_set_focuswidget(_spinscale, widget); +} + + +void SpinScale::set_appearance(const gchar* appearance) +{ + gimp_spin_scale_set_appearance(_spinscale, appearance); +} + +#if WITH_GTKMM_3_0 +const Glib::RefPtr<Gtk::Adjustment> SpinScale::get_adjustment() const +#else +const Gtk::Adjustment *SpinScale::get_adjustment() const +#endif +{ + return _adjustment; +} +#if WITH_GTKMM_3_0 +Glib::RefPtr<Gtk::Adjustment> SpinScale::get_adjustment() +#else +Gtk::Adjustment *SpinScale::get_adjustment() +#endif +{ + return _adjustment; +} + + +DualSpinScale::DualSpinScale(const char* label1, const char* label2, double value, double lower, double upper, double step_inc, + double climb_rate, int digits, const SPAttributeEnum a, char* tip_text1, char* tip_text2) + : AttrWidget(a), + _s1(label1, value, lower, upper, step_inc, climb_rate, digits, SP_ATTR_INVALID, tip_text1), + _s2(label2, value, lower, upper, step_inc, climb_rate, digits, SP_ATTR_INVALID, tip_text2), + //TRANSLATORS: "Link" means to _link_ two sliders together + _link(C_("Sliders", "Link")) +{ + signal_value_changed().connect(signal_attr_changed().make_slot()); + + _s1.get_adjustment()->signal_value_changed().connect(_signal_value_changed.make_slot()); + _s2.get_adjustment()->signal_value_changed().connect(_signal_value_changed.make_slot()); + _s1.get_adjustment()->signal_value_changed().connect(sigc::mem_fun(*this, &DualSpinScale::update_linked)); + + _link.signal_toggled().connect(sigc::mem_fun(*this, &DualSpinScale::link_toggled)); + + Gtk::VBox* vb = Gtk::manage(new Gtk::VBox); + vb->add(_s1); + vb->add(_s2); + pack_start(*vb); + pack_start(_link, false, false); + _link.set_active(true); + + show_all(); +} + +Glib::ustring DualSpinScale::get_as_attribute() const +{ + if(_link.get_active()) + return _s1.get_as_attribute(); + else + return _s1.get_as_attribute() + " " + _s2.get_as_attribute(); +} + +void DualSpinScale::set_from_attribute(SPObject* o) +{ + const gchar* val = attribute_value(o); + if(val) { + // Split val into parts + gchar** toks = g_strsplit(val, " ", 2); + + if(toks) { + double v1 = 0.0, v2 = 0.0; + if(toks[0]) + v1 = v2 = Glib::Ascii::strtod(toks[0]); + if(toks[1]) + v2 = Glib::Ascii::strtod(toks[1]); + + _link.set_active(toks[1] == 0); + + _s1.get_adjustment()->set_value(v1); + _s2.get_adjustment()->set_value(v2); + + g_strfreev(toks); + } + } +} + +sigc::signal<void>& DualSpinScale::signal_value_changed() +{ + return _signal_value_changed; +} + +const SpinScale& DualSpinScale::get_SpinScale1() const +{ + return _s1; +} + +SpinScale& DualSpinScale::get_SpinScale1() +{ + return _s1; +} + +const SpinScale& DualSpinScale::get_SpinScale2() const +{ + return _s2; +} + +SpinScale& DualSpinScale::get_SpinScale2() +{ + return _s2; +} + +/*void DualSpinScale::remove_scale() +{ + _s1.remove_scale(); + _s2.remove_scale(); +}*/ + +void DualSpinScale::link_toggled() +{ + _s2.set_sensitive(!_link.get_active()); + update_linked(); +} + +void DualSpinScale::update_linked() +{ + if(_link.get_active()) + _s2.set_value(_s1.get_value()); +} + + +} // namespace Widget +} // namespace UI +} // namespace Inkscape + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=c++:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/widget/spin-scale.h b/src/ui/widget/spin-scale.h new file mode 100644 index 000000000..5fec8b1d8 --- /dev/null +++ b/src/ui/widget/spin-scale.h @@ -0,0 +1,125 @@ +/* + * Author: + * + * Copyright (C) 2012 Author + * + * Released under GNU GPL. Read the file 'COPYING' for more information. + */ + +#ifndef INKSCAPE_UI_WIDGET_SPIN_SCALE_H +#define INKSCAPE_UI_WIDGET_SPIN_SCALE_H + +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + +#include <gtkmm/adjustment.h> +#include <gtkmm/box.h> +#include <gtkmm/scale.h> +#include <gtkmm/togglebutton.h> +#include "spinbutton.h" +#include "attr-widget.h" + +namespace Inkscape { +namespace UI { +namespace Widget { + +/** + * Wrap the gimpspinscale class + * A combo widget with label, scale slider, spinbutton and adjustment + */ +class SpinScale : public Gtk::HBox, public AttrWidget +{ + +public: + SpinScale(const char* label, double value, double lower, double upper, double step_inc, double climb_rate, + int digits, const SPAttributeEnum a = SP_ATTR_INVALID, const char* tip_text = NULL); + + SpinScale(const char* label, +#if WITH_GTKMM_3_0 + Glib::RefPtr<Gtk::Adjustment> adj, +#else + Gtk::Adjustment *adj, +#endif + int digits, const SPAttributeEnum a = SP_ATTR_INVALID, const char* tip_text = NULL); + + virtual Glib::ustring get_as_attribute() const; + virtual void set_from_attribute(SPObject*); + + // Shortcuts to _adjustment + Glib::SignalProxy0<void> signal_value_changed(); + double get_value() const; + void set_value(const double); + void set_focuswidget(GtkWidget *widget); + void set_appearance(const gchar* appearance); + +#if WITH_GTKMM_3_0 + const Glib::RefPtr<Gtk::Adjustment> get_adjustment() const; + Glib::RefPtr<Gtk::Adjustment> get_adjustment(); +#else + const Gtk::Adjustment *get_adjustment() const; + Gtk::Adjustment *get_adjustment(); +#endif + +private: +#if WITH_GTKMM_3_0 + Glib::RefPtr<Gtk::Adjustment> _adjustment; +#else + Gtk::Adjustment *_adjustment; +#endif + + GtkWidget *_spinscale; +}; + + +/** + * Contains two SpinScales for controlling number-opt-number attributes. + * + * @see SpinScale + */ +class DualSpinScale : public Gtk::HBox, public AttrWidget +{ +public: + DualSpinScale(const char* label1, const char* label2, double value, double lower, double upper, double step_inc, + double climb_rate, int digits, const SPAttributeEnum, char* tip_text1, char* tip_text2); + + virtual Glib::ustring get_as_attribute() const; + virtual void set_from_attribute(SPObject*); + + sigc::signal<void>& signal_value_changed(); + + const SpinScale& get_SpinScale1() const; + SpinScale& get_SpinScale1(); + + const SpinScale& get_SpinScale2() const; + SpinScale& get_SpinScale2(); + + //void remove_scale(); +private: + void link_toggled(); + void update_linked(); + sigc::signal<void> _signal_value_changed; + SpinScale _s1, _s2; + Gtk::ToggleButton _link; +}; + +} // namespace Widget +} // namespace UI +} // namespace Inkscape + +#endif // INKSCAPE_UI_WIDGET_SPIN_SCALE_H + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=c++:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/widget/spin-slider.cpp b/src/ui/widget/spin-slider.cpp index 97ae18e20..1cb59a7b3 100644 --- a/src/ui/widget/spin-slider.cpp +++ b/src/ui/widget/spin-slider.cpp @@ -8,12 +8,11 @@ * Released under GNU GPL. Read the file 'COPYING' for more information. */ -#include <glib.h> +#include "spin-slider.h" + #include <glibmm/i18n.h> #include <glibmm/stringutils.h> -#include "spin-slider.h" - namespace Inkscape { namespace UI { namespace Widget { @@ -116,11 +115,20 @@ Gtk::Adjustment& SpinSlider::get_adjustment() return _adjustment; } +#if WITH_GTKMM_3_0 +const Gtk::Scale& SpinSlider::get_scale() const +#else const Gtk::HScale& SpinSlider::get_scale() const +#endif { return _scale; } + +#if WITH_GTKMM_3_0 +Gtk::Scale& SpinSlider::get_scale() +#else Gtk::HScale& SpinSlider::get_scale() +#endif { return _scale; } @@ -186,7 +194,7 @@ void DualSpinSlider::set_from_attribute(SPObject* o) gchar** toks = g_strsplit(val, " ", 2); if(toks) { - double v1, v2; + double v1 = 0.0, v2 = 0.0; if(toks[0]) v1 = v2 = Glib::Ascii::strtod(toks[0]); if(toks[1]) diff --git a/src/ui/widget/spin-slider.h b/src/ui/widget/spin-slider.h index f4a62107b..5f86fd15a 100644 --- a/src/ui/widget/spin-slider.h +++ b/src/ui/widget/spin-slider.h @@ -10,6 +10,14 @@ #ifndef INKSCAPE_UI_WIDGET_SPIN_SLIDER_H #define INKSCAPE_UI_WIDGET_SPIN_SLIDER_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/adjustment.h> #include <gtkmm/box.h> #include <gtkmm/scale.h> @@ -41,13 +49,14 @@ public: #if WITH_GTKMM_3_0 const Glib::RefPtr<Gtk::Adjustment> get_adjustment() const; Glib::RefPtr<Gtk::Adjustment> get_adjustment(); + const Gtk::Scale& get_scale() const; + Gtk::Scale& get_scale(); #else const Gtk::Adjustment& get_adjustment() const; Gtk::Adjustment& get_adjustment(); -#endif - const Gtk::HScale& get_scale() const; Gtk::HScale& get_scale(); +#endif const Inkscape::UI::Widget::SpinButton& get_spin_button() const; Inkscape::UI::Widget::SpinButton& get_spin_button(); @@ -57,10 +66,11 @@ public: private: #if WITH_GTKMM_3_0 Glib::RefPtr<Gtk::Adjustment> _adjustment; + Gtk::Scale _scale; #else Gtk::Adjustment _adjustment; -#endif Gtk::HScale _scale; +#endif Inkscape::UI::Widget::SpinButton _spin; }; diff --git a/src/ui/widget/spinbutton.cpp b/src/ui/widget/spinbutton.cpp index 7d6479923..7709a837b 100644 --- a/src/ui/widget/spinbutton.cpp +++ b/src/ui/widget/spinbutton.cpp @@ -14,12 +14,9 @@ #include "spinbutton.h" #include "unit-menu.h" +#include "unit-tracker.h" #include "util/expression-evaluator.h" -#include "event-context.h" - -#if !GTK_CHECK_VERSION(2,22,0) -#include "compat-key-syms.h" -#endif +#include "ui/tools/tool-base.h" namespace Inkscape { namespace UI { @@ -36,16 +33,23 @@ SpinButton::connect_signals() { int SpinButton::on_input(double* newvalue) { try { - Inkscape::Util::GimpEevlQuantity result; - if (_unit_menu) { - Unit unit = _unit_menu->getUnit(); - result = Inkscape::Util::gimp_eevl_evaluate (get_text().c_str(), &unit); + Inkscape::Util::EvaluatorQuantity result; + if (_unit_menu || _unit_tracker) { + Unit const *unit = NULL; + if (_unit_menu) { + unit = _unit_menu->getUnit(); + } else { + unit = _unit_tracker->getActiveUnit(); + } + Inkscape::Util::ExpressionEvaluator eval = Inkscape::Util::ExpressionEvaluator(get_text().c_str(), unit); + result = eval.evaluate(); // check if output dimension corresponds to input unit - if (result.dimension != (unit.isAbsolute() ? 1 : 0) ) { + if (result.dimension != (unit->isAbsolute() ? 1 : 0) ) { throw Inkscape::Util::EvaluatorException("Input dimensions do not match with parameter dimensions.",""); } } else { - result = Inkscape::Util::gimp_eevl_evaluate (get_text().c_str(), NULL); + Inkscape::Util::ExpressionEvaluator eval = Inkscape::Util::ExpressionEvaluator(get_text().c_str(), NULL); + result = eval.evaluate(); } *newvalue = result.value; @@ -61,13 +65,13 @@ int SpinButton::on_input(double* newvalue) bool SpinButton::on_my_focus_in_event(GdkEventFocus* /*event*/) { - on_focus_in_value = get_value(); + _on_focus_in_value = get_value(); return false; // do not consume the event } bool SpinButton::on_my_key_press_event(GdkEventKey* event) { - switch (get_group0_keyval (event)) { + switch (Inkscape::UI::Tools::get_group0_keyval (event)) { case GDK_KEY_Escape: undo(); return true; // I consumed the event @@ -88,7 +92,7 @@ bool SpinButton::on_my_key_press_event(GdkEventKey* event) void SpinButton::undo() { - set_value(on_focus_in_value); + set_value(_on_focus_in_value); } diff --git a/src/ui/widget/spinbutton.h b/src/ui/widget/spinbutton.h index 57c48369e..812b5f515 100644 --- a/src/ui/widget/spinbutton.h +++ b/src/ui/widget/spinbutton.h @@ -10,6 +10,14 @@ #ifndef INKSCAPE_UI_WIDGET_SPINBUTTON_H #define INKSCAPE_UI_WIDGET_SPINBUTTON_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/spinbutton.h> namespace Inkscape { @@ -17,6 +25,7 @@ namespace UI { namespace Widget { class UnitMenu; +class UnitTracker; /** * SpinButton widget, that allows entry of simple math expressions (also units, when linked with UnitMenu), @@ -29,7 +38,9 @@ class SpinButton : public Gtk::SpinButton public: SpinButton(double climb_rate = 0.0, guint digits = 0) : Gtk::SpinButton(climb_rate, digits), - _unit_menu(NULL) + _unit_menu(NULL), + _unit_tracker(NULL), + _on_focus_in_value(0.) { connect_signals(); }; @@ -39,7 +50,9 @@ public: explicit SpinButton(Gtk::Adjustment& adjustment, double climb_rate = 0.0, guint digits = 0) #endif : Gtk::SpinButton(adjustment, climb_rate, digits), - _unit_menu(NULL) + _unit_menu(NULL), + _unit_tracker(NULL), + _on_focus_in_value(0.) { connect_signals(); }; @@ -47,9 +60,13 @@ public: virtual ~SpinButton() {}; void setUnitMenu(UnitMenu* unit_menu) { _unit_menu = unit_menu; }; + + void addUnitTracker(UnitTracker* ut) { _unit_tracker = ut; }; protected: UnitMenu *_unit_menu; /// Linked unit menu for unit conversion in entered expressions. + UnitTracker *_unit_tracker; // Linked unit tracker for unit conversion in entered expressions. + double _on_focus_in_value; void connect_signals(); @@ -82,8 +99,6 @@ protected: */ void undo(); - double on_focus_in_value; - private: // noncopyable SpinButton(const SpinButton&); diff --git a/src/ui/widget/style-subject.h b/src/ui/widget/style-subject.h index 47da91732..c2941d995 100644 --- a/src/ui/widget/style-subject.h +++ b/src/ui/widget/style-subject.h @@ -20,7 +20,7 @@ class SPDesktop; class SPObject; class SPCSSAttr; -class SPStyle; +struct SPStyle; namespace Inkscape { class Selection; diff --git a/src/ui/widget/style-swatch.cpp b/src/ui/widget/style-swatch.cpp index 1ee26e803..a33c1d09f 100644 --- a/src/ui/widget/style-swatch.cpp +++ b/src/ui/widget/style-swatch.cpp @@ -11,31 +11,35 @@ * Released under GNU GPL. Read the file 'COPYING' for more information. */ -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif +#include "style-swatch.h" #include <cstring> #include <string> -#include "style-swatch.h" - #include "widgets/spw-utilities.h" #include "ui/widget/color-preview.h" #include "style.h" -#include "sp-linear-gradient-fns.h" -#include "sp-radial-gradient-fns.h" +#include "sp-linear-gradient.h" +#include "sp-radial-gradient.h" #include "sp-pattern.h" #include "xml/repr.h" +#include "xml/sp-css-attr.h" #include "widgets/widget-sizes.h" -#include "helper/units.h" +#include "util/units.h" #include "helper/action.h" +#include "helper/action-context.h" #include "preferences.h" #include "inkscape.h" #include "verbs.h" #include <glibmm/i18n.h> +#if WITH_GTKMM_3_0 +# include <gtkmm/grid.h> +#else +# include <gtkmm/table.h> +#endif + enum { SS_FILL, SS_STROKE @@ -113,7 +117,11 @@ StyleSwatch::StyleSwatch(SPCSSAttr *css, gchar const *main_tip) _css(NULL), _tool_obs(NULL), _style_obs(NULL), - _table(2, 6), +#if WITH_GTKMM_3_0 + _table(Gtk::manage(new Gtk::Grid())), +#else + _table(Gtk::manage(new Gtk::Table(2, 6))), +#endif _sw_unit(NULL) { _label[SS_FILL].set_markup(_("Fill:")); @@ -129,23 +137,35 @@ StyleSwatch::StyleSwatch(SPCSSAttr *css, gchar const *main_tip) _opacity_value.set_alignment(0.0, 0.5); _opacity_value.set_padding(0, 0); - _table.set_col_spacings (2); - _table.set_row_spacings (0); +#if WITH_GTKMM_3_0 + _table->set_column_spacing(2); + _table->set_row_spacing(0); +#else + _table->set_col_spacings(2); + _table->set_row_spacings(0); +#endif _stroke.pack_start(_place[SS_STROKE]); _stroke_width_place.add(_stroke_width); _stroke.pack_start(_stroke_width_place, Gtk::PACK_SHRINK); - - _table.attach(_label[SS_FILL], 0,1, 0,1, Gtk::FILL, Gtk::SHRINK); - _table.attach(_label[SS_STROKE], 0,1, 1,2, Gtk::FILL, Gtk::SHRINK); - - _table.attach(_place[SS_FILL], 1,2, 0,1); - _table.attach(_stroke, 1,2, 1,2); - + _opacity_place.add(_opacity_value); - _table.attach(_opacity_place, 2,3, 0,2, Gtk::SHRINK, Gtk::SHRINK); - _swatch.add(_table); +#if WITH_GTKMM_3_0 + _table->attach(_label[SS_FILL], 0, 0, 1, 1); + _table->attach(_label[SS_STROKE], 0, 1, 1, 1); + _table->attach(_place[SS_FILL], 1, 0, 1, 1); + _table->attach(_stroke, 1, 1, 1, 1); + _table->attach(_opacity_place, 2, 0, 1, 2); +#else + _table->attach(_label[SS_FILL], 0,1, 0,1, Gtk::FILL, Gtk::SHRINK); + _table->attach(_label[SS_STROKE], 0,1, 1,2, Gtk::FILL, Gtk::SHRINK); + _table->attach(_place[SS_FILL], 1,2, 0,1); + _table->attach(_stroke, 1,2, 1,2); + _table->attach(_opacity_place, 2,3, 0,2, Gtk::SHRINK, Gtk::SHRINK); +#endif + + _swatch.add(*_table); pack_start(_swatch, true, true, 0); set_size_request (STYLE_SWATCH_WIDTH, -1); @@ -181,7 +201,7 @@ StyleSwatch::on_click(GdkEventButton */*event*/) { if (this->_desktop && this->_verb_t != SP_VERB_NONE) { Inkscape::Verb *verb = Inkscape::Verb::get(this->_verb_t); - SPAction *action = verb->get_action((Inkscape::UI::View::View *) this->_desktop); + SPAction *action = verb->get_action(Inkscape::ActionContext((Inkscape::UI::View::View *) this->_desktop)); sp_action_perform (action, NULL); return true; } @@ -227,8 +247,7 @@ StyleSwatch::setWatchedTool(const char *path, bool synthesize) } -void -StyleSwatch::setStyle(SPCSSAttr *css) +void StyleSwatch::setStyle(SPCSSAttr *css) { if (_css) sp_repr_css_attr_unref (_css); @@ -239,18 +258,18 @@ StyleSwatch::setStyle(SPCSSAttr *css) _css = sp_repr_css_attr_new(); sp_repr_css_merge(_css, css); - gchar const *css_string = sp_repr_css_write_string (_css); + Glib::ustring css_string; + sp_repr_css_write_string (_css, css_string); SPStyle *temp_spstyle = sp_style_new(SP_ACTIVE_DOCUMENT); - if (css_string) - sp_style_merge_from_style_string (temp_spstyle, css_string); - + if (~css_string.empty()) { + sp_style_merge_from_style_string (temp_spstyle, css_string.c_str()); + } + setStyle (temp_spstyle); - sp_style_unref (temp_spstyle); } -void -StyleSwatch::setStyle(SPStyle *query) +void StyleSwatch::setStyle(SPStyle *query) { _place[SS_FILL].remove(); _place[SS_STROKE].remove(); @@ -314,7 +333,7 @@ StyleSwatch::setStyle(SPStyle *query) if (has_stroke) { double w; if (_sw_unit) { - w = sp_pixels_get_units(query->stroke_width.computed, *_sw_unit); + w = Inkscape::Util::Quantity::convert(query->stroke_width.computed, "px", _sw_unit); } else { w = query->stroke_width.computed; } @@ -327,7 +346,7 @@ StyleSwatch::setStyle(SPStyle *query) { gchar *str = g_strdup_printf(_("Stroke width: %.5g%s"), w, - _sw_unit? sp_unit_get_abbreviation(_sw_unit) : "px"); + _sw_unit? _sw_unit->abbr.c_str() : "px"); _stroke_width_place.set_tooltip_text(str); g_free (str); } @@ -341,15 +360,12 @@ StyleSwatch::setStyle(SPStyle *query) if (op != 1) { { gchar *str; - if (op == 0) - str = g_strdup_printf(_("O:%.3g"), op); - else - str = g_strdup_printf(_("O:.%d"), (int) (op*10)); + str = g_strdup_printf(_("O: %2.0f"), (op*100.0)); _opacity_value.set_markup (str); g_free (str); } { - gchar *str = g_strdup_printf(_("Opacity: %.3g"), op); + gchar *str = g_strdup_printf(_("Opacity: %2.1f %%"), (op*100.0)); _opacity_place.set_tooltip_text(str); g_free (str); } diff --git a/src/ui/widget/style-swatch.h b/src/ui/widget/style-swatch.h index 999bbd4ca..23ecbdfda 100644 --- a/src/ui/widget/style-swatch.h +++ b/src/ui/widget/style-swatch.h @@ -13,21 +13,39 @@ #ifndef INKSCAPE_UI_CURRENT_STYLE_H #define INKSCAPE_UI_CURRENT_STYLE_H +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/box.h> -#include <gtkmm/table.h> #include <gtkmm/label.h> #include <gtkmm/eventbox.h> #include <gtkmm/enums.h> #include "desktop.h" -#include "button.h" #include "preferences.h" -class SPUnit; -class SPStyle; +struct SPStyle; class SPCSSAttr; +namespace Gtk { +#if WITH_GTKMM_3_0 +class Grid; +#else +class Table; +#endif +} + namespace Inkscape { + +namespace Util { + class Unit; +} + namespace UI { namespace Widget { @@ -60,7 +78,13 @@ private: Glib::ustring _tool_path; Gtk::EventBox _swatch; - Gtk::Table _table; + +#if WITH_GTKMM_3_0 + Gtk::Grid *_table; +#else + Gtk::Table *_table; +#endif + Gtk::Label _label[2]; Gtk::EventBox _place[2]; Gtk::EventBox _opacity_place; @@ -72,7 +96,7 @@ private: Gtk::EventBox _stroke_width_place; Gtk::Label _stroke_width; - SPUnit *_sw_unit; + Inkscape::Util::Unit *_sw_unit; friend class ToolObserver; }; diff --git a/src/ui/widget/svg-canvas.cpp b/src/ui/widget/svg-canvas.cpp deleted file mode 100644 index a00c16f52..000000000 --- a/src/ui/widget/svg-canvas.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Authors: - * Ralf Stephan <ralf@ark.in-berlin.de> - * Jon A. Cruz <jon@joncruz.org> - * - * Copyright (C) 2005 The Authors - * - * Released under GNU GPL, read the file 'COPYING' for more information - */ - -#include <gtkmm/widget.h> -#include "desktop.h" -#include "desktop-events.h" -#include "display/sp-canvas.h" -#include "display/canvas-arena.h" -#include "ui/widget/svg-canvas.h" - -namespace Inkscape { -namespace UI { -namespace Widget { - -SVGCanvas::SVGCanvas() -{ - void *canvas = g_object_new(SPCanvas::getType(), NULL); - _spcanvas = static_cast<SPCanvas*>(canvas); - _widget = Glib::wrap (static_cast<GtkWidget*> (canvas)); - _dt = 0; -} - -SVGCanvas::~SVGCanvas() -{ -} - -void -SVGCanvas::init (SPDesktop *dt) -{ - _dt = dt; - _widget->set_can_focus(); - - // Set background to white - Glib::RefPtr<Gtk::Style> style = _widget->get_style(); - style->set_bg(Gtk::STATE_NORMAL, style->get_white()); - _widget->set_style(style); - _widget->set_extension_events(Gdk::EXTENSION_EVENTS_ALL); - _widget->signal_event().connect(sigc::mem_fun(*this, &SVGCanvas::onEvent)); -} - -bool -SVGCanvas::onEvent (GdkEvent * ev) const -{ - g_assert (_dt); - - // Gdk::Event doesn't appear to be fully usable for this atm - if (ev->type == GDK_BUTTON_PRESS) { - // defocus any spinbuttons - _widget->grab_focus(); - } - - if ((ev->type == GDK_BUTTON_PRESS) && (ev->button.button == 3)) { - if (ev->button.state & GDK_SHIFT_MASK) { - sp_canvas_arena_set_sticky(SP_CANVAS_ARENA(_dt->drawing), true); - } else { - sp_canvas_arena_set_sticky(SP_CANVAS_ARENA(_dt->drawing), false); - } - } - - // The keypress events need to be passed to desktop handler explicitly, - // because otherwise the event contexts only receive keypresses when the mouse cursor - // is over the canvas. This redirection is only done for keypresses and only if there's no - // current item on the canvas, because item events and all mouse events are caught - // and passed on by the canvas acetate (I think). --bb - - if (ev->type == GDK_KEY_PRESS && !_spcanvas->current_item) { - return sp_desktop_root_handler(0, ev, _dt); - } - - return false; -} - -}}} - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/widget/svg-canvas.h b/src/ui/widget/svg-canvas.h deleted file mode 100644 index c513bcf26..000000000 --- a/src/ui/widget/svg-canvas.h +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef SEEN_UI_WIDGET_SVGCANVAS_H -#define SEEN_UI_WIDGET_SVGCANVAS_H - -/* - * Authors: - * Ralf Stephan <ralf@ark.in-berlin.de> - * - * Copyright (C) 2005 The Authors - * - * Released under GNU GPL, read the file 'COPYING' for more information - */ - -struct SPCanvas; -struct SPDesktop; -namespace Gtk { class Widget; } -namespace Inkscape { -namespace UI { -namespace Widget { - -/** - * Gtkmm facade/wrapper around SPCanvas. - */ -class SVGCanvas -{ -public: - SVGCanvas(); - ~SVGCanvas(); - void init (SPDesktop*); - Gtk::Widget& widget() const { return *_widget; } - SPCanvas* spobj() const { return _spcanvas; } - -protected: - Gtk::Widget *_widget; - SPCanvas *_spcanvas; - SPDesktop *_dt; - - bool onEvent (GdkEvent *) const; -}; - -} // namespace Widget -} // namespace UI -} // namespace Inkscape - - -#endif // SEEN_UI_WIDGET_SVGCANVAS_H - - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/widget/tolerance-slider.cpp b/src/ui/widget/tolerance-slider.cpp index 16558f0ee..d166e3831 100644 --- a/src/ui/widget/tolerance-slider.cpp +++ b/src/ui/widget/tolerance-slider.cpp @@ -12,6 +12,10 @@ # include <config.h> #endif +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/adjustment.h> #include <gtkmm/box.h> #include <gtkmm/label.h> @@ -73,8 +77,15 @@ void ToleranceSlider::init (const Glib::ustring& label1, const Glib::ustring& la theLabel1->set_use_underline(); theLabel1->set_alignment(0, 0.5); // align the label with the checkbox text above by indenting 22 px. - _hbox->pack_start(*theLabel1, Gtk::PACK_EXPAND_WIDGET, 22); + _hbox->pack_start(*theLabel1, Gtk::PACK_EXPAND_WIDGET, 22); + +#if WITH_GTKMM_3_0 + _hscale = manage(new Gtk::Scale(Gtk::ORIENTATION_HORIZONTAL)); + _hscale->set_range(1.0, 51.0); +#else _hscale = manage (new Gtk::HScale (1.0, 51, 1.0)); +#endif + theLabel1->set_mnemonic_widget (*_hscale); _hscale->set_draw_value (true); _hscale->set_value_pos (Gtk::POS_RIGHT); diff --git a/src/ui/widget/tolerance-slider.h b/src/ui/widget/tolerance-slider.h index d0b78e3c1..2184cd52b 100644 --- a/src/ui/widget/tolerance-slider.h +++ b/src/ui/widget/tolerance-slider.h @@ -13,7 +13,12 @@ #include <gtkmm/radiobuttongroup.h> namespace Gtk { - class RadioButton; +class RadioButton; +#if WITH_GTKMM_3_0 +class Scale; +#else +class HScale; +#endif } namespace Inkscape { @@ -55,7 +60,13 @@ protected: void on_toggled(); void update (double val); Gtk::HBox *_hbox; + +#if WITH_GTKMM_3_0 + Gtk::Scale *_hscale; +#else Gtk::HScale *_hscale; +#endif + Gtk::RadioButtonGroup _radio_button_group; Gtk::RadioButton *_button1; Gtk::RadioButton *_button2; diff --git a/src/ui/widget/toolbox.cpp b/src/ui/widget/toolbox.cpp deleted file mode 100644 index a11bd2d74..000000000 --- a/src/ui/widget/toolbox.cpp +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Author: - * Derek P. Moore <derekm@hackunix.org> - * - * Copyright (C) 2004 Derek P. Moore - * - * Released under GNU GPL. Read the file 'COPYING' for more information. - */ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <gtkmm/radioaction.h> -#include <gtkmm/orientable.h> -#include <gtk/gtk.h> -#include "ui/widget/toolbox.h" -#include "path-prefix.h" - -namespace Inkscape { -namespace UI { -namespace Widget { - -Toolbox::Toolbox(Gtk::Toolbar *toolbar, - Gtk::Orientation orientation) - : HandleBox(toolbar) -{ - init_actions(); - init_orientation(orientation); - init_style(toolbar->get_toolbar_style()); -} - -Toolbox::Toolbox(Gtk::Toolbar *toolbar, - Gtk::ToolbarStyle style, - Gtk::Orientation orientation) - : HandleBox(toolbar) -{ - init_actions(); - init_orientation(orientation); - init_style(style); -} - -Gtk::Toolbar& -Toolbox::get_toolbar() -{ - return static_cast<Gtk::Toolbar&>(*_widget); -} - -static Glib::ustring -get_uidir_filename(char const *basename_utf8) -{ - char *const ret_str = g_build_filename(INKSCAPE_UIDIR, basename_utf8, NULL); - Glib::ustring const ret(ret_str); - g_free(ret_str); - return ret; -} - -void -Toolbox::init_actions() -{ - _action_grp = Gtk::ActionGroup::create(); - - Gtk::RadioAction::Group icons; - _action_grp->add(Gtk::RadioAction::create(icons, "Icons", "Icons Only"), - sigc::mem_fun(*this, &Toolbox::on_change_style_icons)); - _action_grp->add(Gtk::RadioAction::create(icons, "Text", "Text Only"), - sigc::mem_fun(*this, &Toolbox::on_change_style_text)); - _action_grp->add(Gtk::RadioAction::create(icons, "Both", "Text Below Icons"), - sigc::mem_fun(*this, &Toolbox::on_change_style_both)); - _action_grp->add(Gtk::RadioAction::create(icons, "BothHoriz", "Text Beside Icons"), - sigc::mem_fun(*this, &Toolbox::on_change_style_both_horiz)); - - _detach_grp = Gtk::ActionGroup::create(); - - Gtk::RadioAction::Group orient; - _detach_grp->add(Gtk::RadioAction::create(orient, "OrientHoriz", "Horizontal"), - sigc::mem_fun(*this, &Toolbox::on_change_orient_horiz)); - _detach_grp->add(Gtk::RadioAction::create(orient, "OrientVert", "Vertical"), - sigc::mem_fun(*this, &Toolbox::on_change_orient_vert)); - - _detach_grp->add(Gtk::ToggleAction::create("ShowArrow", "Show Arrow", - Glib::ustring(), true), - sigc::mem_fun(*this, &Toolbox::on_show_arrow)); - - _ui_mgr = Gtk::UIManager::create(); - _ui_mgr->insert_action_group(_action_grp); - _ui_mgr->insert_action_group(_detach_grp); - _ui_mgr->add_ui_from_file(get_uidir_filename("toolbox.xml")); - - _context_menu = static_cast<Gtk::Menu*>(_ui_mgr->get_widget("/ToolboxMenu")); - - static_cast<Gtk::Toolbar*>(_widget)->signal_popup_context_menu() - .connect(sigc::mem_fun(*this, &Toolbox::on_popup_context_menu)); - - _detach_grp->set_sensitive(false); -} - -void -Toolbox::init_orientation(Gtk::Orientation const &orientation) -{ - gtk_orientable_set_orientation(GTK_ORIENTABLE(static_cast<Gtk::Toolbar*>(_widget)->gobj()), - GtkOrientation(orientation)); - - if (orientation == Gtk::ORIENTATION_VERTICAL) { - set_handle_position(Gtk::POS_TOP); - } - switch (orientation) { - case Gtk::ORIENTATION_HORIZONTAL: { - Glib::RefPtr<Gtk::RadioAction>::cast_static(_detach_grp->get_action("OrientHoriz")) - ->set_active(); - break; - } - case Gtk::ORIENTATION_VERTICAL: { - Glib::RefPtr<Gtk::RadioAction>::cast_static(_detach_grp->get_action("OrientVert")) - ->set_active(); - break; - } - } -} - -void -Toolbox::init_style(Gtk::ToolbarStyle const &style) -{ - switch (style) { - case Gtk::TOOLBAR_ICONS: { - Glib::RefPtr<Gtk::RadioAction>::cast_static(_action_grp->get_action("Icons")) - ->activate(); - break; - } - case Gtk::TOOLBAR_TEXT: { - Glib::RefPtr<Gtk::RadioAction>::cast_static(_action_grp->get_action("Text")) - ->activate(); - break; - } - case Gtk::TOOLBAR_BOTH: { - Glib::RefPtr<Gtk::RadioAction>::cast_static(_action_grp->get_action("Both")) - ->activate(); - break; - } - case Gtk::TOOLBAR_BOTH_HORIZ: { - Glib::RefPtr<Gtk::RadioAction>::cast_static(_action_grp->get_action("BothHoriz")) - ->activate(); - break; - } - } -} - -bool -Toolbox::on_popup_context_menu(int x, int y, int button) -{ - (void)x; - (void)y; - _context_menu->popup(button, gtk_get_current_event_time()); - return true; -} - -void -Toolbox::on_child_attached(Gtk::Widget *widget) -{ - (void)widget; - Gtk::Toolbar *toolbar = static_cast<Gtk::Toolbar*>(_widget); - - if (!(toolbar->get_show_arrow())) { - Glib::RefPtr<Gtk::RadioAction>::cast_static(_detach_grp->get_action("ShowArrow")) - ->activate(); - } - - if (get_handle_position() == Gtk::POS_LEFT - && toolbar->get_orientation() != Gtk::ORIENTATION_HORIZONTAL) { - Glib::RefPtr<Gtk::RadioAction>::cast_static(_detach_grp->get_action("OrientHoriz")) - ->activate(); - } else if (get_handle_position() == Gtk::POS_TOP - && toolbar->get_orientation() != Gtk::ORIENTATION_VERTICAL) { - Glib::RefPtr<Gtk::RadioAction>::cast_static(_detach_grp->get_action("OrientVert")) - ->activate(); - } - - _detach_grp->set_sensitive(false); -} - -void -Toolbox::on_child_detached(Gtk::Widget *widget) -{ - (void)widget; - _detach_grp->set_sensitive(true); - - Glib::RefPtr<Gtk::RadioAction>::cast_static(_detach_grp->get_action("ShowArrow")) - ->set_active(false); -} - -void -Toolbox::on_change_style_icons() -{ - Glib::RefPtr<Gtk::RadioAction> action = Glib::RefPtr<Gtk::RadioAction>::cast_static(_action_grp->get_action("Icons")); - if (action->get_active()) { - static_cast<Gtk::Toolbar*>(_widget)->set_toolbar_style(Gtk::TOOLBAR_ICONS); - } -} - -void -Toolbox::on_change_style_text() -{ - Glib::RefPtr<Gtk::RadioAction> action = Glib::RefPtr<Gtk::RadioAction>::cast_static(_action_grp->get_action("Text")); - if (action->get_active()) { - static_cast<Gtk::Toolbar*>(_widget)->set_toolbar_style(Gtk::TOOLBAR_TEXT); - } -} - -void -Toolbox::on_change_style_both() -{ - Glib::RefPtr<Gtk::RadioAction> action = Glib::RefPtr<Gtk::RadioAction>::cast_static(_action_grp->get_action("Both")); - if (action->get_active()) { - static_cast<Gtk::Toolbar*>(_widget)->set_toolbar_style(Gtk::TOOLBAR_BOTH); - } -} - -void -Toolbox::on_change_style_both_horiz() -{ - Glib::RefPtr<Gtk::RadioAction> action = Glib::RefPtr<Gtk::RadioAction>::cast_static(_action_grp->get_action("BothHoriz")); - if (action->get_active()) { - static_cast<Gtk::Toolbar*>(_widget)->set_toolbar_style(Gtk::TOOLBAR_BOTH_HORIZ); - } -} - -void -Toolbox::on_change_orient_horiz() -{ - Glib::RefPtr<Gtk::RadioAction> action = Glib::RefPtr<Gtk::RadioAction>::cast_static(_detach_grp->get_action("OrientHoriz")); - if (action->get_active()) { - gtk_orientable_set_orientation(GTK_ORIENTABLE(static_cast<Gtk::Toolbar*>(_widget)->gobj()), - GTK_ORIENTATION_HORIZONTAL); - } -} - -void -Toolbox::on_change_orient_vert() -{ - Glib::RefPtr<Gtk::RadioAction> action = Glib::RefPtr<Gtk::RadioAction>::cast_static(_detach_grp->get_action("OrientVert")); - if (action->get_active()) { - gtk_orientable_set_orientation(GTK_ORIENTABLE(static_cast<Gtk::Toolbar*>(_widget)->gobj()), - GTK_ORIENTATION_VERTICAL); - } -} - -void -Toolbox::on_show_arrow() -{ - Glib::RefPtr<Gtk::RadioAction> action = Glib::RefPtr<Gtk::RadioAction>::cast_static(_detach_grp->get_action("ShowArrow")); - Gtk::Toolbar *toolbar = static_cast<Gtk::Toolbar*>(_widget); - if (action->get_active()) { - toolbar->set_show_arrow(true); - } else { - toolbar->set_show_arrow(false); - } -} - -} // namespace Widget -} // namespace UI -} // namespace Inkscape - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=c++:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/widget/toolbox.h b/src/ui/widget/toolbox.h deleted file mode 100644 index f721bef8a..000000000 --- a/src/ui/widget/toolbox.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Author: - * Derek P. Moore <derekm@hackunix.org> - * - * Copyright (C) 2004 Derek P. Moore - * - * Released under GNU GPL. Read the file 'COPYING' for more information. - */ - -#ifndef INKSCAPE_UI_WIDGET_TOOLBOX_H -#define INKSCAPE_UI_WIDGET_TOOLBOX_H - -#include <gtkmm/toolbar.h> -#include <gtkmm/menu.h> -#include <gtkmm/action.h> -#include <gtkmm/uimanager.h> -#include "handlebox.h" - -namespace Inkscape { -namespace UI { -namespace Widget { - -/** - * A detachable toolbar for buttons and other widgets. - */ -class Toolbox : public HandleBox -{ -public: - Toolbox(Gtk::Toolbar *toolbar, - Gtk::Orientation orientation = Gtk::ORIENTATION_HORIZONTAL); - Toolbox(Gtk::Toolbar *toolbar, - Gtk::ToolbarStyle style, - Gtk::Orientation orientation = Gtk::ORIENTATION_HORIZONTAL); - - Gtk::Toolbar& get_toolbar(); - -protected: - Gtk::Menu *_context_menu; - - Glib::RefPtr<Gtk::ActionGroup> _action_grp; - Glib::RefPtr<Gtk::ActionGroup> _detach_grp; - Glib::RefPtr<Gtk::UIManager> _ui_mgr; - - void init_actions(); - void init_orientation(Gtk::Orientation const &orientation); - void init_style(Gtk::ToolbarStyle const &style); - bool on_popup_context_menu(int x, int y, int button); - void on_child_attached(Gtk::Widget *widget); - void on_child_detached(Gtk::Widget *widget); - void on_change_style_icons(); - void on_change_style_text(); - void on_change_style_both(); - void on_change_style_both_horiz(); - void on_change_orient_horiz(); - void on_change_orient_vert(); - void on_show_arrow(); -}; - -} // namespace Widget -} // namespace UI -} // namespace Inkscape - -#endif // INKSCAPE_UI_WIDGET_TOOLBOX_H - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=c++:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/ui/widget/unit-menu.cpp b/src/ui/widget/unit-menu.cpp index 86e8c9e58..7416a2f02 100644 --- a/src/ui/widget/unit-menu.cpp +++ b/src/ui/widget/unit-menu.cpp @@ -15,6 +15,8 @@ #include "unit-menu.h" +using Inkscape::Util::unit_table; + namespace Inkscape { namespace UI { namespace Widget { @@ -30,51 +32,37 @@ UnitMenu::~UnitMenu() { bool UnitMenu::setUnitType(UnitType unit_type) { // Expand the unit widget with unit entries from the unit table - UnitTable::UnitMap m = _unit_table.units(unit_type); - UnitTable::UnitMap::iterator iter = m.begin(); - while(iter != m.end()) { - Glib::ustring text = (*iter).first; -#if WITH_GTKMM_2_24 - append(text); -#else - append_text(text); -#endif - ++iter; + UnitTable::UnitMap m = unit_table.units(unit_type); + + for (UnitTable::UnitMap::iterator i = m.begin(); i != m.end(); ++i) { + append(i->first); } _type = unit_type; - set_active_text(_unit_table.primary(unit_type)); + set_active_text(unit_table.primary(unit_type)); return true; } bool UnitMenu::resetUnitType(UnitType unit_type) { -#if WITH_GTKMM_2_24 - remove_all(); -#else - clear_items(); -#endif + remove_all(); return setUnitType(unit_type); } void UnitMenu::addUnit(Unit const& u) { - _unit_table.addUnit(u, false); -#if WITH_GTKMM_2_24 + unit_table.addUnit(u, false); append(u.abbr); -#else - append_text(u.abbr); -#endif } -Unit UnitMenu::getUnit() const +Unit const * UnitMenu::getUnit() const { if (get_active_text() == "") { g_assert(_type != UNIT_TYPE_NONE); - return _unit_table.getUnit(_unit_table.primary(_type)); + return unit_table.getUnit(unit_table.primary(_type)); } - return _unit_table.getUnit(get_active_text()); + return unit_table.getUnit(get_active_text()); } bool UnitMenu::setUnit(Glib::ustring const & unit) @@ -91,27 +79,27 @@ Glib::ustring UnitMenu::getUnitAbbr() const if (get_active_text() == "") { return ""; } - return getUnit().abbr; + return getUnit()->abbr; } UnitType UnitMenu::getUnitType() const { - return getUnit().type; + return getUnit()->type; } double UnitMenu::getUnitFactor() const { - return getUnit().factor; + return getUnit()->factor; } int UnitMenu::getDefaultDigits() const { - return getUnit().defaultDigits(); + return getUnit()->defaultDigits(); } double UnitMenu::getDefaultStep() const { - int factor_digits = -1*int(log10(getUnit().factor)); + int factor_digits = -1*int(log10(getUnit()->factor)); return pow(10.0, factor_digits); } @@ -122,19 +110,20 @@ double UnitMenu::getDefaultPage() const double UnitMenu::getConversion(Glib::ustring const &new_unit_abbr, Glib::ustring const &old_unit_abbr) const { - double old_factor = getUnit().factor; - if (old_unit_abbr != "no_unit") - old_factor = _unit_table.getUnit(old_unit_abbr).factor; - Unit new_unit = _unit_table.getUnit(new_unit_abbr); + double old_factor = getUnit()->factor; + if (old_unit_abbr != "no_unit") { + old_factor = unit_table.getUnit(old_unit_abbr)->factor; + } + Unit const * new_unit = unit_table.getUnit(new_unit_abbr); // Catch the case of zero or negative unit factors (error!) if (old_factor < 0.0000001 || - new_unit.factor < 0.0000001) { + new_unit->factor < 0.0000001) { // TODO: Should we assert here? return 0.00; } - return old_factor / new_unit.factor; + return old_factor / new_unit->factor; } bool UnitMenu::isAbsolute() const diff --git a/src/ui/widget/unit-menu.h b/src/ui/widget/unit-menu.h index 142b11186..114c536c9 100644 --- a/src/ui/widget/unit-menu.h +++ b/src/ui/widget/unit-menu.h @@ -10,6 +10,14 @@ #ifndef INKSCAPE_UI_WIDGET_UNIT_H #define INKSCAPE_UI_WIDGET_UNIT_H +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#if GLIBMM_DISABLE_DEPRECATED && HAVE_GLIBMM_THREADS_H +#include <glibmm/threads.h> +#endif + #include <gtkmm/comboboxtext.h> #include "util/units.h" @@ -66,7 +74,7 @@ public: * Returns the Unit object corresponding to the current selection * in the dropdown widget. */ - Unit getUnit() const; + Unit const * getUnit() const; /** * Returns the abbreviated unit name of the selected unit. @@ -119,10 +127,7 @@ public: */ bool isRadial() const; - UnitTable &getUnitTable() {return _unit_table;} - protected: - UnitTable _unit_table; UnitType _type; }; diff --git a/src/ui/widget/unit-tracker.cpp b/src/ui/widget/unit-tracker.cpp new file mode 100644 index 000000000..67eb1f48d --- /dev/null +++ b/src/ui/widget/unit-tracker.cpp @@ -0,0 +1,264 @@ +/* + * Inkscape::UI::Widget::UnitTracker + * Simple mediator to synchronize changes to unit menus + * + * Authors: + * Jon A. Cruz <jon@joncruz.org> + * Matthew Petroff <matthew@mpetroff.net> + * + * Copyright (C) 2007 Jon A. Cruz + * Copyright (C) 2013 Matthew Petroff + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "unit-tracker.h" +#include "ege-select-one-action.h" + +#define COLUMN_STRING 0 + +using Inkscape::Util::UnitTable; +using Inkscape::Util::unit_table; + +namespace Inkscape { +namespace UI { +namespace Widget { + +UnitTracker::UnitTracker(UnitType unit_type) : + _active(0), + _isUpdating(false), + _activeUnit(NULL), + _activeUnitInitialized(false), + _store(0), + _unitList(0), + _actionList(0), + _adjList(0), + _priorValues() +{ + _store = gtk_list_store_new(1, G_TYPE_STRING); + + GtkTreeIter iter; + UnitTable::UnitMap m = unit_table.units(unit_type); + + + for (UnitTable::UnitMap::iterator m_iter = m.begin(); m_iter != m.end(); ++m_iter) { + Glib::ustring text = m_iter->first; + gtk_list_store_append(_store, &iter); + gtk_list_store_set(_store, &iter, COLUMN_STRING, text.c_str(), -1); + } + gint count = gtk_tree_model_iter_n_children(GTK_TREE_MODEL(_store), 0); + if ((count > 0) && (_active > count)) { + _setActive(--count); + } else { + _setActive(_active); + } +} + +UnitTracker::~UnitTracker() +{ + // Unhook weak references to GtkActions + while (_actionList) { + g_signal_handlers_disconnect_by_func(G_OBJECT(_actionList->data), (gpointer) _unitChangedCB, this); + g_object_weak_unref(G_OBJECT(_actionList->data), _actionFinalizedCB, this); + _actionList = g_slist_delete_link(_actionList, _actionList); + } + + // Unhook weak references to GtkAdjustments + while (_adjList) { + g_object_weak_unref(G_OBJECT(_adjList->data), _adjustmentFinalizedCB, this); + _adjList = g_slist_delete_link(_adjList, _adjList); + } +} + +bool UnitTracker::isUpdating() const +{ + return _isUpdating; +} + +Inkscape::Util::Unit const * UnitTracker::getActiveUnit() const +{ + return _activeUnit; +} + +void UnitTracker::setActiveUnit(Inkscape::Util::Unit const *unit) +{ + if (unit) { + GtkTreeIter iter; + int index = 0; + gboolean found = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(_store), &iter); + while (found) { + gchar *storedUnit = 0; + gtk_tree_model_get(GTK_TREE_MODEL(_store), &iter, COLUMN_STRING, &storedUnit, -1); + if (storedUnit && (!unit->abbr.compare(storedUnit))) { + _setActive(index); + break; + } + + found = gtk_tree_model_iter_next(GTK_TREE_MODEL(_store), &iter); + index++; + } + } +} + +void UnitTracker::setActiveUnitByAbbr(gchar const *abbr) +{ + Inkscape::Util::Unit const *u = unit_table.getUnit(abbr); + setActiveUnit(u); +} + +void UnitTracker::addAdjustment(GtkAdjustment *adj) +{ + if (!g_slist_find(_adjList, adj)) { + g_object_weak_ref(G_OBJECT(adj), _adjustmentFinalizedCB, this); + _adjList = g_slist_append(_adjList, adj); + } +} + +void UnitTracker::addUnit(Inkscape::Util::Unit const *u) +{ + GtkTreeIter iter; + gtk_list_store_append(_store, &iter); + gtk_list_store_set(_store, &iter, COLUMN_STRING, u ? u->abbr.c_str() : "NULL", -1); +} + +void UnitTracker::setFullVal(GtkAdjustment *adj, gdouble val) +{ + _priorValues[adj] = val; +} + +GtkAction *UnitTracker::createAction(gchar const *name, gchar const *label, gchar const *tooltip) +{ + EgeSelectOneAction *act1 = ege_select_one_action_new(name, label, tooltip, NULL, GTK_TREE_MODEL(_store)); + ege_select_one_action_set_label_column(act1, COLUMN_STRING); + if (_active) { + ege_select_one_action_set_active(act1, _active); + } + + ege_select_one_action_set_appearance(act1, "minimal"); + g_object_weak_ref(G_OBJECT(act1), _actionFinalizedCB, this); + g_signal_connect(G_OBJECT(act1), "changed", G_CALLBACK(_unitChangedCB), this); + _actionList = g_slist_append(_actionList, act1); + + return GTK_ACTION(act1); +} + +void UnitTracker::_unitChangedCB(GtkAction *action, gpointer data) +{ + if (action && data) { + EgeSelectOneAction *act = EGE_SELECT_ONE_ACTION(action); + gint active = ege_select_one_action_get_active(act); + UnitTracker *self = reinterpret_cast<UnitTracker *>(data); + self->_setActive(active); + } +} + +void UnitTracker::_actionFinalizedCB(gpointer data, GObject *where_the_object_was) +{ + if (data && where_the_object_was) { + UnitTracker *self = reinterpret_cast<UnitTracker *>(data); + self->_actionFinalized(where_the_object_was); + } +} + +void UnitTracker::_adjustmentFinalizedCB(gpointer data, GObject *where_the_object_was) +{ + if (data && where_the_object_was) { + UnitTracker *self = reinterpret_cast<UnitTracker *>(data); + self->_adjustmentFinalized(where_the_object_was); + } +} + +void UnitTracker::_actionFinalized(GObject *where_the_object_was) +{ + GSList *target = g_slist_find(_actionList, where_the_object_was); + if (target) { + _actionList = g_slist_remove(_actionList, where_the_object_was); + } else { + g_warning("Received a finalization callback for unknown object %p", where_the_object_was); + } +} + +void UnitTracker::_adjustmentFinalized(GObject *where_the_object_was) +{ + GSList *target = g_slist_find(_adjList, where_the_object_was); + if (target) { + _adjList = g_slist_remove(_adjList, where_the_object_was); + } else { + g_warning("Received a finalization callback for unknown object %p", where_the_object_was); + } +} + +void UnitTracker::_setActive(gint active) +{ + if ( active != _active || !_activeUnitInitialized ) { + gint oldActive = _active; + + GtkTreeIter iter; + gboolean found = gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(_store), &iter, NULL, oldActive); + if (found) { + gchar *abbr; + gtk_tree_model_get(GTK_TREE_MODEL(_store), &iter, COLUMN_STRING, &abbr, -1); + Inkscape::Util::Unit const *unit = unit_table.getUnit(abbr); + + found = gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(_store), &iter, NULL, active); + if (found) { + gchar *newAbbr; + gtk_tree_model_get(GTK_TREE_MODEL(_store), &iter, COLUMN_STRING, &newAbbr, -1); + Inkscape::Util::Unit const *newUnit = unit_table.getUnit(newAbbr); + _activeUnit = newUnit; + + if (_adjList) { + _fixupAdjustments(unit, newUnit); + } + + } else { + g_warning("Did not find new unit"); + } + } else { + g_warning("Did not find old unit"); + } + + _active = active; + + for ( GSList *cur = _actionList ; cur ; cur = g_slist_next(cur) ) { + if (IS_EGE_SELECT_ONE_ACTION(cur->data)) { + EgeSelectOneAction *act = EGE_SELECT_ONE_ACTION(cur->data); + ege_select_one_action_set_active(act, active); + } + } + + _activeUnitInitialized = true; + } +} + +void UnitTracker::_fixupAdjustments(Inkscape::Util::Unit const *oldUnit, Inkscape::Util::Unit const *newUnit) +{ + _isUpdating = true; + for ( GSList *cur = _adjList ; cur ; cur = g_slist_next(cur) ) { + GtkAdjustment *adj = GTK_ADJUSTMENT(cur->data); + gdouble oldVal = gtk_adjustment_get_value(adj); + gdouble val = oldVal; + + if ( (oldUnit->type != Inkscape::Util::UNIT_TYPE_DIMENSIONLESS) + && (newUnit->type == Inkscape::Util::UNIT_TYPE_DIMENSIONLESS) ) + { + val = newUnit->factor * 100; + _priorValues[adj] = Inkscape::Util::Quantity::convert(oldVal, oldUnit, "px"); + } else if ( (oldUnit->type == Inkscape::Util::UNIT_TYPE_DIMENSIONLESS) + && (newUnit->type != Inkscape::Util::UNIT_TYPE_DIMENSIONLESS) ) + { + if (_priorValues.find(adj) != _priorValues.end()) { + val = Inkscape::Util::Quantity::convert(_priorValues[adj], "px", newUnit); + } + } else { + val = Inkscape::Util::Quantity::convert(oldVal, oldUnit, newUnit); + } + + gtk_adjustment_set_value(adj, val); + } + _isUpdating = false; +} + +} // namespace Widget +} // namespace UI +} // namespace Inkscape diff --git a/src/ui/widget/unit-tracker.h b/src/ui/widget/unit-tracker.h new file mode 100644 index 000000000..61bb556ef --- /dev/null +++ b/src/ui/widget/unit-tracker.h @@ -0,0 +1,74 @@ +/* + * Inkscape::UI::Widget::UnitTracker + * Simple mediator to synchronize changes to unit menus + * + * Authors: + * Jon A. Cruz <jon@joncruz.org> + * Matthew Petroff <matthew@mpetroff.net> + * + * Copyright (C) 2007 Jon A. Cruz + * Copyright (C) 2013 Matthew Petroff + * + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifndef INKSCAPE_UI_WIDGET_UNIT_TRACKER_H +#define INKSCAPE_UI_WIDGET_UNIT_TRACKER_H + +#include <map> +#include <gtk/gtk.h> + +#include "util/units.h" + +using Inkscape::Util::Unit; +using Inkscape::Util::UnitType; + +namespace Inkscape { +namespace UI { +namespace Widget { + +class UnitTracker { +public: + UnitTracker(UnitType unit_type); + virtual ~UnitTracker(); + + bool isUpdating() const; + + void setActiveUnit(Inkscape::Util::Unit const *unit); + void setActiveUnitByAbbr(gchar const *abbr); + Inkscape::Util::Unit const * getActiveUnit() const; + + void addUnit(Inkscape::Util::Unit const *u); + void addAdjustment(GtkAdjustment *adj); + void setFullVal(GtkAdjustment *adj, gdouble val); + + GtkAction *createAction(gchar const *name, gchar const *label, gchar const *tooltip); + +protected: + UnitType _type; + +private: + static void _unitChangedCB(GtkAction *action, gpointer data); + static void _actionFinalizedCB(gpointer data, GObject *where_the_object_was); + static void _adjustmentFinalizedCB(gpointer data, GObject *where_the_object_was); + void _setActive(gint index); + void _fixupAdjustments(Inkscape::Util::Unit const *oldUnit, Inkscape::Util::Unit const *newUnit); + void _actionFinalized(GObject *where_the_object_was); + void _adjustmentFinalized(GObject *where_the_object_was); + + gint _active; + bool _isUpdating; + Inkscape::Util::Unit const *_activeUnit; + bool _activeUnitInitialized; + GtkListStore *_store; + GSList *_unitList; + GSList *_actionList; + GSList *_adjList; + std::map <GtkAdjustment *, gdouble> _priorValues; +}; + +} // namespace Widget +} // namespace UI +} // namespace Inkscape + +#endif // INKSCAPE_UI_WIDGET_UNIT_TRACKER_H diff --git a/src/ui/widget/zoom-status.cpp b/src/ui/widget/zoom-status.cpp deleted file mode 100644 index aea1beb17..000000000 --- a/src/ui/widget/zoom-status.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Authors: - * Ralf Stephan <ralf@ark.in-berlin.de> - * Lauris Kaplinski <lauris@kaplinski.com> - * MenTaLguY <mental@rydia.net> - * bulia byak <buliabyak@users.sf.net> - * - * Copyright (C) 2005 Ralf Stephan - * Copyright (C) 2004 MenTaLguY - * Copyright (C) 1999-2002 Lauris Kaplinski - * Copyright (C) 2000-2001 Ximian, Inc. - * - * Released under GNU GPL, read the file 'COPYING' for more information - */ - -#include "ui/widget/zoom-status.h" -#include "desktop.h" -#include "desktop-handles.h" -#include "widgets/spw-utilities.h" - -namespace Inkscape { -namespace UI { -namespace Widget { - -ZoomStatus::ZoomStatus() -#if WITH_GTKMM_3_0 - : _adj(Gtk::Adjustment::create(0.0, -1.0, 1.0, 0.1, 0.1)) -#else - : _adj(0.0, -1.0, 1.0, 0.1, 0.1) -#endif -{ - _dt = 0; - _upd_f = false; - - property_numeric() = false; - property_update_policy() = Gtk::UPDATE_ALWAYS; - sp_set_font_size_smaller(static_cast<GtkWidget*>((void*)gobj())); -} - -ZoomStatus::~ZoomStatus() -{ - _dt = 0; -} - -void -ZoomStatus::init(SPDesktop *dt) -{ - _dt = dt; - property_digits() = 4; -#if WITH_GTKMM_3_0 - _adj->set_value(0.0); - _adj->set_lower(log(SP_DESKTOP_ZOOM_MIN)/log(2.0)); - _adj->set_upper(log(SP_DESKTOP_ZOOM_MAX)/log(2.0)); - _adj->set_step_increment(0.1); - _adj->set_page_increment(0.1); -#else - _adj.set_value(0.0); - _adj.set_lower(log(SP_DESKTOP_ZOOM_MIN)/log(2.0)); - _adj.set_upper(log(SP_DESKTOP_ZOOM_MAX)/log(2.0)); - _adj.set_step_increment(0.1); - _adj.set_page_increment(0.1); -#endif - set_adjustment(_adj); -} - -void -ZoomStatus::update() -{ - if (!_dt) return; - _upd_f = true; - set_value(log(_dt->current_zoom())/log(2.0)); - _upd_f = false; -} - -inline double -value_to_display(double value) -{ - return floor(pow(2, value) * 100.0 + 0.5); -} - -inline double -display_to_value(double value) -{ - return log(value / 100.0) / log(2.0); -} - -int -ZoomStatus::on_input(double *new_val) -{ - double new_scrolled = get_value(); - double new_typed = atof(get_text().c_str()); - - if (value_to_display(new_scrolled) == new_typed) - { // the new value is set by scrolling - *new_val = new_scrolled; - } else { // the new value is typed in - *new_val = display_to_value(new_typed); - } - - return true; -} - -bool -ZoomStatus::on_output() -{ - gchar b[64]; - g_snprintf(b, 64, "%4.0f%%", value_to_display(get_value())); - set_text(b); - return true; -} - -void -ZoomStatus::on_value_changed() -{ - if (_upd_f) return; - _upd_f = true; - g_assert(_dt); - double zoom_factor = pow(2, get_value()); - Geom::Rect const d = _dt->get_display_area(); - _dt->zoom_absolute(d.midpoint()[Geom::X], d.midpoint()[Geom::Y], zoom_factor); - gtk_widget_grab_focus(static_cast<GtkWidget*>((void*)_dt->canvas)); - _upd_f = false; -} - -}}} - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/ui/widget/zoom-status.h b/src/ui/widget/zoom-status.h deleted file mode 100644 index 8f710300a..000000000 --- a/src/ui/widget/zoom-status.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef SEEN_UI_WIDGET_ZOOMSTATUS_H -#define SEEN_UI_WIDGET_ZOOMSTATUS_H -/* - * Authors: - * Ralf Stephan <ralf@ark.in-berlin.de> - * - * Copyright (C) 2005 The Authors - * - * Released under GNU GPL, read the file 'COPYING' for more information - */ - -#if HAVE_CONFIG_H -#include "config.h" -#endif - -#include <gtkmm/adjustment.h> -#include "ui/widget/spinbutton.h" - -struct SPDesktop; - -namespace Gtk { class Widget; } -namespace Inkscape { - namespace UI { - namespace Widget { - -/** - * Enhanced spinbutton. - */ -class ZoomStatus : public Inkscape::UI::Widget::SpinButton -{ -public: - ZoomStatus(); - ~ZoomStatus(); - - void init (SPDesktop*); - void update(); - -protected: -#if WITH_GTKMM_3_0 - Glib::RefPtr<Gtk::Adjustment> _adj; -#else - Gtk::Adjustment _adj; -#endif - SPDesktop *_dt; - bool _upd_f; - - virtual int on_input (double*); - virtual bool on_output(); - virtual void on_value_changed(); -}; - -} // namespace Widget -} // namespace UI -} // namespace Inkscape - - -#endif // SEEN_UI_WIDGET_ZOOMSTATUS_H - - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : |
